Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

fix: require encryption key outside dev fallback (#87)

Ricardo03e5815378ba
diff --git a/README.md b/README.md
index ff283e8b..f7ce1ff9 100644
--- a/README.md
+++ b/README.md
@@ -107,6 +107,10 @@ echo "ENCRYPTION_KEY=$(node -e "console.log(require('crypto').randomBytes(32).to
npm run dev
```
+`ENCRYPTION_KEY` is required for startup. The server only falls back to a
+database-stored development key when `DEV_MODE=true` and `NODE_ENV` is not
+`production`; do not use that fallback with real provider keys.
+
Open http://localhost:5173 (the Vite dev UI), add your provider keys on the **Keys** page, reorder the **Fallback Chain** to taste, and grab your unified API key from the **Keys** page header. That unified key is what you point your OpenAI SDK at.
For a production build:
diff --git a/server/src/__tests__/lib/crypto-init.test.ts b/server/src/__tests__/lib/crypto-init.test.ts
index 4e26dacf..1d6be5f0 100644
--- a/server/src/__tests__/lib/crypto-init.test.ts
+++ b/server/src/__tests__/lib/crypto-init.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import Database from 'better-sqlite3';
import { initEncryptionKey, encrypt, decrypt } from '../../lib/crypto.js';
@@ -8,9 +8,25 @@ function freshDb(): Database.Database {
return db;
}
+const ORIGINAL_NODE_ENV = process.env.NODE_ENV;
+
+function restoreEnv() {
+ delete process.env.ENCRYPTION_KEY;
+ delete process.env.DEV_MODE;
+ if (ORIGINAL_NODE_ENV === undefined) {
+ delete process.env.NODE_ENV;
+ } else {
+ process.env.NODE_ENV = ORIGINAL_NODE_ENV;
+ }
+}
+
describe('initEncryptionKey — input validation', () => {
beforeEach(() => {
- delete process.env.ENCRYPTION_KEY;
+ restoreEnv();
+ });
+
+ afterEach(() => {
+ restoreEnv();
});
it('accepts a valid 64-char hex env key', () => {
@@ -40,22 +56,49 @@ describe('initEncryptionKey — input validation', () => {
expect(() => initEncryptionKey(db)).toThrow(/Invalid ENCRYPTION_KEY \(env\)/);
});
- it('still treats the placeholder as "not set" and falls through to DB / generation', () => {
+ it('requires ENCRYPTION_KEY when dev fallback is not explicitly enabled', () => {
+ const db = freshDb();
+ expect(() => initEncryptionKey(db)).toThrow(/ENCRYPTION_KEY is required/);
+ const row = db.prepare("SELECT value FROM settings WHERE key = 'encryption_key'").get();
+ expect(row).toBeUndefined();
+ });
+
+ it('does not load a DB-stored fallback key when dev fallback is disabled', () => {
+ const db = freshDb();
+ db.prepare("INSERT INTO settings (key, value) VALUES ('encryption_key', ?)").run('b'.repeat(64));
+ expect(() => initEncryptionKey(db)).toThrow(/ENCRYPTION_KEY is required/);
+ });
+
+ it('requires ENCRYPTION_KEY in production even when DEV_MODE is set', () => {
+ process.env.DEV_MODE = 'true';
+ process.env.NODE_ENV = 'production';
+ const db = freshDb();
+ expect(() => initEncryptionKey(db)).toThrow(/ENCRYPTION_KEY is required/);
+ const row = db.prepare("SELECT value FROM settings WHERE key = 'encryption_key'").get();
+ expect(row).toBeUndefined();
+ });
+
+ it('still treats the placeholder as "not set" and allows explicit dev fallback generation', () => {
process.env.ENCRYPTION_KEY = 'your-64-char-hex-key-here';
+ process.env.DEV_MODE = 'true';
+ process.env.NODE_ENV = 'test';
const db = freshDb();
expect(() => initEncryptionKey(db)).not.toThrow();
- // Fell through to generation — DB now has a key.
const row = db.prepare("SELECT value FROM settings WHERE key = 'encryption_key'").get() as { value: string };
expect(row.value).toMatch(/^[0-9a-f]{64}$/);
});
it('throws on a corrupted DB-stored key', () => {
+ process.env.DEV_MODE = 'true';
+ process.env.NODE_ENV = 'test';
const db = freshDb();
db.prepare("INSERT INTO settings (key, value) VALUES ('encryption_key', ?)").run('not-hex');
expect(() => initEncryptionKey(db)).toThrow(/Invalid ENCRYPTION_KEY \(db\)/);
});
- it('generates a fresh key on a virgin DB and persists it', () => {
+ it('generates a fresh key on a virgin DB and persists it only in explicit dev fallback mode', () => {
+ process.env.DEV_MODE = 'true';
+ process.env.NODE_ENV = 'test';
const db = freshDb();
initEncryptionKey(db);
const row = db.prepare("SELECT value FROM settings WHERE key = 'encryption_key'").get() as { value: string };
diff --git a/server/src/__tests__/services/routing-exhaustion.test.ts b/server/src/__tests__/services/routing-exhaustion.test.ts
index a7f5fde9..45d1304b 100644
--- a/server/src/__tests__/services/routing-exhaustion.test.ts
+++ b/server/src/__tests__/services/routing-exhaustion.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { routeRequest } from '../../services/router.js';
import * as ratelimit from '../../services/ratelimit.js';
import { getDb, initDb } from '../../db/index.js';
@@ -24,8 +24,26 @@ vi.mock('../../lib/crypto.js', async () => {
};
});
+const ORIGINAL_DEV_MODE = process.env.DEV_MODE;
+const ORIGINAL_NODE_ENV = process.env.NODE_ENV;
+
+function restoreEnv() {
+ if (ORIGINAL_DEV_MODE === undefined) {
+ delete process.env.DEV_MODE;
+ } else {
+ process.env.DEV_MODE = ORIGINAL_DEV_MODE;
+ }
+ if (ORIGINAL_NODE_ENV === undefined) {
+ delete process.env.NODE_ENV;
+ } else {
+ process.env.NODE_ENV = ORIGINAL_NODE_ENV;
+ }
+}
+
describe('Routing Key Exhaustion', () => {
beforeEach(() => {
+ process.env.DEV_MODE = 'true';
+ process.env.NODE_ENV = 'test';
initDb(':memory:');
const db = getDb();
@@ -47,6 +65,10 @@ describe('Routing Key Exhaustion', () => {
vi.clearAllMocks();
});
+ afterEach(() => {
+ restoreEnv();
+ });
+
it('should skip exhausted Key B and use functional Key A for the same high-priority model', () => {
const db = getDb();
const keys = db.prepare("SELECT id, label FROM api_keys").all();
diff --git a/server/src/lib/crypto.ts b/server/src/lib/crypto.ts
index 6a7fc4e3..b4fc857b 100644
--- a/server/src/lib/crypto.ts
+++ b/server/src/lib/crypto.ts
@@ -14,6 +14,7 @@ let cachedKey: Buffer | null = null;
*/
const KEY_BYTES = 32;
const KEY_HEX_LEN = KEY_BYTES * 2;
+const PLACEHOLDER_KEY = 'your-64-char-hex-key-here';
function parseHexKey(value: string, source: 'env' | 'db'): Buffer {
if (value.length !== KEY_HEX_LEN || !/^[0-9a-fA-F]+$/.test(value)) {
@@ -25,18 +26,33 @@ function parseHexKey(value: string, source: 'env' | 'db'): Buffer {
return Buffer.from(value, 'hex');
}
+function isDevFallbackAllowed(): boolean {
+ return process.env.DEV_MODE === 'true' && process.env.NODE_ENV !== 'production';
+}
+
+function missingKeyError(): Error {
+ return new Error(
+ 'ENCRYPTION_KEY is required for API key encryption. ' +
+ `Set a ${KEY_HEX_LEN}-char hex key, or set DEV_MODE=true outside production to allow a local DB-stored fallback key.`,
+ );
+}
+
/**
- * Initialize encryption key from env, DB, or generate a new one.
+ * Initialize encryption key from env or an explicit local-dev fallback.
* Must be called after DB is initialized.
*/
export function initEncryptionKey(db: Database.Database): void {
// 1. Check env var
const envKey = process.env.ENCRYPTION_KEY;
- if (envKey && envKey !== 'your-64-char-hex-key-here') {
+ if (envKey && envKey !== PLACEHOLDER_KEY) {
cachedKey = parseHexKey(envKey, 'env');
return;
}
+ if (!isDevFallbackAllowed()) {
+ throw missingKeyError();
+ }
+
// 2. Check DB for persisted key
const row = db.prepare("SELECT value FROM settings WHERE key = 'encryption_key'").get() as { value: string } | undefined;
if (row) {