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: stop fresh clones from silently failing to reach the server (#142)
Tashfeen51cc8d6aa29c
diff --git a/client/src/pages/KeysPage.tsx b/client/src/pages/KeysPage.tsxindex 2358aa61..25d854fe 100644--- a/client/src/pages/KeysPage.tsx+++ b/client/src/pages/KeysPage.tsx@@ -65,7 +65,7 @@ function UnifiedKeySection() {const [showKey, setShowKey] = useState(false)const [copied, setCopied] = useState(false)- const { data } = useQuery<{ apiKey: string }>({+ const { data, isError } = useQuery<{ apiKey: string }>({queryKey: ['unified-key'],queryFn: () => apiFetch('/api/settings/api-key'),})@@ -100,23 +100,31 @@ function UnifiedKeySection() {variant="ghost"size="sm"onClick={() => regenerate.mutate()}- disabled={regenerate.isPending}+ disabled={regenerate.isPending || isError}>Regenerate</Button></div>- <div className="flex items-center gap-2">- <code className="flex-1 font-mono text-xs bg-muted px-3 py-2 rounded-md select-all truncate tabular-nums">- {showKey ? apiKey : masked}- </code>- <Button variant="outline" size="sm" onClick={() => setShowKey(!showKey)}>- {showKey ? 'Hide' : 'Show'}- </Button>- <Button variant="outline" size="sm" onClick={copy}>- {copied ? 'Copied' : 'Copy'}- </Button>- </div>+ {isError ? (+ <div className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2.5 text-xs text-destructive">+ Can't reach the server on <code className="font-mono">{baseUrl.replace('/v1', '')}</code>. Make sure the+ backend is running — <code className="font-mono">npm run dev</code> starts both, and the server logs print+ under the <code className="font-mono">server</code> prefix.+ </div>+ ) : (+ <div className="flex items-center gap-2">+ <code className="flex-1 font-mono text-xs bg-muted px-3 py-2 rounded-md select-all truncate tabular-nums">+ {showKey ? apiKey : masked}+ </code>+ <Button variant="outline" size="sm" onClick={() => setShowKey(!showKey)}>+ {showKey ? 'Hide' : 'Show'}+ </Button>+ <Button variant="outline" size="sm" onClick={copy}>+ {copied ? 'Copied' : 'Copy'}+ </Button>+ </div>+ )}<div className="mt-4 grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5 text-xs"><span className="text-muted-foreground">Base URL</span>diff --git a/package.json b/package.jsonindex 81ca71b0..aa0a8d8e 100644--- a/package.json+++ b/package.json@@ -7,7 +7,7 @@"client"],"scripts": {- "dev": "concurrently \"npm run dev -w server\" \"npm run dev -w client\"",+ "dev": "concurrently --kill-others-on-fail --names server,client \"npm run dev -w server\" \"npm run dev -w client\"","test": "npm run test -w server && npm run test -w client --if-present","build": "npm run build -w server && npm run build -w client","build:server": "npm run build -w server"diff --git a/server/src/__tests__/lib/crypto-init.test.ts b/server/src/__tests__/lib/crypto-init.test.tsindex 1d6be5f0..a795e9c2 100644--- a/server/src/__tests__/lib/crypto-init.test.ts+++ b/server/src/__tests__/lib/crypto-init.test.ts@@ -56,21 +56,25 @@ describe('initEncryptionKey — input validation', () => {expect(() => initEncryptionKey(db)).toThrow(/Invalid ENCRYPTION_KEY \(env\)/);});- it('requires ENCRYPTION_KEY when dev fallback is not explicitly enabled', () => {+ it('auto-generates and persists a key outside production when ENCRYPTION_KEY is unset', () => {+ process.env.NODE_ENV = 'test';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();+ expect(() => initEncryptionKey(db)).not.toThrow();+ 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('does not load a DB-stored fallback key when dev fallback is disabled', () => {+ it('loads an existing DB-stored fallback key outside production', () => {+ process.env.NODE_ENV = 'test';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/);+ expect(() => initEncryptionKey(db)).not.toThrow();+ // The existing key is reused, not overwritten.+ const row = db.prepare("SELECT value FROM settings WHERE key = 'encryption_key'").get() as { value: string };+ expect(row.value).toBe('b'.repeat(64));});- it('requires ENCRYPTION_KEY in production even when DEV_MODE is set', () => {- process.env.DEV_MODE = 'true';+ it('requires ENCRYPTION_KEY in production and never persists a fallback key', () => {process.env.NODE_ENV = 'production';const db = freshDb();expect(() => initEncryptionKey(db)).toThrow(/ENCRYPTION_KEY is required/);@@ -78,9 +82,15 @@ describe('initEncryptionKey — input validation', () => {expect(row).toBeUndefined();});- it('still treats the placeholder as "not set" and allows explicit dev fallback generation', () => {+ it('does not load a DB-stored fallback key in production', () => {+ process.env.NODE_ENV = 'production';+ 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('treats the placeholder as "not set" and auto-generates outside production', () => {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();@@ -89,19 +99,9 @@ describe('initEncryptionKey — input validation', () => {});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 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 };- expect(row.value).toMatch(/^[0-9a-f]{64}$/);- });});diff --git a/server/src/index.ts b/server/src/index.tsindex 7085e67f..948a4acc 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -16,4 +16,11 @@ async function main() {});}-main().catch(console.error);+main().catch((err) => {+ // A boot failure (e.g. a missing production ENCRYPTION_KEY) must exit+ // non-zero rather than leaving a half-initialized process that never starts+ // listening — that silent state is what surfaces in the client as+ // "Can't reach the server".+ console.error('\n[server] Failed to start:\n ' + (err?.message ?? err) + '\n');+ process.exit(1);+});diff --git a/server/src/lib/crypto.ts b/server/src/lib/crypto.tsindex b4fc857b..7635a355 100644--- a/server/src/lib/crypto.ts+++ b/server/src/lib/crypto.ts@@ -26,14 +26,22 @@ function parseHexKey(value: string, source: 'env' | 'db'): Buffer {return Buffer.from(value, 'hex');}+// Outside production we auto-generate and persist a key so a fresh clone+// (`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+// would make every stored API key undecryptable.function isDevFallbackAllowed(): boolean {- return process.env.DEV_MODE === 'true' && process.env.NODE_ENV !== 'production';+ return 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.`,+ '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.',);}@@ -57,12 +65,14 @@ export function initEncryptionKey(db: Database.Database): void {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).');return;}// 3. Generate and persistcachedKey = 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.');}function getEncryptionKey(): Buffer {