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

feat: encryption key rotation command — re-encrypt stored secrets under a new key (#1112) (#1113)

suantea (asuan_suan)80bd25f9ef76
diff --git a/docs/i18n/zh-CN/docs/install.md b/docs/i18n/zh-CN/docs/install.md
index 73470c55..c724839a 100644
--- a/docs/i18n/zh-CN/docs/install.md
+++ b/docs/i18n/zh-CN/docs/install.md
@@ -107,6 +107,27 @@ npm run dev
启动必须要有 `ENCRYPTION_KEY`。当 `NODE_ENV` 不是 `production` 且没有设置它时,服务会自动生成一个开发用的密钥,并保存到 SQLite 数据库旁边的 `.encryption-key` 文件(权限 0600)里,而不是存进数据库。以前把密钥存在数据库里的旧安装,会在首次启动时迁移到这个文件。不要在放着真实提供方密钥的环境里依赖这个兜底行为,请显式设置 `ENCRYPTION_KEY`。
+### 轮换加密密钥
+
+存储的密文用的是 AES-256-GCM,所以直接改 `ENCRYPTION_KEY` 不会重新加密任何东西——它只会让所有提供方密钥、按密钥的代理覆盖、客户端配置档凭据以及已保存的 Fetch Relay 令牌同时解不开。请先停掉服务,把它们重新加密:
+
+```bash
+# 1. 生成新密钥
+NEW_KEY="$(node -e 'console.log(require("crypto").randomBytes(32).toString("hex"))')"
+
+# 2. 预演(只读,不写入任何内容)
+cd server
+ENCRYPTION_KEY=<旧密钥> npm run rotate-encryption-key -- \
+ --new-key "$NEW_KEY" --dry-run
+
+# 3. 正式轮换
+ENCRYPTION_KEY=<旧密钥> npm run rotate-encryption-key -- --new-key "$NEW_KEY"
+```
+
+`--old-key <hex>` 可以覆盖从 `ENCRYPTION_KEY` 读到的密钥,`--db <path>` 用来指向 `server/data` 以外的数据库。只有当每一个值都能解密时才会写入,所以旧密钥填错会以非零状态退出,数据库保持原样。
+
+之后把新密钥写进 `.env`(`ENCRYPTION_KEY=$NEW_KEY`)并重启。使用 Docker 时,在容器内对挂载的数据库执行这条命令,然后用更新后的 `.env` 重启容器。轮换前请先备份数据库文件。
+
请求分析数据默认保留 90 天或 100000 条请求记录,以先触发的那个上限为准。在 `.env` 里设置 `REQUEST_ANALYTICS_RETENTION_DAYS=0` 或 `REQUEST_ANALYTICS_MAX_ROWS=0` 可以分别关掉对应的保留上限。
打开 http://localhost:5173 (Vite 开发界面),在 **密钥** 页添加你的提供方密钥,按喜好调整 **回退链** 的顺序,然后在 **密钥** 页顶部拿到你的统一 API 密钥。这个统一密钥就是你的 OpenAI SDK 要指向的东西。
diff --git a/docs/install.md b/docs/install.md
index 611b1982..9b0ece25 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -112,6 +112,36 @@ and it is unset, the server auto-generates a development key and saves it to a
installs that kept the key in the database are migrated to this file on first
boot. Do not rely on that fallback with real provider keys; set `ENCRYPTION_KEY`.
+### Rotating the encryption key
+
+Stored secrets are AES-256-GCM, so simply changing `ENCRYPTION_KEY` does not
+re-encrypt anything — it makes every provider key, per-key proxy override,
+client-profile credential and saved Fetch Relay token fail to decrypt at once.
+Re-encrypt them first, with the server stopped:
+
+```bash
+# 1. Generate the new key
+NEW_KEY="$(node -e 'console.log(require("crypto").randomBytes(32).toString("hex"))')"
+
+# 2. Preview (reads only, writes nothing)
+cd server
+ENCRYPTION_KEY=<old key> npm run rotate-encryption-key -- \
+ --new-key "$NEW_KEY" --dry-run
+
+# 3. Rotate for real
+ENCRYPTION_KEY=<old key> npm run rotate-encryption-key -- --new-key "$NEW_KEY"
+```
+
+`--old-key <hex>` overrides the key read from `ENCRYPTION_KEY`, and
+`--db <path>` points at a database somewhere other than `server/data`. Nothing
+is written unless every value decrypts, so a wrong old key aborts with a
+non-zero exit and an untouched database.
+
+Then put the new key in `.env` (`ENCRYPTION_KEY=$NEW_KEY`) and restart. Under
+Docker, run the command inside the container against the mounted database and
+restart the container with the updated `.env`. Take a copy of the database file
+before rotating.
+
Request analytics are retained for 90 days or 100000 request rows by default,
whichever limit prunes first. Set `REQUEST_ANALYTICS_RETENTION_DAYS=0` or
`REQUEST_ANALYTICS_MAX_ROWS=0` in `.env` to disable either retention limit.
diff --git a/server/package.json b/server/package.json
index 5cbf7822..dbb93fd7 100644
--- a/server/package.json
+++ b/server/package.json
@@ -11,6 +11,7 @@
"test:watch": "vitest",
"test:migrations": "vitest run --pool=forks --fileParallelism=false src/__tests__/db/migrate/roundtrip.test.ts",
"export-catalog": "tsx src/scripts/export-catalog.ts",
+ "rotate-encryption-key": "tsx src/scripts/rotate-encryption-key.ts",
"db:migration:up": "tsx src/db/migrate/cli.ts up",
"db:migration:down": "tsx src/db/migrate/cli.ts down",
"db:migration:fresh": "tsx src/db/migrate/cli.ts fresh",
diff --git a/server/src/__tests__/scripts/rotate-encryption-key-cli.test.ts b/server/src/__tests__/scripts/rotate-encryption-key-cli.test.ts
new file mode 100644
index 00000000..c2c2f7f7
--- /dev/null
+++ b/server/src/__tests__/scripts/rotate-encryption-key-cli.test.ts
@@ -0,0 +1,148 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { spawnSync } from 'child_process';
+import { createRequire } from 'module';
+import fs from 'fs';
+import os from 'os';
+import path from 'path';
+import { fileURLToPath } from 'url';
+import { initDb } from '../../db/index.js';
+import { encryptWith, decryptWith } from '../../scripts/rotate-encryption-key.js';
+
+// End-to-end coverage for the CLI itself, not just the exported helpers. The
+// script is an ESM module (server/package.json is "type": "module"), so a
+// stray `require()` in main() throws "require is not defined in ES module
+// scope" the moment `npm run rotate-encryption-key` is invoked — a failure the
+// unit tests cannot see, because they import rotateSecrets() directly. Only
+// actually running the script catches it.
+
+const require_ = createRequire(import.meta.url);
+const TSX_CLI = path.join(path.dirname(require_.resolve('tsx/package.json')), 'dist', 'cli.mjs');
+const SCRIPT = fileURLToPath(new URL('../../scripts/rotate-encryption-key.ts', import.meta.url));
+
+const OLD_HEX = 'a'.repeat(64);
+const NEW_HEX = 'b'.repeat(64);
+const OLD_KEY = Buffer.from(OLD_HEX, 'hex');
+const NEW_KEY = Buffer.from(NEW_HEX, 'hex');
+
+const API_KEY_SECRET = 'sk-live-rotate-me';
+const PROFILE_SECRET = 'cp-live-rotate-me';
+const RELAY_TOKEN = 'relay-bearer-rotate-me';
+
+let tmpDir: string;
+let dbPath: string;
+
+/** A real on-disk DB with the production schema, seeded under the OLD key. */
+function seedTempDb(): void {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'rotate-cli-'));
+ dbPath = path.join(tmpDir, 'freeapi.db');
+
+ // Set before initDb so crypto.ts takes the env key and never writes a
+ // .encryption-key file next to the temp DB.
+ process.env.ENCRYPTION_KEY = OLD_HEX;
+ const db = initDb(dbPath);
+
+ const keyEnc = encryptWith(OLD_KEY, API_KEY_SECRET);
+ db.prepare('INSERT INTO api_keys (platform, encrypted_key, iv, auth_tag, status, enabled) VALUES (?,?,?,?,?,?)')
+ .run('openai', keyEnc.encrypted, keyEnc.iv, keyEnc.authTag, 'unknown', 1);
+
+ const profileEnc = encryptWith(OLD_KEY, PROFILE_SECRET);
+ db.prepare('INSERT INTO client_profiles (name, token_hash, encrypted_key, iv, auth_tag, enabled) VALUES (?,?,?,?,?,?)')
+ .run('claude', 'hash-cli', profileEnc.encrypted, profileEnc.iv, profileEnc.authTag, 1);
+
+ // Same encoding encodeFetchRelayToken() writes: JSON.stringify(encrypt(v)).
+ const relayEnc = encryptWith(OLD_KEY, RELAY_TOKEN);
+ db.prepare('INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)')
+ .run('fetch_relay_token', JSON.stringify(relayEnc));
+
+ db.close?.();
+}
+
+/** Read every seeded ciphertext straight out of the file, no server involved. */
+function readSecrets(): { key: [string, string, string]; profile: [string, string, string]; relay: [string, string, string] } {
+ process.env.ENCRYPTION_KEY = OLD_HEX;
+ const db = initDb(dbPath);
+ const k = db.prepare('SELECT encrypted_key, iv, auth_tag FROM api_keys').get() as { encrypted_key: string; iv: string; auth_tag: string };
+ const p = db.prepare('SELECT encrypted_key, iv, auth_tag FROM client_profiles').get() as { encrypted_key: string; iv: string; auth_tag: string };
+ const s = db.prepare("SELECT value FROM settings WHERE key = 'fetch_relay_token'").get() as { value: string };
+ const relay = JSON.parse(s.value) as { encrypted: string; iv: string; authTag: string };
+ db.close?.();
+ return {
+ key: [k.encrypted_key, k.iv, k.auth_tag],
+ profile: [p.encrypted_key, p.iv, p.auth_tag],
+ relay: [relay.encrypted, relay.iv, relay.authTag],
+ };
+}
+
+function runScript(args: string[]): { status: number | null; stdout: string; stderr: string } {
+ // The script must not silently inherit the harness's own ENCRYPTION_KEY:
+ // --old-key has to carry the whole story.
+ const env = { ...process.env };
+ delete env.ENCRYPTION_KEY;
+ const res = spawnSync(process.execPath, [TSX_CLI, SCRIPT, ...args], { encoding: 'utf8', env });
+ return { status: res.status, stdout: res.stdout ?? '', stderr: res.stderr ?? '' };
+}
+
+describe('rotate-encryption-key CLI (end to end)', () => {
+ beforeEach(() => {
+ seedTempDb();
+ });
+
+ afterEach(() => {
+ if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
+ delete process.env.ENCRYPTION_KEY;
+ });
+
+ it('rotates every stored secret to the new key and leaves the old key unable to read them', () => {
+ const before = readSecrets();
+
+ const run = runScript(['--old-key', OLD_HEX, '--new-key', NEW_HEX, '--db', dbPath]);
+ expect(run.stderr).toBe('');
+ expect(run.status).toBe(0);
+ // api key + client profile + relay token.
+ expect(run.stdout).toContain('Rotated 3 value(s)');
+
+ const after = readSecrets();
+
+ expect(decryptWith(NEW_KEY, ...after.key)).toBe(API_KEY_SECRET);
+ expect(decryptWith(NEW_KEY, ...after.profile)).toBe(PROFILE_SECRET);
+ expect(decryptWith(NEW_KEY, ...after.relay)).toBe(RELAY_TOKEN);
+
+ // The old key must no longer open any of them (GCM fails the auth tag).
+ expect(() => decryptWith(OLD_KEY, ...after.key)).toThrow();
+ expect(() => decryptWith(OLD_KEY, ...after.profile)).toThrow();
+ expect(() => decryptWith(OLD_KEY, ...after.relay)).toThrow();
+
+ // Every ciphertext actually changed.
+ expect(after.key[0]).not.toBe(before.key[0]);
+ expect(after.profile[0]).not.toBe(before.profile[0]);
+ expect(after.relay[0]).not.toBe(before.relay[0]);
+ }, 60_000);
+
+ it('--dry-run reports the work without changing a single row', () => {
+ const before = readSecrets();
+
+ const run = runScript(['--old-key', OLD_HEX, '--new-key', NEW_HEX, '--db', dbPath, '--dry-run']);
+ expect(run.stderr).toBe('');
+ expect(run.status).toBe(0);
+ expect(run.stdout).toContain('[dry-run] would rotate 3 value(s)');
+ expect(run.stdout).toContain('settings.fetch_relay_token');
+ // Plaintext is never printed in full.
+ expect(run.stdout).not.toContain(API_KEY_SECRET);
+
+ const after = readSecrets();
+ expect(after).toEqual(before);
+ // And the old key still opens everything.
+ expect(decryptWith(OLD_KEY, ...after.key)).toBe(API_KEY_SECRET);
+ expect(decryptWith(OLD_KEY, ...after.relay)).toBe(RELAY_TOKEN);
+ }, 60_000);
+
+ it('exits non-zero and writes nothing when the old key is wrong', () => {
+ const before = readSecrets();
+
+ const run = runScript(['--old-key', 'c'.repeat(64), '--new-key', NEW_HEX, '--db', dbPath]);
+ expect(run.status).toBe(1);
+ expect(run.stderr).toMatch(/cannot decrypt/);
+
+ expect(readSecrets()).toEqual(before);
+ }, 60_000);
+});
diff --git a/server/src/__tests__/scripts/rotate-encryption-key.test.ts b/server/src/__tests__/scripts/rotate-encryption-key.test.ts
new file mode 100644
index 00000000..593bb3e7
--- /dev/null
+++ b/server/src/__tests__/scripts/rotate-encryption-key.test.ts
@@ -0,0 +1,84 @@
+import { describe, it, expect, beforeAll } from 'vitest';
+import { initDb, getDb } from '../../db/index.js';
+import { encrypt, decrypt } from '../../lib/crypto.js';
+import {
+ rotateSecrets,
+ applyRotation,
+ encryptWith,
+ decryptWith,
+} from '../../scripts/rotate-encryption-key.js';
+
+const OLD_KEY = Buffer.from('a'.repeat(64), 'hex'); // 64 hex chars
+const NEW_KEY = Buffer.from('b'.repeat(64), 'hex');
+
+// Seed one row in every encryption group with the OLD key.
+function seedRows() {
+ const db = getDb();
+ const keyEnc = encryptWith(OLD_KEY, 'sk-prod-secret-123');
+ db.prepare('INSERT INTO api_keys (platform, encrypted_key, iv, auth_tag, status, enabled) VALUES (?,?,?,?,?,?)')
+ .run('openai', keyEnc.encrypted, keyEnc.iv, keyEnc.authTag, 'unknown', 1);
+ const proxyEnc = encryptWith(OLD_KEY, 'http://user:[email protected]:8080');
+ db.prepare("UPDATE api_keys SET proxy_encrypted = ?, proxy_iv = ?, proxy_auth_tag = ? WHERE platform = 'openai'")
+ .run(proxyEnc.encrypted, proxyEnc.iv, proxyEnc.authTag);
+ const profileEnc = encryptWith(OLD_KEY, 'cp-secret');
+ db.prepare('INSERT INTO client_profiles (name, token_hash, encrypted_key, iv, auth_tag, enabled) VALUES (?,?,?,?,?,?)')
+ .run('claude', 'hash1', profileEnc.encrypted, profileEnc.iv, profileEnc.authTag, 1);
+}
+
+describe('rotate-encryption-key: key rotation round-trip', () => {
+ beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ seedRows();
+ });
+
+ it('re-encrypts every stored secret so the new key can decrypt it', () => {
+ const result = rotateSecrets(getDb(), OLD_KEY, NEW_KEY);
+ expect(result.error).toBeUndefined();
+ expect(result.rows).toHaveLength(3);
+
+ applyRotation(getDb(), result.rows);
+
+ const rows = getDb().prepare('SELECT id, encrypted_key, iv, auth_tag FROM api_keys').all() as Array<{ id: number; encrypted_key: string; iv: string; auth_tag: string }>;
+ expect(decryptWith(NEW_KEY, rows[0].encrypted_key, rows[0].iv, rows[0].auth_tag)).toBe('sk-prod-secret-123');
+
+ const proxy = getDb().prepare('SELECT proxy_encrypted, proxy_iv, proxy_auth_tag FROM api_keys').get() as { proxy_encrypted: string; proxy_iv: string; proxy_auth_tag: string };
+ expect(decryptWith(NEW_KEY, proxy.proxy_encrypted, proxy.proxy_iv, proxy.proxy_auth_tag)).toBe('http://user:[email protected]:8080');
+
+ const cp = getDb().prepare('SELECT encrypted_key, iv, auth_tag FROM client_profiles').get() as { encrypted_key: string; iv: string; auth_tag: string };
+ expect(decryptWith(NEW_KEY, cp.encrypted_key, cp.iv, cp.auth_tag)).toBe('cp-secret');
+ });
+});
+
+describe('rotate-encryption-key: wrong-key protection', () => {
+ beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ seedRows();
+ });
+
+ it('reports an error (and no rows) when the old key cannot decrypt a value', () => {
+ const wrong = Buffer.from('c'.repeat(64), 'hex');
+ const result = rotateSecrets(getDb(), wrong, NEW_KEY);
+ expect(result.rows).toHaveLength(0);
+ expect(result.error).toMatch(/cannot decrypt/);
+ });
+});
+
+describe('rotate-encryption-key: aes-256-gcm parity with crypto.ts', () => {
+ it('produces ciphertext the server crypto module can open (same params)', () => {
+ // The rotate script must be a drop-in re-encryptor for the running server:
+ // a value encrypted with encryptWith() has to decrypt under the server's
+ // crypto.decrypt() with the same key, and vice versa.
+ process.env.ENCRYPTION_KEY = 'd'.repeat(64);
+ const key = Buffer.from('d'.repeat(64), 'hex');
+ initDb(':memory:');
+
+ const serverEnc = encrypt('roundtrip-parity');
+ // The rotate script decrypts it with the same raw key bytes.
+ expect(decryptWith(key, serverEnc.encrypted, serverEnc.iv, serverEnc.authTag)).toBe('roundtrip-parity');
+ // And its own ciphertext decrypts under the server module with that key.
+ const scriptEnc = encryptWith(key, 'script-parity');
+ expect(decrypt(scriptEnc.encrypted, scriptEnc.iv, scriptEnc.authTag)).toBe('script-parity');
+ });
+});
diff --git a/server/src/scripts/rotate-encryption-key.ts b/server/src/scripts/rotate-encryption-key.ts
new file mode 100644
index 00000000..1e2c7f17
--- /dev/null
+++ b/server/src/scripts/rotate-encryption-key.ts
@@ -0,0 +1,326 @@
+#!/usr/bin/env node
+/**
+ * rotate-encryption-key — re-encrypt every stored secret under a new
+ * ENCRYPTION_KEY without losing a single value.
+ *
+ * Why this exists: AES-256-GCM is authenticated, so a DB carried over to a
+ * different ENCRYPTION_KEY fails loudly on the first decrypt — every stored
+ * API key, proxy override, client-profile credential and the Fetch Relay
+ * token becomes unreadable at once, and there is no recovery path short of
+ * re-entering secrets by hand.
+ * Rotating keys (compromise, policy expiry, onboarding) therefore has to walk
+ * the ciphertext, decrypt each value with the OLD key and re-encrypt it with
+ * the NEW one, atomically, before the new key ever becomes active.
+ *
+ * The cipher parameters deliberately mirror server/src/lib/crypto.ts
+ * (aes-256-gcm, 32-byte key hex, 16-byte IV, 16-byte GCM tag) so a value
+ * written here decrypts under the running server exactly like one written by
+ * `encrypt()`. The script does NOT touch the module-level key cache — it
+ * performs every decrypt with `--old-key` and every encrypt with `--new-key`
+ * explicitly, so it is safe to run while the server is stopped (recommended)
+ * or even live (a writer that fires mid-run sees only already-migrated rows
+ * because both keys are valid until the process restarts with the new key).
+ *
+ * Usage:
+ * tsx src/scripts/rotate-encryption-key.ts --old-key <64hex> --new-key <64hex> [--db <path>] [--dry-run]
+ *
+ * --old-key the current key (hex, 64 chars). Falls back to ENCRYPTION_KEY.
+ * --new-key the key to rotate to (hex, 64 chars). Required.
+ * --db SQLite path (default: the server's data/freeapi.db).
+ * --dry-run decrypt + print every affected row WITHOUT writing anything.
+ *
+ * Exits 0 on success (or a clean dry run), 1 on any decrypt/validation error.
+ * Nothing is written unless EVERY row decrypts — a partial rotate would leave
+ * the DB in a mixed-key state that is exactly the failure this script exists
+ * to prevent.
+ */
+import Database from 'better-sqlite3';
+import crypto from 'crypto';
+import fs from 'fs';
+import path from 'path';
+import { fileURLToPath } from 'url';
+
+const ALGORITHM = 'aes-256-gcm';
+const KEY_HEX_LEN = 64;
+const AUTH_TAG_BYTES = 16;
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const DEFAULT_DB = path.resolve(__dirname, '../../data/freeapi.db');
+
+function arg(name: string): string | undefined {
+ const i = process.argv.indexOf(`--${name}`);
+ return i !== -1 ? process.argv[i + 1] : undefined;
+}
+function flag(name: string): boolean {
+ return process.argv.includes(`--${name}`);
+}
+
+function parseHexKey(value: string, source: string): Buffer {
+ if (value.length !== KEY_HEX_LEN || !/^[0-9a-fA-F]+$/.test(value)) {
+ throw new Error(
+ `Invalid key (${source}): expected ${KEY_HEX_LEN} hex chars (32 bytes), got ${value.length} chars. ` +
+ `Generate one with: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"`,
+ );
+ }
+ return Buffer.from(value, 'hex');
+}
+
+export function encryptWith(key: Buffer, text: string): { encrypted: string; iv: string; authTag: string } {
+ const iv = crypto.randomBytes(16);
+ const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
+ let encrypted = cipher.update(text, 'utf8', 'hex');
+ encrypted += cipher.final('hex');
+ return { encrypted, iv: iv.toString('hex'), authTag: cipher.getAuthTag().toString('hex') };
+}
+
+export function decryptWith(key: Buffer, encrypted: string, iv: string, authTag: string): string {
+ const decipher = crypto.createDecipheriv(ALGORITHM, key, Buffer.from(iv, 'hex'), { authTagLength: AUTH_TAG_BYTES });
+ decipher.setAuthTag(Buffer.from(authTag, 'hex'));
+ let decrypted = decipher.update(encrypted, 'hex', 'utf8');
+ decrypted += decipher.final('utf8');
+ return decrypted;
+}
+
+/**
+ * Ciphertext stored in dedicated columns: the IV and tag live next to their
+ * ciphertext in sibling columns, all TEXT.
+ */
+interface ColumnGroup {
+ kind: 'columns';
+ table: string;
+ idColumn: string;
+ encrypted: string;
+ iv: string;
+ authTag: string;
+ label: string;
+}
+
+/**
+ * Ciphertext stored as a JSON blob in a single `settings` value, in the shape
+ * `JSON.stringify(encrypt(plaintext))` — i.e. `{"encrypted","iv","authTag"}`.
+ * The Fetch Relay bearer token is written this way by
+ * `encodeFetchRelayToken()` (server/src/lib/proxy.ts) and read back by
+ * `decodeFetchRelayToken()`, which degrades to '' with a warning when the
+ * value will not decrypt. Miss it here and a rotate silently drops the relay
+ * credential on the next restart.
+ */
+interface SettingGroup {
+ kind: 'setting';
+ table: 'settings';
+ settingKey: string;
+ label: string;
+}
+
+type EncryptionGroup = ColumnGroup | SettingGroup;
+
+// Every place a secret is persisted. Keep this in step with the `encrypt()`
+// call sites in server/src/lib/crypto.ts consumers: api_keys (keys.ts,
+// custom-endpoint.ts, declarative-config.ts), api_keys proxy columns
+// (lib/key-proxy.ts), client_profiles (routes/client-profiles.ts) and the
+// settings blob (lib/proxy.ts).
+const ENCRYPTION_GROUPS: EncryptionGroup[] = [
+ { kind: 'columns', table: 'api_keys', idColumn: 'id', encrypted: 'encrypted_key', iv: 'iv', authTag: 'auth_tag', label: 'api key' },
+ { kind: 'columns', table: 'api_keys', idColumn: 'id', encrypted: 'proxy_encrypted', iv: 'proxy_iv', authTag: 'proxy_auth_tag', label: 'per-key proxy override' },
+ { kind: 'columns', table: 'client_profiles', idColumn: 'id', encrypted: 'encrypted_key', iv: 'iv', authTag: 'auth_tag', label: 'client-profile credential' },
+ { kind: 'setting', table: 'settings', settingKey: 'fetch_relay_token', label: 'fetch relay token' },
+];
+
+interface RowToRotate {
+ group: EncryptionGroup;
+ /** Row id for column groups, the settings key for settings blobs. */
+ id: number | string;
+ plaintext: string;
+ reEncrypted: { encrypted: string; iv: string; authTag: string };
+}
+
+/** Result of a rotate attempt: rows re-encrypted, or an error that aborted it. */
+export interface RotateResult {
+ rows: RowToRotate[];
+ error?: string;
+}
+
+/** The read surface rotateSecrets needs — better-sqlite3 and the app's Db both satisfy it. */
+export interface RotateReadDb {
+ prepare(sql: string): { all(...args: unknown[]): unknown[]; get(...args: unknown[]): unknown };
+}
+
+/** The write surface applyRotation needs, including better-sqlite3's transaction(). */
+export interface RotateWriteDb {
+ prepare(sql: string): { run(...args: unknown[]): unknown };
+ // Deliberately phrased as "a callable taking the same arguments" rather than
+ // "returns F": better-sqlite3 hands back a Transaction<F> (F plus .deferred
+ // and friends) while the app's Db type returns F itself, and both satisfy
+ // this shape.
+ transaction<A extends unknown[]>(fn: (...args: A) => void): (...args: A) => unknown;
+}
+
+/**
+ * Core rotate routine, exported so tests can drive it against an in-memory
+ * DB. Decrypts every stored secret with `oldKey` and re-encrypts with
+ * `newKey`. Returns `{ rows }` on success and `{ rows: [], error }` when ANY
+ * value fails to decrypt — the caller must treat the error case as "nothing
+ * written".
+ */
+export function rotateSecrets(
+ db: RotateReadDb,
+ oldKey: Buffer,
+ newKey: Buffer,
+): RotateResult {
+ const rowsToRotate: RowToRotate[] = [];
+
+ for (const group of ENCRYPTION_GROUPS) {
+ const cols = db.prepare(`PRAGMA table_info(${group.table})`).all() as Array<{ name: string }>;
+ const names = new Set(cols.map((c) => c.name));
+
+ // Ciphertext held as (encrypted, iv, auth_tag) columns.
+ if (group.kind === 'columns') {
+ if (!names.has(group.encrypted) || !names.has(group.iv) || !names.has(group.authTag)) {
+ continue;
+ }
+
+ const rows = db.prepare(
+ `SELECT ${group.idColumn} AS id, ${group.encrypted} AS enc, ${group.iv} AS iv, ${group.authTag} AS tag ` +
+ `FROM ${group.table} WHERE ${group.encrypted} IS NOT NULL`,
+ ).all() as Array<{ id: number; enc: string; iv: string; tag: string }>;
+
+ for (const row of rows) {
+ let plaintext: string;
+ try {
+ plaintext = decryptWith(oldKey, row.enc, row.iv, row.tag);
+ } catch (err) {
+ return {
+ rows: [],
+ error: `cannot decrypt ${group.label} #${row.id} with --old-key — wrong key or corrupted ciphertext (${(err as Error).message}). Aborting; nothing was written.`,
+ };
+ }
+ rowsToRotate.push({ group, id: row.id, plaintext, reEncrypted: encryptWith(newKey, plaintext) });
+ }
+ continue;
+ }
+
+ // Ciphertext held as a JSON blob in settings.value.
+ if (!names.has('key') || !names.has('value')) continue;
+
+ const row = db.prepare('SELECT value FROM settings WHERE key = ?').get(group.settingKey) as { value: string } | undefined;
+ // An unset or cleared setting stores '' rather than a blob — nothing to do.
+ if (!row || !row.value) continue;
+
+ let parsed: { encrypted?: string; iv?: string; authTag?: string };
+ try {
+ parsed = JSON.parse(row.value) as { encrypted?: string; iv?: string; authTag?: string };
+ } catch {
+ return {
+ rows: [],
+ error: `${group.label} (settings.${group.settingKey}) is not valid JSON — refusing to guess. Aborting; nothing was written.`,
+ };
+ }
+ if (!parsed.encrypted || !parsed.iv || !parsed.authTag) {
+ return {
+ rows: [],
+ error: `${group.label} (settings.${group.settingKey}) is missing encrypted/iv/authTag. Aborting; nothing was written.`,
+ };
+ }
+
+ let plaintext: string;
+ try {
+ plaintext = decryptWith(oldKey, parsed.encrypted, parsed.iv, parsed.authTag);
+ } catch (err) {
+ return {
+ rows: [],
+ error: `cannot decrypt ${group.label} (settings.${group.settingKey}) with --old-key — wrong key or corrupted ciphertext (${(err as Error).message}). Aborting; nothing was written.`,
+ };
+ }
+ rowsToRotate.push({ group, id: group.settingKey, plaintext, reEncrypted: encryptWith(newKey, plaintext) });
+ }
+
+ return { rows: rowsToRotate };
+}
+
+/**
+ * Apply a rotate result: write every re-encrypted value back to its row, in
+ * one transaction. Exported so main() and tests share the exact write path.
+ */
+export function applyRotation(
+ db: RotateWriteDb,
+ rows: RowToRotate[],
+): void {
+ const write = db.transaction((items: RowToRotate[]) => {
+ for (const r of items) {
+ if (r.group.kind === 'setting') {
+ // Same encoding encodeFetchRelayToken() writes, so the running server
+ // reads it back unchanged.
+ db.prepare('UPDATE settings SET value = ? WHERE key = ?')
+ .run(JSON.stringify(r.reEncrypted), r.group.settingKey);
+ continue;
+ }
+ db.prepare(
+ `UPDATE ${r.group.table} SET ${r.group.encrypted} = ?, ${r.group.iv} = ?, ${r.group.authTag} = ? WHERE ${r.group.idColumn} = ?`,
+ ).run(r.reEncrypted.encrypted, r.reEncrypted.iv, r.reEncrypted.authTag, r.id);
+ }
+ });
+ write(rows);
+}
+
+function main(): void {
+ const oldKeyHex = arg('old-key') ?? process.env.ENCRYPTION_KEY;
+ const newKeyHex = arg('new-key');
+ const dbPath = arg('db') ?? DEFAULT_DB;
+ const dryRun = flag('dry-run');
+
+ if (!oldKeyHex) {
+ console.error('error: --old-key is required (or set ENCRYPTION_KEY)');
+ process.exit(1);
+ }
+ if (!newKeyHex) {
+ console.error('error: --new-key is required');
+ process.exit(1);
+ }
+ if (!fs.existsSync(dbPath)) {
+ console.error(`error: database not found at ${dbPath}`);
+ process.exit(1);
+ }
+
+ const oldKey = parseHexKey(oldKeyHex, 'old');
+ const newKey = parseHexKey(newKeyHex, 'new');
+ if (oldKey.equals(newKey)) {
+ console.error('error: --old-key and --new-key are identical — nothing to rotate');
+ process.exit(1);
+ }
+
+ const db = new Database(dbPath, { readonly: dryRun });
+ try {
+ const result = rotateSecrets(db, oldKey, newKey);
+ if (result.error) {
+ console.error(`error: ${result.error}`);
+ process.exit(1);
+ }
+
+ const rowsToRotate = result.rows;
+ if (rowsToRotate.length === 0) {
+ console.log('No encrypted values found — nothing to rotate.');
+ return;
+ }
+
+ if (dryRun) {
+ console.log(`[dry-run] would rotate ${rowsToRotate.length} value(s):`);
+ for (const r of rowsToRotate) {
+ const where = r.group.kind === 'setting' ? `settings.${r.group.settingKey}` : `#${r.id}`;
+ console.log(` ${r.group.label} ${where} -> ${r.plaintext.slice(0, 3)}*** (${r.plaintext.length} chars)`);
+ }
+ return;
+ }
+
+ applyRotation(db, rowsToRotate);
+
+ console.log(`Rotated ${rowsToRotate.length} value(s) to the new key.`);
+ console.log('Next steps: set ENCRYPTION_KEY to the new key (or overwrite the .encryption-key file next to the DB) and restart the server.');
+ } finally {
+ db.close();
+ }
+}
+
+// Only run when invoked directly (`tsx src/scripts/rotate-encryption-key.ts`),
+// not when the module is imported by tests for `rotateSecrets`/`encryptWith`.
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ main();
+}