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
security: first-run setup code, key file out of the DB, CSV export hardening (#477)
Tashfeena66f75206cfb
diff --git a/.dockerignore b/.dockerignoreindex b04cc417..58610da5 100644--- a/.dockerignore+++ b/.dockerignore@@ -14,6 +14,7 @@ dist*.db-wal*.db-shm*.bak+.encryption-key.DS_Storenpm-debug.log*repo-assetsdiff --git a/.env.example b/.env.exampleindex f45827b4..c48e05e9 100644--- a/.env.example+++ b/.env.example@@ -1,4 +1,9 @@-# Server encryption key for API key storage (generate with: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))")+# Server encryption key for API key storage (generate with: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))").+# Required in production. Outside production it is optional: when unset, a key is+# auto-generated and written to a file named .encryption-key next to the SQLite+# database (not inside it), with 0600 permissions. Precedence: this env var, then+# that key file, then a legacy key found in the old settings table (migrated to+# the file on first boot), then a freshly generated key.ENCRYPTION_KEY=your-64-char-hex-key-here# Server port (default: 3001)@@ -10,6 +15,12 @@ PORT=3001# below, which only affects Docker port publishing.)# HOST=::+# First-run setup: the first account is created through the dashboard. A browser+# on the same machine as the server can do this with no extra step. If the server+# is reachable from other devices, creating that first account also requires a+# one-time setup code, printed in the server logs at startup while no account+# exists. This stops a stranger from claiming a freshly exposed install.+# Docker only: which host interface the container's port is published on.# Defaults to 127.0.0.1, so the dashboard/API is reachable only from the# machine running Docker. To open it to other devices on your LAN (e.g. adiff --git a/.gitignore b/.gitignoreindex 9d981732..7442529a 100644--- a/.gitignore+++ b/.gitignore@@ -5,6 +5,9 @@ server/data/*.db-wal*.db-shm*.bak+# Auto-generated dev encryption key (written next to the SQLite DB when+# ENCRYPTION_KEY is unset outside production). Never commit it.+.encryption-key.env.env.local.DS_Storediff --git a/README.md b/README.mdindex 8faab85c..3add7c4f 100644--- a/README.md+++ b/README.md@@ -201,9 +201,11 @@ $ENCRYPTION_KEY = node -e "console.log(require('crypto').randomBytes(32).toStrinnpm run dev```-`ENCRYPTION_KEY` is required for startup. The server only falls back to a-database-stored development key when `NODE_ENV` is not `production`; do not use-that fallback with real provider keys.+`ENCRYPTION_KEY` is required for startup. When `NODE_ENV` is not `production`+and it is unset, the server auto-generates a development key and saves it to a+`.encryption-key` file (0600) next to the SQLite database, not inside it. Older+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`.Request analytics are retained for 90 days or 100000 request rows by default,whichever limit prunes first. Set `REQUEST_ANALYTICS_RETENTION_DAYS=0` ordiff --git a/client/src/components/auth-gate.tsx b/client/src/components/auth-gate.tsxindex c2209add..7547ced1 100644--- a/client/src/components/auth-gate.tsx+++ b/client/src/components/auth-gate.tsx@@ -1,6 +1,6 @@import { useEffect, useState, type ReactNode } from 'react'import { useQuery, useQueryClient } from '@tanstack/react-query'-import { apiFetch, setToken, UNAUTHORIZED_EVENT } from '@/lib/api'+import { apiFetch, setToken, UNAUTHORIZED_EVENT, type ApiError } from '@/lib/api'import { Button } from '@/components/ui/button'import { FieldError } from '@/components/ui/field-error'import { Input } from '@/components/ui/input'@@ -29,6 +29,10 @@ function AuthForm({ mode, onAuthed }: { mode: 'setup' | 'login'; onAuthed: () =>const { t } = useI18n()const [email, setEmail] = useState('')const [password, setPassword] = useState('')+ const [setupCode, setSetupCode] = useState('')+ // Revealed only after the server asks for it (remote first-run setup). A+ // browser on the same machine as the server never sees this field.+ const [codeRequired, setCodeRequired] = useState(false)const [error, setError] = useState('')const [busy, setBusy] = useState(false)const [attempted, setAttempted] = useState(false)@@ -58,13 +62,22 @@ function AuthForm({ mode, onAuthed }: { mode: 'setup' | 'login'; onAuthed: () =>setBusy(true)setError('')try {+ const payload: Record<string, string> = { email, password }+ // Only the setup flow carries a code, and only once the server has asked+ // for it. The server ignores it for local (loopback) setup.+ if (isSetup && setupCode) payload.setupCode = setupCode.trim()const res = await apiFetch<{ token: string }>(isSetup ? '/api/auth/setup' : '/api/auth/login', {method: 'POST',- body: JSON.stringify({ email, password }),+ body: JSON.stringify(payload),})setToken(res.token)onAuthed()} catch (err) {+ // The server gates remote first-run setup behind a one-time code; reveal+ // the field so the operator can paste the code from the server logs.+ if (isSetup && (err as ApiError).code === 'setup_code_required') {+ setCodeRequired(true)+ }setError((err as Error).message)} finally {setBusy(false)@@ -111,6 +124,20 @@ function AuthForm({ mode, onAuthed }: { mode: 'setup' | 'login'; onAuthed: () =>/>{attempted && <FieldError error={passwordError} />}</div>+ {isSetup && codeRequired && (+ <div className="space-y-1.5">+ <Label className="text-xs" htmlFor="auth-setup-code">{t('auth.setupCode')}</Label>+ <Input+ id="auth-setup-code"+ type="text"+ autoComplete="off"+ value={setupCode}+ onChange={e => setSetupCode(e.target.value)}+ placeholder={t('auth.setupCodePlaceholder')}+ />+ <p className="text-xs text-muted-foreground">{t('auth.setupCodeHint')}</p>+ </div>+ )}{error && <p className="text-destructive text-xs">{error}</p>}<Button type="submit" className="w-full" disabled={busy}>{busy ? (isSetup ? t('auth.creating') : t('auth.signingIn')) : isSetup ? t('auth.createAccount') : t('auth.signIn')}diff --git a/client/src/i18n/locales/en.json b/client/src/i18n/locales/en.jsonindex 0be69031..10dd6224 100644--- a/client/src/i18n/locales/en.json+++ b/client/src/i18n/locales/en.json@@ -32,7 +32,10 @@"newPasswordAutoComplete": "new-password","currentPasswordAutoComplete": "current-password","serverUnreachableBefore": "Can't reach the server. Make sure the backend is running (",- "serverUnreachableAfter": ")."+ "serverUnreachableAfter": ").",+ "setupCode": "Setup code",+ "setupCodePlaceholder": "code from the server logs",+ "setupCodeHint": "Setting up from another device needs the one-time code printed in the server logs at startup."},"common": {"save": "Save",diff --git a/client/src/lib/api.ts b/client/src/lib/api.tsindex 9a6751b9..12af6fc1 100644--- a/client/src/lib/api.ts+++ b/client/src/lib/api.ts@@ -15,6 +15,13 @@ export function clearToken(): void {export const UNAUTHORIZED_EVENT = 'freellmapi:unauthorized';+// Error thrown by apiFetch on a non-2xx response. Carries the HTTP status and+// the server's machine-readable `error.type` so callers can branch on them.+export interface ApiError extends Error {+ status?: number;+ code?: string;+}+export async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {const token = getToken();const headers = new Headers(options?.headers);@@ -39,7 +46,13 @@ export async function apiFetch<T>(path: string, options?: RequestInit): Promise<}if (!res.ok) {const body = await res.json().catch(() => ({ error: { message: res.statusText } }));- throw new Error(body.error?.message ?? `HTTP ${res.status}`);+ // Surface the HTTP status and the machine-readable error type on the thrown+ // Error so callers can branch on them (e.g. the setup form reveals a code+ // field on a `setup_code_required` 403). `.message` behaviour is unchanged.+ const err = new Error(body.error?.message ?? `HTTP ${res.status}`) as ApiError;+ err.status = res.status;+ err.code = body.error?.type;+ throw err;}// A 200 whose body isn't JSON means this request never reached the API — the// usual cause is a reverse proxy (or static host) serving the dashboard'sdiff --git a/server/src/__tests__/lib/crypto-keyfile.test.ts b/server/src/__tests__/lib/crypto-keyfile.test.tsnew file mode 100644index 00000000..d765cbc4--- /dev/null+++ b/server/src/__tests__/lib/crypto-keyfile.test.ts@@ -0,0 +1,122 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import Database from 'better-sqlite3';+import fs from 'fs';+import os from 'os';+import path from 'path';+import { initEncryptionKey, encrypt, decrypt } from '../../lib/crypto.js';++// FIX 2: the dev-fallback key is persisted to a file next to the DB, not into+// the `settings` table it protects. These tests use REAL file-backed DBs+// (db.memory === false) so the file branch runs; the in-memory settings-table+// behavior is covered by crypto-init.test.ts.++const ORIGINAL_NODE_ENV = process.env.NODE_ENV;+const ORIGINAL_ENCRYPTION_KEY = process.env.ENCRYPTION_KEY;++const openDbs: Database.Database[] = [];+const tempDirs: string[] = [];++function fileDb(): { db: Database.Database; keyFile: string } {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'freellmapi-keyfile-'));+ tempDirs.push(dir);+ const db = new Database(path.join(dir, 'freeapi.db'));+ db.exec('CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)');+ openDbs.push(db);+ return { db, keyFile: path.join(dir, '.encryption-key') };+}++function restoreEnv() {+ if (ORIGINAL_NODE_ENV === undefined) delete process.env.NODE_ENV;+ else process.env.NODE_ENV = ORIGINAL_NODE_ENV;+ if (ORIGINAL_ENCRYPTION_KEY === undefined) delete process.env.ENCRYPTION_KEY;+ else process.env.ENCRYPTION_KEY = ORIGINAL_ENCRYPTION_KEY;+}++describe('initEncryptionKey — key file (dev fallback)', () => {+ beforeEach(() => {+ restoreEnv();+ delete process.env.ENCRYPTION_KEY;+ process.env.NODE_ENV = 'test';+ });++ afterEach(() => {+ while (openDbs.length) openDbs.pop()!.close();+ for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true });+ tempDirs.length = 0;+ restoreEnv();+ });++ it('generates a fresh key into a file next to the DB, not the settings table', () => {+ const { db, keyFile } = fileDb();++ initEncryptionKey(db);++ expect(fs.existsSync(keyFile)).toBe(true);+ expect(fs.readFileSync(keyFile, 'utf8').trim()).toMatch(/^[0-9a-f]{64}$/);+ // The key must NOT be stored in the DB it protects.+ expect(db.prepare("SELECT value FROM settings WHERE key = 'encryption_key'").get()).toBeUndefined();+ // The generated key actually works.+ const enc = encrypt('hello');+ expect(decrypt(enc.encrypted, enc.iv, enc.authTag)).toBe('hello');++ if (process.platform !== 'win32') {+ expect(fs.statSync(keyFile).mode & 0o777).toBe(0o600);+ }+ });++ it('reuses an existing key file on the next boot', () => {+ const { db, keyFile } = fileDb();+ initEncryptionKey(db);+ const firstKey = fs.readFileSync(keyFile, 'utf8').trim();+ const enc = encrypt('provider-secret');++ // Second boot (fresh module state simulated by calling init again).+ initEncryptionKey(db);+ expect(fs.readFileSync(keyFile, 'utf8').trim()).toBe(firstKey);+ // Ciphertext from the first boot still decrypts under the reused key.+ expect(decrypt(enc.encrypted, enc.iv, enc.authTag)).toBe('provider-secret');+ });++ it('migrates a legacy settings-table key to the file and still decrypts', () => {+ const K = 'd'.repeat(64);+ // Encrypt a secret under K via the env path (how an old install's data was+ // written), then simulate that install: key in settings, no env, no file.+ process.env.ENCRYPTION_KEY = K;+ const { db, keyFile } = fileDb();+ initEncryptionKey(db);+ const secret = 'sk-legacy-secret';+ const ciphertext = encrypt(secret);++ delete process.env.ENCRYPTION_KEY;+ process.env.NODE_ENV = 'test';+ db.prepare("INSERT INTO settings (key, value) VALUES ('encryption_key', ?)").run(K);+ expect(fs.existsSync(keyFile)).toBe(false);++ initEncryptionKey(db);++ // Key moved to the file, with the same bytes.+ expect(fs.readFileSync(keyFile, 'utf8').trim()).toBe(K);+ // And removed from the DB.+ expect(db.prepare("SELECT value FROM settings WHERE key = 'encryption_key'").get()).toBeUndefined();+ // Existing ciphertext still decrypts seamlessly.+ expect(decrypt(ciphertext.encrypted, ciphertext.iv, ciphertext.authTag)).toBe(secret);+ });++ it('prefers the ENCRYPTION_KEY env over an existing key file', () => {+ const { db, keyFile } = fileDb();+ fs.writeFileSync(keyFile, 'a'.repeat(64));++ process.env.ENCRYPTION_KEY = 'b'.repeat(64);+ initEncryptionKey(db);+ const encUnderEnv = encrypt('x');++ // The file was not consulted and is left untouched.+ expect(fs.readFileSync(keyFile, 'utf8').trim()).toBe('a'.repeat(64));++ // Prove env != file: re-init without env now loads the (different) file key,+ // so ciphertext produced under the env key can no longer be decrypted.+ delete process.env.ENCRYPTION_KEY;+ initEncryptionKey(db);+ expect(() => decrypt(encUnderEnv.encrypted, encUnderEnv.iv, encUnderEnv.authTag)).toThrow();+ });+});diff --git a/server/src/__tests__/routes/auth-setup-code.test.ts b/server/src/__tests__/routes/auth-setup-code.test.tsnew file mode 100644index 00000000..923d0a10--- /dev/null+++ b/server/src/__tests__/routes/auth-setup-code.test.ts@@ -0,0 +1,99 @@+import { describe, it, expect, beforeAll, beforeEach } from 'vitest';+import express, { type Express } from 'express';+import { authRouter } from '../../routes/auth.js';+import { initDb, getDb } from '../../db/index.js';+import { generateSetupCode, getSetupCode } from '../../lib/setup-code.js';++// FIX 1: first-run setup is frictionless from the local machine (loopback) but+// a remote caller must present the one-time setup code minted at boot. The real+// connection here is always loopback, so a middleware overrides req.socket with+// the address under test (the route reads req.socket.remoteAddress, never req.ip+// or X-Forwarded-For).++function appWithRemote(remoteAddr: string): Express {+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ Object.defineProperty(req, 'socket', { value: { remoteAddress: remoteAddr }, configurable: true });+ next();+ });+ app.use('/api/auth', authRouter);+ return app;+}++async function postSetup(app: Express, body: unknown) {+ const server = app.listen(0);+ const addr = server.address() as { port: number };+ const res = await fetch(`http://127.0.0.1:${addr.port}/api/auth/setup`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });+ const data = await res.json().catch(() => null);+ server.close();+ return { status: res.status, body: data };+}++const CREDS = { email: '[email protected]', password: 'supersecret' };++describe('First-run setup code gate (FIX 1)', () => {+ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ });++ beforeEach(() => {+ // Reset to an unclaimed dashboard and mint a fresh code for each case.+ const db = getDb();+ db.prepare('DELETE FROM sessions').run();+ db.prepare('DELETE FROM users').run();+ generateSetupCode();+ });++ it('allows setup from IPv4 loopback without a code', async () => {+ const { status, body } = await postSetup(appWithRemote('127.0.0.1'), CREDS);+ expect(status).toBe(201);+ expect(typeof body.token).toBe('string');+ });++ it('allows setup from IPv6 loopback without a code', async () => {+ const { status } = await postSetup(appWithRemote('::1'), CREDS);+ expect(status).toBe(201);+ });++ it('allows setup from an IPv4-mapped IPv6 loopback without a code', async () => {+ const { status } = await postSetup(appWithRemote('::ffff:127.0.0.1'), CREDS);+ expect(status).toBe(201);+ });++ it('rejects remote setup with no code (403 setup_code_required)', async () => {+ const { status, body } = await postSetup(appWithRemote('203.0.113.7'), CREDS);+ expect(status).toBe(403);+ expect(body.error.type).toBe('setup_code_required');+ // No account was created.+ const count = (getDb().prepare('SELECT COUNT(*) AS c FROM users').get() as { c: number }).c;+ expect(count).toBe(0);+ });++ it('rejects remote setup with a wrong code', async () => {+ const { status, body } = await postSetup(appWithRemote('203.0.113.7'), { ...CREDS, setupCode: 'WRONGCODE9' });+ expect(status).toBe(403);+ expect(body.error.type).toBe('setup_code_required');+ });++ it('allows remote setup with the correct code', async () => {+ const code = getSetupCode();+ expect(code).toBeTruthy();+ const { status, body } = await postSetup(appWithRemote('203.0.113.7'), { ...CREDS, setupCode: code });+ expect(status).toBe(201);+ expect(typeof body.token).toBe('string');+ });++ it('still 409s a second setup once an account exists (remote, even with a code)', async () => {+ // Claim locally first.+ expect((await postSetup(appWithRemote('127.0.0.1'), CREDS)).status).toBe(201);+ const { status, body } = await postSetup(appWithRemote('203.0.113.7'), { email: '[email protected]', password: 'supersecret', setupCode: getSetupCode() ?? 'x' });+ expect(status).toBe(409);+ expect(body.error.type).toBe('setup_complete');+ });+});diff --git a/server/src/__tests__/routes/keys-export-csv.test.ts b/server/src/__tests__/routes/keys-export-csv.test.tsnew file mode 100644index 00000000..04722363--- /dev/null+++ b/server/src/__tests__/routes/keys-export-csv.test.ts@@ -0,0 +1,91 @@+import { describe, it, expect, beforeAll, beforeEach } from 'vitest';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { initDb, getDb } from '../../db/index.js';+import { mintDashboardToken } from '../helpers/auth.js';++// FIX 3: CSV export must neutralize formula-injection in free-text labels. A+// label like `=HYPERLINK(...)` would run as a formula when the file is opened+// in Excel or Sheets; prefixing the cell with a single quote forces text.++let dashToken = '';++async function post(app: Express, path: string, body: unknown) {+ const server = app.listen(0);+ const addr = server.address() as { port: number };+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${dashToken}` },+ body: JSON.stringify(body),+ });+ const data = await res.json().catch(() => null);+ server.close();+ return { status: res.status, body: data };+}++async function exportCsvText(app: Express): Promise<{ status: number; text: string }> {+ const server = app.listen(0);+ const addr = server.address() as { port: number };+ const res = await fetch(`http://127.0.0.1:${addr.port}/api/keys/export?format=csv`, {+ headers: { Authorization: `Bearer ${dashToken}` },+ });+ const text = await res.text();+ server.close();+ return { status: res.status, text };+}++describe('Keys CSV export — formula injection guard (FIX 3)', () => {+ let app: Express;++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();+ dashToken = mintDashboardToken();+ });++ beforeEach(() => {+ getDb().prepare('DELETE FROM api_keys').run();+ });++ it('prefixes formula-leading labels with a single quote', async () => {+ await post(app, '/api/keys', {+ platform: 'groq',+ key: 'gsk_realkey_123456',+ label: '=HYPERLINK("http://evil.example","click")',+ });++ const { status, text } = await exportCsvText(app);+ expect(status).toBe(200);++ const dataLine = text.trim().split('\n')[1]!;+ // The label cell is quoted; inside it the leading '=' is neutralized to "'=".+ expect(dataLine).toContain('"\'=HYPERLINK');+ // Sanity: the raw un-neutralized formula start is not present as a live cell.+ expect(dataLine).not.toContain(',"=HYPERLINK');+ // The real key value must round-trip verbatim (not neutralized).+ expect(dataLine).toContain('gsk_realkey_123456');+ });++ it('neutralizes the other risky lead characters (+, -, @, tab, CR) in labels', async () => {+ for (const [label, lead] of [+ ['+1+2', "'+"],+ ['-2+3', "'-"],+ ['@SUM(A1)', "'@"],+ ] as const) {+ getDb().prepare('DELETE FROM api_keys').run();+ await post(app, '/api/keys', { platform: 'groq', key: 'gsk_realkey_123456', label });+ const { text } = await exportCsvText(app);+ const dataLine = text.trim().split('\n')[1]!;+ expect(dataLine).toContain(`"${lead}`);+ }+ });++ it('leaves ordinary labels untouched', async () => {+ await post(app, '/api/keys', { platform: 'groq', key: 'gsk_realkey_123456', label: 'My Groq Key' });+ const { text } = await exportCsvText(app);+ const dataLine = text.trim().split('\n')[1]!;+ expect(dataLine).toContain('"My Groq Key"');+ expect(dataLine).not.toContain("'My Groq Key");+ });+});diff --git a/server/src/db/types.ts b/server/src/db/types.tsindex 353f25c8..3c5b4142 100644--- a/server/src/db/types.ts+++ b/server/src/db/types.ts@@ -13,6 +13,12 @@ export interface Db {// eslint-disable-next-line @typescript-eslint/no-explicit-anytransaction<F extends (...args: any[]) => unknown>(fn: F): F;pragma(source: string): unknown;+ // Optional file metadata, populated when the backing store is better-sqlite3+ // (the default factory passes the raw handle through). Consumers that need a+ // filesystem location (e.g. the dev encryption-key file) must treat absence+ // as "no file backing" and fall back accordingly.+ readonly name?: string;+ readonly memory?: boolean;}/** Factory that opens (or creates) a database at the given resolved path anddiff --git a/server/src/index.ts b/server/src/index.tsindex 6983535a..ce0a129f 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -9,6 +9,8 @@ import { NodeScheduler } from './lib/scheduler.js';import { loadConfig } from './lib/config.js';import { applyDeclarativeConfigFromEnv } from './services/declarative-config.js';import { restoreDbBackupIfNeeded, startDbBackupPump } from './lib/db-backup.js';+import { userCount } from './services/auth.js';+import { generateSetupCode } from './lib/setup-code.js';async function main() {const config = loadConfig();@@ -28,6 +30,13 @@ async function main() {initDb(config.dbPath ?? undefined);applyDeclarativeConfigFromEnv();+ // First-run hardening: when the dashboard is still unclaimed, mint a one-time+ // setup code and log it. A loopback browser can finish setup without it; a+ // remote caller must supply it (see routes/auth.ts). Regenerated each boot.+ if (userCount() === 0) {+ generateSetupCode();+ }+// Load the persisted proxy settings from the DB (env var wins if set).// Must happen after initDb so the settings table is ready.applyProxyUrl(getSetting('proxy_url') ?? '');diff --git a/server/src/lib/crypto.ts b/server/src/lib/crypto.tsindex cd861fd6..b0e1163f 100644--- a/server/src/lib/crypto.ts+++ b/server/src/lib/crypto.ts@@ -1,4 +1,6 @@import crypto from 'crypto';+import fs from 'fs';+import path from 'path';import type { Db } from '../db/types.js';const ALGORITHM = 'aes-256-gcm';@@ -16,7 +18,14 @@ 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 {+// The dev-fallback key lives in a file next to the DB, NOT in the DB itself.+// Storing it beside the ciphertext it protects (the old `settings` row) meant+// encryption-at-rest protected nothing for a default install: whoever copied+// the DB also copied the key. The file sits in the same directory but is a+// separate artifact, and is chmod 0600 so it isn't world-readable.+const KEY_FILE_NAME = '.encryption-key';++function parseHexKey(value: string, source: 'env' | 'db' | 'file'): Buffer {if (value.length !== KEY_HEX_LEN || !/^[0-9a-fA-F]+$/.test(value)) {throw new Error(`Invalid ENCRYPTION_KEY (${source}): expected ${KEY_HEX_LEN} hex chars (32 bytes), got ${value.length} chars. ` +@@ -30,7 +39,7 @@ function parseHexKey(value: string, source: 'env' | 'db'): Buffer {// (`npm run dev`) boots without manual setup — the placeholder ENCRYPTION_KEY// in .env.example would otherwise crash the server on boot, which surfaces in// the client as "Can't reach the server". Production still requires an explicit-// env key: a generated key lives only in the local DB and silently losing it+// env key: a generated key lives only on the local disk and silently losing it// would make every stored API key undecryptable.function isDevFallbackAllowed(): boolean {return process.env.NODE_ENV !== 'production';@@ -41,16 +50,43 @@ function missingKeyError(): Error {'ENCRYPTION_KEY is required in production for API key encryption. ' +`Set a ${KEY_HEX_LEN}-char hex key (generate one with: ` +`node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"). ` +- 'Outside production a local DB-stored key is auto-generated.',+ 'Outside production a local key file is auto-generated next to the database.',);}+// The directory that holds the DB is the only place we can keep the key file+// next to (but not inside) the database. In-memory and anonymous databases have+// no such directory (db.memory is true, db.name is ":memory:" or ""), and Db+// backings without file metadata (memory undefined) have none either, so those+// callers fall back to the legacy settings-table behavior.+function keyFilePathFor(db: Db): string | null {+ if (db.memory !== false) return null;+ const dbPath = db.name;+ if (!dbPath || dbPath === ':memory:') return null;+ return path.join(path.dirname(dbPath), KEY_FILE_NAME);+}++// Write the hex key with a temp-file-and-rename so a crash never leaves a+// half-written key, and chmod 0600 so it isn't readable by other local users.+function writeKeyFileAtomic(keyFile: string, hex: string): void {+ const dir = path.dirname(keyFile);+ const tmp = path.join(dir, `${KEY_FILE_NAME}.tmp-${crypto.randomBytes(6).toString('hex')}`);+ fs.writeFileSync(tmp, hex, { mode: 0o600 });+ try { fs.chmodSync(tmp, 0o600); } catch { /* best effort — e.g. filesystems without POSIX modes */ }+ fs.renameSync(tmp, keyFile);+ try { fs.chmodSync(keyFile, 0o600); } catch { /* best effort */ }+}+/*** Initialize encryption key from env or an explicit local-dev fallback.* Must be called after DB is initialized.+ *+ * Precedence (dev fallback): ENCRYPTION_KEY env > existing key file next to the+ * DB > legacy `settings` table row (migrated to the file, then deleted) >+ * freshly generated key written to the file.*/export function initEncryptionKey(db: Db): void {- // 1. Check env var+ // 1. Explicit env key always wins.const envKey = process.env.ENCRYPTION_KEY;if (envKey && envKey !== PLACEHOLDER_KEY) {cachedKey = parseHexKey(envKey, 'env');@@ -61,18 +97,53 @@ export function initEncryptionKey(db: Db): void {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) {- cachedKey = parseHexKey(row.value, 'db');- console.warn('[crypto] No ENCRYPTION_KEY set — using auto-generated key from the local DB (dev only).');+ const keyFile = keyFilePathFor(db);++ // In-memory / anonymous DBs have no directory to hold a key file, so keep the+ // legacy settings-table behavior for them (ephemeral runs, most tests).+ if (!keyFile) {+ const row = db.prepare("SELECT value FROM settings WHERE key = 'encryption_key'").get() as { value: string } | undefined;+ if (row) {+ cachedKey = parseHexKey(row.value, 'db');+ console.warn('[crypto] No ENCRYPTION_KEY set — using an auto-generated in-memory key (dev only).');+ return;+ }+ cachedKey = crypto.randomBytes(KEY_BYTES);+ db.prepare("INSERT INTO settings (key, value) VALUES ('encryption_key', ?)").run(cachedKey.toString('hex'));+ console.warn('[crypto] No ENCRYPTION_KEY set — generated an in-memory dev key. Set ENCRYPTION_KEY for production.');+ return;+ }++ // 2. An existing key file next to the DB.+ if (fs.existsSync(keyFile)) {+ const value = fs.readFileSync(keyFile, 'utf8').trim();+ cachedKey = parseHexKey(value, 'file');+ console.warn(`[crypto] No ENCRYPTION_KEY set — using the auto-generated key at ${keyFile} (dev only). Set ENCRYPTION_KEY for production.`);+ return;+ }++ // 3. A legacy key still sitting in the settings table (older dev installs).+ // Migrate it to the key file so the DB stops storing the key that protects+ // it, confirm a decrypt round-trip with the migrated key, then drop the row.+ const legacy = db.prepare("SELECT value FROM settings WHERE key = 'encryption_key'").get() as { value: string } | undefined;+ if (legacy) {+ const migrated = parseHexKey(legacy.value, 'db');+ writeKeyFileAtomic(keyFile, migrated.toString('hex'));+ cachedKey = migrated;+ const probe = encrypt('roundtrip');+ if (decrypt(probe.encrypted, probe.iv, probe.authTag) !== 'roundtrip') {+ cachedKey = null;+ throw new Error('[crypto] Failed to migrate the DB-stored key to a key file: round-trip check failed.');+ }+ db.prepare("DELETE FROM settings WHERE key = 'encryption_key'").run();+ console.warn(`[crypto] Migrated the legacy DB-stored key to ${keyFile} and removed it from the database (dev only). Set ENCRYPTION_KEY for production.`);return;}- // 3. Generate and persist+ // 4. Generate a fresh key and persist it to the file.cachedKey = crypto.randomBytes(KEY_BYTES);- db.prepare("INSERT INTO settings (key, value) VALUES ('encryption_key', ?)").run(cachedKey.toString('hex'));- console.warn('[crypto] No ENCRYPTION_KEY set — generated and persisted a local dev key. Set ENCRYPTION_KEY for production.');+ writeKeyFileAtomic(keyFile, cachedKey.toString('hex'));+ console.warn(`[crypto] No ENCRYPTION_KEY set — generated a local dev key at ${keyFile}. Set ENCRYPTION_KEY for production.`);}function getEncryptionKey(): Buffer {diff --git a/server/src/lib/setup-code.ts b/server/src/lib/setup-code.tsnew file mode 100644index 00000000..6b217e2b--- /dev/null+++ b/server/src/lib/setup-code.ts@@ -0,0 +1,58 @@+import crypto from 'crypto';++// One-time first-run setup code.+//+// POST /api/auth/setup creates the first admin account while there are zero+// users. The server binds all interfaces by default, so an exposed fresh+// install could be claimed by whoever reaches it first. To gate that without+// hurting the local/desktop first-run experience, we mint a random code at boot+// when the dashboard is unclaimed and log it. A browser on the same machine+// (a loopback socket) never needs the code; a request from any other address+// must present it. The code is regenerated once per boot and cleared as soon as+// an account exists.++// Uppercase letters + digits, minus the visually ambiguous I, O, 0 and 1, so+// the code is easy to read from a log and type by hand.+const ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';+const CODE_LENGTH = 10;++let currentCode: string | null = null;++function generate(): string {+ const bytes = crypto.randomBytes(CODE_LENGTH);+ let out = '';+ for (let i = 0; i < CODE_LENGTH; i++) {+ out += ALPHABET[bytes[i]! % ALPHABET.length];+ }+ return out;+}++// Mint a fresh code and log it prominently. Call once at boot when there are+// zero accounts. Returns the code (handy for tests).+export function generateSetupCode(): string {+ currentCode = generate();+ console.log('');+ console.log(' First-run setup code: ' + currentCode);+ console.log(' A browser on this machine can finish setup without it. From any');+ console.log(' other device, enter this code to create the first account.');+ console.log('');+ return currentCode;+}++export function getSetupCode(): string | null {+ return currentCode;+}++export function clearSetupCode(): void {+ currentCode = null;+}++// Constant-time comparison against the active code. Returns false when no code+// is active or the input is not a matching string.+export function setupCodeMatches(provided: unknown): boolean {+ if (!currentCode || typeof provided !== 'string') return false;+ const a = Buffer.from(currentCode);+ const b = Buffer.from(provided);+ if (a.length !== b.length) return false;+ return crypto.timingSafeEqual(a, b);+}diff --git a/server/src/routes/auth.ts b/server/src/routes/auth.tsindex cf3afb01..f538a1cb 100644--- a/server/src/routes/auth.ts+++ b/server/src/routes/auth.ts@@ -9,6 +9,7 @@ import {validateSession,deleteSession,} from '../services/auth.js';+import { setupCodeMatches, clearSetupCode } from '../lib/setup-code.js';export const authRouter = Router();@@ -51,6 +52,18 @@ function bearer(req: Request): string | undefined {?? (req.headers['x-dashboard-token'] as string | undefined);}+// Is the caller connecting from the local machine? We check the actual socket+// peer address, NOT req.ip or X-Forwarded-For: those are attacker-controlled+// behind a proxy (and trust proxy is off by default anyway), so trusting them+// here would let a remote caller pretend to be local and skip the setup code.+function isLoopbackRemote(req: Request): boolean {+ let addr = req.socket.remoteAddress ?? '';+ // Node reports IPv4 loopback over a dual-stack socket as "::ffff:127.0.0.1".+ if (addr.startsWith('::ffff:')) addr = addr.slice(7);+ if (addr === '::1') return true;+ return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(addr);+}+// Has the dashboard been set up yet, and is this caller authenticated?authRouter.get('/status', (req: Request, res: Response) => {const session = validateSession(bearer(req));@@ -65,15 +78,33 @@ authRouter.get('/status', (req: Request, res: Response) => {// can't be used to add accounts once the dashboard is claimed.authRouter.post('/setup', (req: Request, res: Response) => {if (userCount() > 0) {+ clearSetupCode();res.status(409).json({ error: { message: 'Setup already completed. Use login instead.', type: 'setup_complete' } });return;}++ // Local/desktop first-run stays frictionless: a browser on this machine can+ // claim the dashboard without any code. A remote caller must present the+ // one-time setup code logged at boot, so an exposed fresh install can't be+ // claimed by a stranger who finds it first.+ if (!isLoopbackRemote(req) && !setupCodeMatches((req.body ?? {}).setupCode)) {+ res.status(403).json({+ error: {+ message: 'A setup code is required to create the first account from a remote device. ' ++ 'Check the server logs for the code, or open the dashboard from a browser on the machine running FreeLLMAPI.',+ type: 'setup_code_required',+ },+ });+ return;+ }+const parsed = credentialsSchema.safeParse(req.body);if (!parsed.success) {res.status(400).json({ error: { message: parsed.error.errors.map(e => e.message).join(', ') } });return;}const user = createUser(parsed.data.email, parsed.data.password);+ clearSetupCode(); // one-time: the dashboard is now claimedconst token = createSession(user.userId);res.status(201).json({ token, email: user.email });});diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex 5fa62431..7ddaf8b7 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -271,9 +271,16 @@ keysRouter.get('/export', (req: Request, res: Response) => {if (format === 'csv') {// CSV format: platform,key,labelconst escCsv = (v: string) => `"${v.replace(/"/g, '""')}"`;+ // CSV formula-injection guard: a spreadsheet treats a cell that starts with+ // =, +, -, @, tab or CR as a live formula, so a label like `=HYPERLINK(...)`+ // would execute on open. Prefix such cells with a single quote to force them+ // to be read as text. Applied only to free-text fields the user controls+ // (labels); the key value must round-trip verbatim for re-import, and the+ // platform is one of our own fixed enum values.+ const neutralize = (v: string) => (/^[=+\-@\t\r]/.test(v) ? `'${v}` : v);const header = 'platform,key,label';const lines = decryptedKeys.map(k =>- [escCsv(k.platform), escCsv(k.key), escCsv(k.label)].join(',')+ [escCsv(k.platform), escCsv(k.key), escCsv(neutralize(k.label))].join(','));const content = [header, ...lines].join('\n') + '\n';res.setHeader('Content-Type', 'text/csv; charset=utf-8');