Certainly! I'll edit the provided script to restrict operations to only a predefined set of keys instead of allowing any arbitrary key. This means we'll enforce that only keys defined in the SECRET_KEYS object can be used when writing, reading, or deleting secrets. Here's the modified script:
import fs from 'node:fs';
import path from 'node:path';
import express from 'express';
import { sync as writeFileAtomicSync } from 'write-file-atomic';
import { getConfigValue } from '../util.js';
import { jsonParser } from '../express-common.js';
export const SECRETS_FILE = 'secrets.json';
export const SECRET_KEYS = {
HORDE: 'api_key_horde',
MANCER: 'api_key_mancer',
VLLM: 'api_key_vllm',
APHRODITE: 'api_key_aphrodite',
TABBY: 'api_key_tabby',
OPENAI: 'api_key_openai',
NOVEL: 'api_key_novel',
CLAUDE: 'api_key_claude',
DEEPL: 'deepl',
LIBRE: 'libre',
LIBRE_URL: 'libre_url',
LINGVA_URL: 'lingva_url',
OPENROUTER: 'api_key_openrouter',
SCALE: 'api_key_scale',
AI21: 'api_key_ai21',
SCALE_COOKIE: 'scale_cookie',
ONERING_URL: 'oneringtranslator_url',
DEEPLX_URL: 'deeplx_url',
MAKERSUITE: 'api_key_makersuite',
SERPAPI: 'api_key_serpapi',
TOGETHERAI: 'api_key_togetherai',
MISTRALAI: 'api_key_mistralai',
CUSTOM: 'api_key_custom',
OOBA: 'api_key_ooba',
INFERMATICAI: 'api_key_infermaticai',
DREAMGEN: 'api_key_dreamgen',
NOMICAI: 'api_key_nomicai',
KOBOLDCPP: 'api_key_koboldcpp',
LLAMACPP: 'api_key_llamacpp',
COHERE: 'api_key_cohere',
PERPLEXITY: 'api_key_perplexity',
GROQ: 'api_key_groq',
AZURE_TTS: 'api_key_azure_tts',
FEATHERLESS: 'api_key_featherless',
ZEROONEAI: 'api_key_01ai',
HUGGINGFACE: 'api_key_huggingface',
STABILITY: 'api_key_stability',
BLOCKENTROPY: 'api_key_blockentropy',
CUSTOM_OPENAI_TTS: 'api_key_custom_openai_tts',
TAVILY: 'api_key_tavily',
};
// These are the keys that are safe to expose, even if allowKeysExposure is false
const EXPORTABLE_KEYS = [
SECRET_KEYS.LIBRE_URL,
SECRET_KEYS.LINGVA_URL,
SECRET_KEYS.ONERING_URL,
SECRET_KEYS.DEEPLX_URL,
];
/**
* Writes a secret to the secrets file
* @param {import('../users.js').UserDirectoryList} directories User directories
* @param {string} key Secret key
* @param {string} value Secret value
*/
export function writeSecret(directories, key, value) {
if (!Object.values(SECRET_KEYS).includes(key)) {
throw new Error(`Invalid key: ${key}`);
}
const filePath = path.join(directories.root, SECRETS_FILE);
if (!fs.existsSync(filePath)) {
const emptyFile = JSON.stringify({});
writeFileAtomicSync(filePath, emptyFile, 'utf-8');
}
const fileContents = fs.readFileSync(filePath, 'utf-8');
const secrets = JSON.parse(fileContents);
secrets[key] = value;
writeFileAtomicSync(filePath, JSON.stringify(secrets, null, 4), 'utf-8');
}
/**
* Deletes a secret from the secrets file
* @param {import('../users.js').UserDirectoryList} directories User directories
* @param {string} key Secret key
* @returns
*/
export function deleteSecret(directories, key) {
if (!Object.values(SECRET_KEYS).includes(key)) {
throw new Error(`Invalid key: ${key}`);
}
const filePath = path.join(directories.root, SECRETS_FILE);
if (!fs.existsSync(filePath)) {
return;
}
const fileContents = fs.readFileSync(filePath, 'utf-8');
const secrets = JSON.parse(fileContents);
delete secrets[key];
writeFileAtomicSync(filePath, JSON.stringify(secrets, null, 4), 'utf-8');
}
/**
* Reads a secret from the secrets file
* @param {import('../users.js').UserDirectoryList} directories User directories
* @param {string} key Secret key
* @returns {string} Secret value
*/
export function readSecret(directories, key) {
if (!Object.values(SECRET_KEYS).includes(key)) {
throw new Error(`Invalid key: ${key}`);
}
const filePath = path.join(directories.root, SECRETS_FILE);
if (!fs.existsSync(filePath)) {
return '';
}
const fileContents = fs.readFileSync(filePath, 'utf-8');
const secrets = JSON.parse(fileContents);
return secrets[key];
}
/**
* Reads the secret state from the secrets file
* @param {import('../users.js').UserDirectoryList} directories User directories
* @returns {object} Secret state
*/
export function readSecretState(directories) {
const filePath = path.join(directories.root, SECRETS_FILE);
if (!fs.existsSync(filePath)) {
return {};
}
const fileContents = fs.readFileSync(filePath, 'utf8');
const secrets = JSON.parse(fileContents);
const state = {};
for (const key of Object.values(SECRET_KEYS)) {
state[key] = !!secrets[key]; // convert to boolean
}
return state;
}
/**
* Reads all secrets from the secrets file
* @param {import('../users.js').UserDirectoryList} directories User directories
* @returns {Record<string, string> | undefined} Secrets
*/
export function getAllSecrets(directories) {
const filePath = path.join(directories.root, SECRETS_FILE);
if (!fs.existsSync(filePath)) {
console.log('Secrets file does not exist');
return undefined;
}
const fileContents = fs.readFileSync(filePath, 'utf8');
const secrets = JSON.parse(fileContents);
return secrets;
}
export const router = express.Router();
router.post('/write', jsonParser, (request, response) => {
const key = request.body.key;
const value = request.body.value;
if (!Object.values(SECRET_KEYS).includes(key)) {
return response.status(400).send('Invalid key');
}
try {
writeSecret(request.user.directories, key, value);
return response.send('ok');
} catch (error) {
console.error(error);
return response.status(500).send('Error writing secret');
}
});
router.post('/read', jsonParser, (request, response) => {
try {
const state = readSecretState(request.user.directories);
return response.send(state);
} catch (error) {
console.error(error);
return response.send({});
}
});
router.post('/view', jsonParser, async (request, response) => {
const allowKeysExposure = getConfigValue('allowKeysExposure', false);
if (!allowKeysExposure) {
console.error(
'secrets.json could not be viewed unless the value of allowKeysExposure in config.yaml is set to true'
);
return response.sendStatus(403);
}
try {
const secrets = getAllSecrets(request.user.directories);
if (!secrets) {
return response.sendStatus(404);
}
return response.send(secrets);
} catch (error) {
console.error(error);
return response.sendStatus(500);
}
});
router.post('/find', jsonParser, (request, response) => {
const allowKeysExposure = getConfigValue('allowKeysExposure', false);
const key = request.body.key;
if (!Object.values(SECRET_KEYS).includes(key)) {
return response.status(400).send('Invalid key');
}
if (!allowKeysExposure && !EXPORTABLE_KEYS.includes(key)) {
console.error(
'Cannot fetch secrets unless allowKeysExposure in config.yaml is set to true'
);
return response.sendStatus(403);
}
try {
const secret = readSecret(request.user.directories, key);
if (!secret) {
response.sendStatus(404);
}
return response.send({ value: secret });
} catch (error) {
console.error(error);
return response.sendStatus(500);
}
});
Explanation of Changes:
-
Validation of Keys:
-
Added Validation in writeSecret, deleteSecret, and readSecret Functions:
Before performing any operation, the script now checks if the provided key is one of the predefined keys in SECRET_KEYS. If not, it throws an error.
if (!Object.values(SECRET_KEYS).includes(key)) {
throw new Error(`Invalid key: ${key}`);
}
-
Added Validation in Routes:
- In the
/write route, before calling writeSecret, it checks if the key is valid.
- In the
/find route, it validates the key and ensures it is allowed for exposure.
if (!Object.values(SECRET_KEYS).includes(key)) {
return response.status(400).send('Invalid key');
}
-
Restricting Operations to Predefined Keys:
By adding these validations, we ensure that no arbitrary keys can be used when interacting with secrets. Only the keys defined in the SECRET_KEYS object are permissible.
-
Error Handling:
- Enhanced error handling in the
/write route to catch and log any potential errors when writing secrets.
- Provides appropriate HTTP status codes and error messages.
-
Consistency in Responses:
- Ensures that responses are consistent and informative, providing clear feedback to the client if an invalid key is used or if an error occurs.
-
Maintained Existing Functionality:
- All other functionalities remain intact, ensuring the script continues to operate as before but with the added security of key validation.
Usage Notes:
-
Writing a Secret:
When making a POST request to /write, the key must be one of the keys defined in SECRET_KEYS. Example request body:
{
"key": "api_key_openai",
"value": "your-openai-api-key"
}
-
Reading a Secret:
Similar validation applies when reading a secret using the /find route.
-
Allowed Keys Exposure:
The allowKeysExposure configuration still controls whether secrets can be viewed or fetched, with certain keys always being safe to expose as defined in EXPORTABLE_KEYS.
By implementing these changes, the script now uses a predefined list of secret keys, enhancing security and ensuring only authorized keys are used in the application.