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
harden router: credential placement, quota boundaries, cooldown visibility (#597)
Tashfeenc0d0b0369a6e
diff --git a/server/src/__tests__/db/hardening.test.ts b/server/src/__tests__/db/hardening.test.tsnew file mode 100644index 00000000..f996c25e--- /dev/null+++ b/server/src/__tests__/db/hardening.test.ts@@ -0,0 +1,77 @@+import fs from 'fs';+import os from 'os';+import path from 'path';+import { describe, it, expect, afterEach } from 'vitest';+import { connectDb } from '../../db/index.js';++const created: string[] = [];++function tempDbPath(): string {+ const p = path.join(os.tmpdir(), `freeapi-hardening-${Date.now()}-${Math.random()}.db`);+ created.push(p);+ return p;+}++afterEach(() => {+ for (const p of created.splice(0)) {+ for (const suffix of ['', '-wal', '-shm']) {+ try { fs.unlinkSync(`${p}${suffix}`); } catch { /* best effort */ }+ }+ }+});++describe('database runtime hardening', () => {+ it('sets a busy timeout so concurrent writers wait instead of erroring', () => {+ const db = connectDb(tempDbPath());+ // pragma() returns a scalar or a row list depending on driver; normalise.+ const raw = db.pragma('busy_timeout');+ const value = Array.isArray(raw)+ ? Number((raw[0] as Record<string, unknown>).timeout ?? (raw[0] as Record<string, unknown>).busy_timeout)+ : Number(raw);+ expect(value).toBe(5000);+ });++ it('keeps foreign keys and WAL on', () => {+ const db = connectDb(tempDbPath());+ const fk = db.pragma('foreign_keys');+ const fkValue = Array.isArray(fk)+ ? Number((fk[0] as Record<string, unknown>).foreign_keys)+ : Number(fk);+ expect(fkValue).toBe(1);++ const jm = db.pragma('journal_mode');+ const jmValue = Array.isArray(jm)+ ? String((jm[0] as Record<string, unknown>).journal_mode)+ : String(jm);+ expect(jmValue.toLowerCase()).toBe('wal');+ });++ it('restricts the database file to the owner', () => {+ const dbPath = tempDbPath();+ connectDb(dbPath);++ // The DB holds encrypted provider keys and the dashboard password hash.+ const mode = fs.statSync(dbPath).mode & 0o777;+ expect(mode & 0o077).toBe(0);+ });++ it('restricts the WAL sidecars once they exist', () => {+ const dbPath = tempDbPath();+ const db = connectDb(dbPath);+ // Force a write so -wal/-shm are created, then reconnect to chmod them.+ db.exec('CREATE TABLE IF NOT EXISTS probe (id INTEGER PRIMARY KEY)');+ db.exec('INSERT INTO probe (id) VALUES (1)');+ connectDb(dbPath);++ for (const suffix of ['-wal', '-shm']) {+ const target = `${dbPath}${suffix}`;+ if (!fs.existsSync(target)) continue;+ const mode = fs.statSync(target).mode & 0o777;+ expect(mode & 0o077).toBe(0);+ }+ });++ it('works for an in-memory database without touching the filesystem', () => {+ expect(() => connectDb(':memory:')).not.toThrow();+ });+});diff --git a/server/src/__tests__/lib/log-redaction.test.ts b/server/src/__tests__/lib/log-redaction.test.tsnew file mode 100644index 00000000..a43266cf--- /dev/null+++ b/server/src/__tests__/lib/log-redaction.test.ts@@ -0,0 +1,197 @@+import { describe, it, expect, afterEach } from 'vitest';+import { redactSecrets, installLogRedaction } from '../../lib/log-redaction.js';++/**+ * Fixtures are assembled at runtime rather than written out as literals.+ *+ * These patterns can only be exercised by strings that look like credentials, but+ * a source file holding such a literal is indistinguishable from a real leak to+ * GitHub push protection and to any other scanner — this file was rejected once+ * for exactly that. Building each value from a vendor prefix plus deterministic+ * filler keeps the coverage while guaranteeing the repo contains no credential,+ * synthetic or otherwise. The stride-based filler is also low-entropy on purpose,+ * so it cannot be mistaken for a live key.+ */+const ALNUM = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';+const LOWER = 'abcdefghijklmnopqrstuvwxyz0123456789';+const HEX = '0123456789abcdef';++function filler(length: number, charset: string = ALNUM): string {+ let out = '';+ for (let i = 0; i < length; i++) out += charset[(i * 7 + 3) % charset.length];+ return out;+}++// [label, prefix, body length, charset] — lengths mirror each vendor's real format.+const SPECS: Array<[string, string, number, string]> = [+ ['Google', 'AIza', 35, ALNUM],+ ['Groq', 'gsk_', 52, ALNUM],+ ['Cerebras', 'csk-', 48, LOWER],+ ['NVIDIA', 'nvapi-', 64, ALNUM],+ ['GitHub PAT', 'github_pat_', 82, ALNUM],+ ['HuggingFace', 'hf_', 34, ALNUM],+ ['OpenRouter', 'sk-or-v1-', 64, HEX],+ ['Cloudflare', 'cfut_', 44, ALNUM],+ ['Vercel', 'vck_', 56, ALNUM],+ ['Aion', 'alv2_', 43, ALNUM],+ ['Pollinations', 'sk_', 32, ALNUM],+ ['Mistral (bare)', '', 32, ALNUM],+ ['Own gateway key', 'freellmapi-', 48, HEX],+];++const SAMPLES: Array<[string, string]> = SPECS.map(+ ([label, prefix, len, charset]) => [label, prefix + filler(len, charset)],+);++// Dotted composite shape (Chutes / Z.ai / Ollama cloud): id.id.secret+SAMPLES.push(['Chutes', `cpk_${filler(32, HEX)}.${filler(32, HEX)}.${filler(32)}`]);++const GOOGLE_LIKE = `AIza${filler(35)}`;+const GROQ_LIKE = `gsk_${filler(52)}`;+const UNIFIED_LIKE = `freellmapi-${filler(48, HEX)}`;++describe('redactSecrets', () => {+ for (const [label, secret] of SAMPLES) {+ it(`redacts a ${label} key`, () => {+ const out = redactSecrets(`request failed with key ${secret} on attempt 2`);+ expect(out).not.toContain(secret);+ expect(out).toContain('attempt 2');+ });+ }++ it('redacts a key embedded in a URL query string', () => {+ const secret = GOOGLE_LIKE;+ const out = redactSecrets(+ `POST https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro:generateContent?key=${secret} 429`,+ );+ expect(out).not.toContain(secret);+ // The URL itself must survive — it is the diagnostic value of the line.+ expect(out).toContain('generativelanguage.googleapis.com');+ expect(out).toContain('429');+ });++ it('redacts Authorization bearer tokens', () => {+ const out = redactSecrets('headers: { Authorization: Bearer abc123def456ghi789jkl012 }');+ expect(out).not.toContain('abc123def456ghi789jkl012');+ expect(out).toContain('Bearer [redacted]');+ });++ it('redacts an x-goog-api-key header value', () => {+ const secret = GOOGLE_LIKE;+ const out = redactSecrets(`{"x-goog-api-key":"${secret}"}`);+ expect(out).not.toContain(secret);+ });++ it('redacts assignment forms for secret-ish names', () => {+ const out = redactSecrets('ENCRYPTION_KEY=0123456789abcdef api_key: swordfishsecret');+ expect(out).not.toContain('0123456789abcdef');+ expect(out).not.toContain('swordfishsecret');+ });++ it('leaves ordinary log lines untouched', () => {+ const line = 'routed groq/llama-3.3-70b in 412ms (attempt 1, 250 tokens)';+ expect(redactSecrets(line)).toBe(line);+ });++ it('does not mangle short identifiers or model names', () => {+ const line = 'model gemini-3-pro-preview key_id 42 status healthy';+ expect(redactSecrets(line)).toBe(line);+ });++ it('emits exactly one marker when two patterns cover the same value', () => {+ // "API key: freellmapi-..." matches both the prefix rule and the key=value+ // rule; without a guard the second pass rewrote the first marker and left a+ // trailing bracket ("[redacted-key]]").+ const out = redactSecrets(+ ` Your unified API key: ${UNIFIED_LIKE}`,+ );+ expect(out).not.toContain(']]');+ expect(out.match(/\[redacted/g)).toHaveLength(1);+ });++ it('is idempotent — redacting twice changes nothing', () => {+ const once = redactSecrets('Authorization: Bearer abc123def456ghi789jkl012');+ expect(redactSecrets(once)).toBe(once);+ });+});++describe('installLogRedaction', () => {+ let restore: (() => void) | null = null;++ afterEach(() => {+ restore?.();+ restore = null;+ });++ it('redacts secrets passed to console.log and console.error', () => {+ const seen: unknown[][] = [];+ const origLog = console.log;+ const origErr = console.error;+ console.log = (...args: unknown[]) => { seen.push(args); };+ console.error = (...args: unknown[]) => { seen.push(args); };++ restore = installLogRedaction();+ const secret = GROQ_LIKE;+ console.log(`using ${secret}`);+ console.error(new Error(`auth failed for ${secret}`));++ restore();+ console.log = origLog;+ console.error = origErr;+ restore = null;++ expect(seen).toHaveLength(2);+ expect(String(seen[0]![0])).not.toContain(secret);+ const err = seen[1]![0] as Error;+ expect(err).toBeInstanceOf(Error);+ expect(err.message).not.toContain(secret);+ });++ it('redacts secrets nested inside a logged object, keeping it an object', () => {+ const seen: unknown[][] = [];+ const origLog = console.log;+ console.log = (...args: unknown[]) => { seen.push(args); };++ restore = installLogRedaction();+ const secret = GOOGLE_LIKE;+ console.log({ platform: 'google', apiKey: secret });++ restore();+ console.log = origLog;+ restore = null;++ const logged = seen[0]![0] as Record<string, unknown>;+ expect(typeof logged).toBe('object');+ expect(logged.platform).toBe('google');+ expect(JSON.stringify(logged)).not.toContain(secret);+ });++ it('passes through values it cannot serialise', () => {+ const seen: unknown[][] = [];+ const origLog = console.log;+ console.log = (...args: unknown[]) => { seen.push(args); };++ restore = installLogRedaction();+ const cyclic: Record<string, unknown> = { name: 'loop' };+ cyclic.self = cyclic;+ console.log(cyclic);++ restore();+ console.log = origLog;+ restore = null;++ expect(seen[0]![0]).toBe(cyclic);+ });++ it('is idempotent', () => {+ restore = installLogRedaction();+ const second = installLogRedaction();+ second();+ const seen: unknown[][] = [];+ const origLog = console.log;+ console.log = (...args: unknown[]) => { seen.push(args); };+ console.log('plain line');+ console.log = origLog;+ expect(String(seen[0]![0])).toBe('plain line');+ });+});diff --git a/server/src/__tests__/providers/google-auth-header.test.ts b/server/src/__tests__/providers/google-auth-header.test.tsnew file mode 100644index 00000000..fdd012a1--- /dev/null+++ b/server/src/__tests__/providers/google-auth-header.test.ts@@ -0,0 +1,77 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { GoogleProvider } from '../../providers/google.js';++// The Gemini REST API accepts the key either as a ?key= query param or an+// x-goog-api-key header. The query form leaks the credential into proxy access+// logs, browser history and any error string that echoes the request URL, so+// every call site must use the header and no URL may carry the key.+// Deliberately not key-shaped: these assertions only care where the string is+// placed, and a realistic-looking key here would trip credential scanners.+const KEY = 'test-google-key-not-a-real-credential';++function headerFrom(init: RequestInit | undefined): Record<string, string> {+ return (init?.headers ?? {}) as Record<string, string>;+}++describe('GoogleProvider credential placement', () => {+ let provider: GoogleProvider;++ beforeEach(() => {+ vi.restoreAllMocks();+ provider = new GoogleProvider();+ });++ it('sends the key as x-goog-api-key on chatCompletion, never in the URL', async () => {+ const fetchSpy = vi.spyOn(global, 'fetch').mockResolvedValueOnce({+ ok: true,+ json: () => Promise.resolve({+ candidates: [{ content: { parts: [{ text: 'hi' }] }, finishReason: 'STOP' }],+ usageMetadata: { promptTokenCount: 1, candidatesTokenCount: 1, totalTokenCount: 2 },+ }),+ } as any);++ await provider.chatCompletion(KEY, [{ role: 'user', content: 'Hi' }], 'gemini-2.5-pro');++ const [url, init] = fetchSpy.mock.calls[0]!;+ expect(String(url)).not.toContain(KEY);+ expect(String(url)).not.toContain('key=');+ expect(headerFrom(init as RequestInit)['x-goog-api-key']).toBe(KEY);+ });++ it('sends the key as x-goog-api-key on the streaming call, keeping alt=sse', async () => {+ const fetchSpy = vi.spyOn(global, 'fetch').mockResolvedValueOnce({+ ok: true,+ body: { getReader: () => ({ read: () => Promise.resolve({ done: true, value: undefined }) }) },+ } as any);++ const stream = provider.streamChatCompletion(+ KEY,+ [{ role: 'user', content: 'Hi' }],+ 'gemini-2.5-pro',+ );+ // Drive the generator far enough to issue the request.+ await stream.next().catch(() => undefined);++ const [url, init] = fetchSpy.mock.calls[0]!;+ expect(String(url)).not.toContain(KEY);+ expect(String(url)).not.toContain('key=');+ expect(String(url)).toContain('alt=sse');+ expect(headerFrom(init as RequestInit)['x-goog-api-key']).toBe(KEY);+ });++ it('sends the key as x-goog-api-key on validateKey, never in the URL', async () => {+ const fetchSpy = vi.spyOn(global, 'fetch').mockResolvedValueOnce({+ ok: true,+ status: 200,+ json: () => Promise.resolve({ models: [] }),+ headers: new Headers(),+ } as any);++ await provider.validateKey(KEY);++ const [url, init] = fetchSpy.mock.calls[0]!;+ expect(String(url)).not.toContain(KEY);+ expect(String(url)).not.toContain('key=');+ expect(headerFrom(init as RequestInit)['x-goog-api-key']).toBe(KEY);+ });+});diff --git a/server/src/__tests__/routes/keys-cooldowns.test.ts b/server/src/__tests__/routes/keys-cooldowns.test.tsnew file mode 100644index 00000000..78feaf1d--- /dev/null+++ b/server/src/__tests__/routes/keys-cooldowns.test.ts@@ -0,0 +1,115 @@+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, isGatedApiPath } from '../helpers/auth.js';+import { setCooldown, isOnCooldown } from '../../services/ratelimit.js';++let dashToken = '';++async function request(app: Express, method: string, path: string, body?: any) {+ const server = app.listen(0);+ const addr = server.address() as any;+ const url = `http://127.0.0.1:${addr.port}${path}`;++ const res = await fetch(url, {+ method,+ headers: {+ ...(body ? { 'Content-Type': 'application/json' } : {}),+ ...(isGatedApiPath(path) ? { Authorization: `Bearer ${dashToken}` } : {}),+ },+ body: body ? JSON.stringify(body) : undefined,+ });++ const data = await res.json().catch(() => null);+ server.close();+ return { status: res.status, body: data };+}++async function createKey(app: Express, platform: string, key: string) {+ const { body } = await request(app, 'POST', '/api/keys', { platform, key, label: `${platform} key` });+ return body.id as number;+}++describe('Key cooldown visibility and clearing', () => {+ let app: Express;++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();+ dashToken = mintDashboardToken();+ });++ beforeEach(() => {+ const db = getDb();+ db.prepare('DELETE FROM api_keys').run();+ db.prepare('DELETE FROM rate_limit_cooldowns').run();+ });++ it('reports an empty cooldown list for a key that is not benched', async () => {+ await createKey(app, 'groq', 'gsk_testkeyvalue123456');+ const { status, body } = await request(app, 'GET', '/api/keys');+ expect(status).toBe(200);+ expect(body[0].cooldowns).toEqual([]);+ });++ it('surfaces active cooldowns on the key list', async () => {+ const id = await createKey(app, 'groq', 'gsk_testkeyvalue123456');+ setCooldown('groq', 'llama-3.3-70b', id, 5 * 60_000);++ const { body } = await request(app, 'GET', '/api/keys');+ const key = body.find((k: any) => k.id === id);++ expect(key.cooldowns).toHaveLength(1);+ expect(key.cooldowns[0].modelId).toBe('llama-3.3-70b');+ expect(key.cooldowns[0].remainingMs).toBeGreaterThan(0);+ // The point of the field: status still reads healthy while the router skips it.+ expect(key.status).not.toBe('cooling');+ });++ it('DELETE /api/keys/:id/cooldowns clears them and reports the count', async () => {+ const id = await createKey(app, 'groq', 'gsk_testkeyvalue123456');+ setCooldown('groq', 'llama-3.3-70b', id, 60 * 60_000);+ setCooldown('groq', 'llama-3.1-8b', id, 60 * 60_000);++ const { status, body } = await request(app, 'DELETE', `/api/keys/${id}/cooldowns`);+ expect(status).toBe(200);+ expect(body.cleared).toBe(2);++ expect(isOnCooldown('groq', 'llama-3.3-70b', id)).toBe(false);+ const after = await request(app, 'GET', '/api/keys');+ expect(after.body.find((k: any) => k.id === id).cooldowns).toEqual([]);+ });++ it('does not disturb cooldowns belonging to another key', async () => {+ const a = await createKey(app, 'groq', 'gsk_testkeyvalueAAAAAA');+ const b = await createKey(app, 'cerebras', 'csk-testkeyvalueBBBBBB');+ setCooldown('groq', 'llama-3.3-70b', a, 60 * 60_000);+ setCooldown('cerebras', 'qwen-3-coder', b, 60 * 60_000);++ await request(app, 'DELETE', `/api/keys/${a}/cooldowns`);++ expect(isOnCooldown('groq', 'llama-3.3-70b', a)).toBe(false);+ expect(isOnCooldown('cerebras', 'qwen-3-coder', b)).toBe(true);+ });++ it('returns 404 for an unknown key and 400 for a non-numeric id', async () => {+ const missing = await request(app, 'DELETE', '/api/keys/987654/cooldowns');+ expect(missing.status).toBe(404);++ const bad = await request(app, 'DELETE', '/api/keys/abc/cooldowns');+ expect(bad.status).toBe(400);+ });++ it('requires dashboard auth', async () => {+ const id = await createKey(app, 'groq', 'gsk_testkeyvalue123456');+ const server = app.listen(0);+ const addr = server.address() as any;+ const res = await fetch(`http://127.0.0.1:${addr.port}/api/keys/${id}/cooldowns`, {+ method: 'DELETE',+ });+ server.close();+ expect(res.status).toBe(401);+ });+});diff --git a/server/src/__tests__/services/declarative-config-profiles.test.ts b/server/src/__tests__/services/declarative-config-profiles.test.tsnew file mode 100644index 00000000..1d2a7d56--- /dev/null+++ b/server/src/__tests__/services/declarative-config-profiles.test.ts@@ -0,0 +1,112 @@+import { describe, it, expect, beforeAll, beforeEach } from 'vitest';+import { initDb, getDb } from '../../db/index.js';+import { applyDeclarativeConfig } from '../../services/declarative-config.js';+import { resolveRoutingChain } from '../../services/router.js';++/**+ * A model needs a row in BOTH fallback_config and profile_models to be routable:+ * once a profile is active the router reads profile_models. routes/keys.ts calls+ * ensureModelInProfiles after its chain insert; declarative config did not, so an+ * env-configured custom model showed up in the dashboard and was never selected.+ */+describe('declarative config keeps profile membership in sync', () => {+ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ });++ beforeEach(() => {+ const db = getDb();+ // Children first: fallback_config and profile_models both reference models.id.+ db.prepare("DELETE FROM profile_models WHERE model_db_id IN (SELECT id FROM models WHERE platform = 'custom')").run();+ db.prepare("DELETE FROM fallback_config WHERE model_db_id IN (SELECT id FROM models WHERE platform = 'custom')").run();+ db.prepare("DELETE FROM models WHERE platform = 'custom'").run();+ db.prepare('DELETE FROM api_keys').run();+ });++ function profileRowCount(modelDbId: number): number {+ return (getDb().prepare(+ 'SELECT COUNT(*) AS n FROM profile_models WHERE model_db_id = ?',+ ).get(modelDbId) as { n: number }).n;+ }++ it('adds a declaratively-registered custom model to every profile', () => {+ const db = getDb();+ const profileCount = (db.prepare('SELECT COUNT(*) AS n FROM profiles').get() as { n: number }).n;+ expect(profileCount).toBeGreaterThan(0);++ applyDeclarativeConfig({+ customProviders: [{+ baseUrl: 'http://127.0.0.1:9124/v1',+ apiKey: 'local-key',+ label: 'Profile sync',+ models: [{ model: 'profile-sync-chat', displayName: 'Profile Sync Chat' }],+ }],+ });++ const model = db.prepare(+ "SELECT id FROM models WHERE platform = 'custom' AND model_id = 'profile-sync-chat'",+ ).get() as { id: number } | undefined;+ expect(model).toBeDefined();++ // Present in the chain...+ const inChain = db.prepare('SELECT 1 FROM fallback_config WHERE model_db_id = ?').get(model!.id);+ expect(inChain).toBeDefined();+ // ...and in every profile, which is what the router actually reads.+ expect(profileRowCount(model!.id)).toBe(profileCount);+ });++ it('makes the model reachable through the active profile chain', () => {+ const db = getDb();+ const profile = db.prepare('SELECT id FROM profiles ORDER BY id LIMIT 1').get() as { id: number };+ db.prepare(+ "INSERT INTO settings (key, value) VALUES ('active_profile_id', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",+ ).run(String(profile.id));++ applyDeclarativeConfig({+ customProviders: [{+ baseUrl: 'http://127.0.0.1:9125/v1',+ apiKey: 'local-key',+ label: 'Reachable',+ models: [{ model: 'reachable-chat', displayName: 'Reachable Chat' }],+ }],+ });++ // resolveRoutingChain('auto') goes through the same active-profile lookup the+ // proxy uses, so this asserts real reachability rather than table contents.+ const { chain } = resolveRoutingChain('auto');+ expect(chain.some(entry => entry.model_id === 'reachable-chat')).toBe(true);++ // The model must also be in the ACTIVE profile specifically, not just some profile.+ const model = db.prepare(+ "SELECT id FROM models WHERE platform = 'custom' AND model_id = 'reachable-chat'",+ ).get() as { id: number };+ const inActiveProfile = db.prepare(+ 'SELECT 1 FROM profile_models WHERE profile_id = ? AND model_db_id = ?',+ ).get(profile.id, model.id);+ expect(inActiveProfile).toBeDefined();++ db.prepare("DELETE FROM settings WHERE key = 'active_profile_id'").run();+ });++ it('is idempotent — re-applying does not duplicate profile rows', () => {+ const config = {+ customProviders: [{+ baseUrl: 'http://127.0.0.1:9126/v1',+ apiKey: 'local-key',+ label: 'Idempotent',+ models: [{ model: 'idempotent-chat', displayName: 'Idempotent Chat' }],+ }],+ };++ applyDeclarativeConfig(config);+ applyDeclarativeConfig(config);++ const model = getDb().prepare(+ "SELECT id FROM models WHERE platform = 'custom' AND model_id = 'idempotent-chat'",+ ).get() as { id: number };+ const profileCount = (getDb().prepare('SELECT COUNT(*) AS n FROM profiles').get() as { n: number }).n;++ expect(profileRowCount(model.id)).toBe(profileCount);+ });+});diff --git a/server/src/__tests__/services/ratelimit-daily-boundary.test.ts b/server/src/__tests__/services/ratelimit-daily-boundary.test.tsnew file mode 100644index 00000000..8b52ebd5--- /dev/null+++ b/server/src/__tests__/services/ratelimit-daily-boundary.test.ts@@ -0,0 +1,155 @@+import { describe, it, expect, beforeEach } from 'vitest';+import { initDb, getDb } from '../../db/index.js';+import {+ providerDailyRequestCount,+ providerDailyTokenCount,+ canUseProvider,+ getActiveCooldownsForKeys,+ clearCooldownsForKey,+ setCooldown,+ isOnCooldown,+} from '../../services/ratelimit.js';++const HOUR = 60 * 60 * 1000;++function utcMidnight(now: number): number {+ return new Date(now).setUTCHours(0, 0, 0, 0);+}++/** Insert a usage row at an explicit timestamp, bypassing recordRequest so the+ * test controls where the row sits relative to the UTC day boundary. */+function seedUsage(+ platform: string,+ modelId: string,+ keyId: number,+ kind: 'request' | 'tokens',+ tokens: number,+ atMs: number,+) {+ getDb().prepare(`+ INSERT INTO rate_limit_usage (platform, model_id, key_id, kind, tokens, created_at_ms)+ VALUES (?, ?, ?, ?, ?, ?)+ `).run(platform, modelId, keyId, kind, tokens, atMs);+}++describe('provider daily caps use a midnight-UTC boundary', () => {+ let keyId: number;++ beforeEach(() => {+ initDb(':memory:');+ keyId = Math.floor(Math.random() * 1_000_000);+ });++ it('excludes usage from before midnight UTC', () => {+ // "Now" is fixed at 02:00 UTC so there is a real yesterday to test against.+ const now = utcMidnight(Date.now()) + 2 * HOUR;+ const beforeMidnight = utcMidnight(now) - HOUR; // 23:00 yesterday+ const afterMidnight = utcMidnight(now) + 30 * 60_000; // 00:30 today++ seedUsage('openrouter', 'm1', keyId, 'request', 0, beforeMidnight);+ seedUsage('openrouter', 'm1', keyId, 'request', 0, beforeMidnight + 60_000);+ seedUsage('openrouter', 'm1', keyId, 'request', 0, afterMidnight);++ // A sliding 24h window would count all three; only today's should count.+ expect(providerDailyRequestCount('openrouter', keyId, now)).toBe(1);+ });++ it('counts every request made since midnight UTC', () => {+ const now = utcMidnight(Date.now()) + 6 * HOUR;+ // Offset by 1ms: the usage window is half-open (created_at_ms > cutoff), so a+ // row stamped exactly at the boundary belongs to the day that just started.+ for (let i = 0; i < 4; i++) {+ seedUsage('openrouter', `m${i}`, keyId, 'request', 0, utcMidnight(now) + 1 + i * HOUR);+ }+ expect(providerDailyRequestCount('openrouter', keyId, now)).toBe(4);+ });++ it('releases a capped provider once the day boundary passes', () => {+ process.env.PROVIDER_DAILY_REQUEST_CAP_OPENROUTER = '2';+ try {+ const yesterdayEvening = utcMidnight(Date.now()) - 2 * HOUR;+ seedUsage('openrouter', 'm1', keyId, 'request', 0, yesterdayEvening);+ seedUsage('openrouter', 'm1', keyId, 'request', 0, yesterdayEvening + 60_000);++ // Evaluated at 23:59 yesterday the cap is spent...+ expect(canUseProvider('openrouter', keyId, yesterdayEvening + 2 * HOUR - 1)).toBe(false);+ // ...and immediately available again after the UTC reset, which a sliding+ // window would not do until a full 24h had elapsed.+ expect(canUseProvider('openrouter', keyId, utcMidnight(Date.now()) + 60_000)).toBe(true);+ } finally {+ delete process.env.PROVIDER_DAILY_REQUEST_CAP_OPENROUTER;+ }+ });++ it('applies the same boundary to token accounting', () => {+ const now = utcMidnight(Date.now()) + 3 * HOUR;+ seedUsage('navy', 'm1', keyId, 'tokens', 5_000, utcMidnight(now) - HOUR);+ seedUsage('navy', 'm1', keyId, 'tokens', 1_200, utcMidnight(now) + HOUR);++ expect(providerDailyTokenCount('navy', keyId, now)).toBe(1_200);+ });++ it('counts nothing at exactly midnight UTC', () => {+ const midnight = utcMidnight(Date.now());+ seedUsage('openrouter', 'm1', keyId, 'request', 0, midnight - 60_000);+ expect(providerDailyRequestCount('openrouter', keyId, midnight)).toBe(0);+ });+});++describe('cooldown visibility and manual clear', () => {+ beforeEach(() => {+ initDb(':memory:');+ });++ it('reports active cooldowns grouped by key with remaining time', () => {+ setCooldown('groq', 'llama-3.3-70b', 11, 60_000);+ setCooldown('groq', 'llama-3.1-8b', 11, 120_000);+ setCooldown('cerebras', 'qwen-3-coder', 12, 90_000);++ const grouped = getActiveCooldownsForKeys([11, 12]);++ expect(grouped.get(11)).toHaveLength(2);+ expect(grouped.get(12)).toHaveLength(1);+ const first = grouped.get(11)!.map(c => c.modelId).sort();+ expect(first).toEqual(['llama-3.1-8b', 'llama-3.3-70b']);+ for (const cd of grouped.get(11)!) {+ expect(cd.remainingMs).toBeGreaterThan(0);+ expect(cd.expiresAtMs).toBeGreaterThan(Date.now());+ }+ });++ it('omits expired cooldowns and keys with none', () => {+ setCooldown('groq', 'llama-3.3-70b', 21, -5_000); // already expired+ const grouped = getActiveCooldownsForKeys([21, 22]);+ expect(grouped.get(21)).toBeUndefined();+ expect(grouped.get(22)).toBeUndefined();+ });++ it('returns an empty map for an empty or invalid key list', () => {+ expect(getActiveCooldownsForKeys([]).size).toBe(0);+ expect(getActiveCooldownsForKeys([Number.NaN]).size).toBe(0);+ });++ it('clears every cooldown for one key and leaves other keys alone', () => {+ setCooldown('groq', 'llama-3.3-70b', 31, 10 * 60_000);+ setCooldown('groq', 'llama-3.1-8b', 31, 10 * 60_000);+ setCooldown('groq', 'llama-3.3-70b', 32, 10 * 60_000);++ expect(isOnCooldown('groq', 'llama-3.3-70b', 31)).toBe(true);++ const cleared = clearCooldownsForKey(31);++ expect(cleared).toBe(2);+ // Both the persisted row and the in-memory entry must be gone, or the next+ // isOnCooldown would re-hydrate the cooldown from whichever survived.+ expect(isOnCooldown('groq', 'llama-3.3-70b', 31)).toBe(false);+ expect(isOnCooldown('groq', 'llama-3.1-8b', 31)).toBe(false);+ expect(isOnCooldown('groq', 'llama-3.3-70b', 32)).toBe(true);+ expect(getActiveCooldownsForKeys([31]).size).toBe(0);+ });++ it('reports zero when a key has nothing to clear', () => {+ expect(clearCooldownsForKey(999_001)).toBe(0);+ expect(clearCooldownsForKey(Number.NaN)).toBe(0);+ });+});diff --git a/server/src/__tests__/services/ratelimit.test.ts b/server/src/__tests__/services/ratelimit.test.tsindex 213059f9..a6d1d868 100644--- a/server/src/__tests__/services/ratelimit.test.ts+++ b/server/src/__tests__/services/ratelimit.test.ts@@ -402,4 +402,22 @@ describe('parseRetryAfterMs', () => {expect(parseRetryAfterMs('')).toBeUndefined();expect(parseRetryAfterMs('soon')).toBeUndefined();});++ const DAY_MS = 24 * 60 * 60 * 1000;++ it('clamps an absurd delta-seconds value to 24h', () => {+ // Feeds the cooldown expiry directly, so an unclamped value benches the key+ // effectively forever.+ expect(parseRetryAfterMs('99999999999')).toBe(DAY_MS);+ expect(parseRetryAfterMs(String(DAY_MS / 1000 + 1))).toBe(DAY_MS);+ });++ it('clamps a far-future HTTP-date to 24h', () => {+ expect(parseRetryAfterMs(new Date(Date.now() + 30 * DAY_MS).toUTCString())).toBe(DAY_MS);+ });++ it('leaves values at or under 24h untouched', () => {+ expect(parseRetryAfterMs(String(DAY_MS / 1000))).toBe(DAY_MS);+ expect(parseRetryAfterMs('3600')).toBe(3_600_000);+ });});diff --git a/server/src/db/index.ts b/server/src/db/index.tsindex d728daf7..0db2ac1e 100644--- a/server/src/db/index.ts+++ b/server/src/db/index.ts@@ -70,11 +70,32 @@ export function connectDb(db = factory(resolvedPath);if (!isMemory) db.pragma('journal_mode = WAL');db.pragma('foreign_keys = ON');+ // The dashboard and the proxy hot path write concurrently; without a busy+ // timeout the loser of a write race gets SQLITE_BUSY immediately and the+ // request fails. Five seconds is far longer than any write here takes.+ db.pragma('busy_timeout = 5000');++ if (!isMemory) restrictDbFilePermissions(resolvedPath);console.log(`Database initialized at ${resolvedPath}`);return db;}+/** Restrict the DB and its WAL sidecars to the owner. The file holds encrypted+ * provider keys plus the dashboard password hash, so it must not be readable by+ * other local users. Best-effort: filesystems without POSIX modes (Windows,+ * some mounts) throw, and that must not stop startup. */+function restrictDbFilePermissions(resolvedPath: string): void {+ for (const suffix of ['', '-wal', '-shm']) {+ const target = `${resolvedPath}${suffix}`;+ try {+ if (fs.existsSync(target)) fs.chmodSync(target, 0o600);+ } catch {+ // Non-fatal: permissions are a hardening measure, not a correctness one.+ }+ }+}+export function initDb(dbPath?: string,opts?: { ensureDir?: boolean; factory?: DbFactory },diff --git a/server/src/db/migrations/20260101_000000_legacy_baseline.ts b/server/src/db/migrations/20260101_000000_legacy_baseline.tsindex a09e2da8..79fb2a04 100644--- a/server/src/db/migrations/20260101_000000_legacy_baseline.ts+++ b/server/src/db/migrations/20260101_000000_legacy_baseline.ts@@ -2241,7 +2241,11 @@ function ensureUnifiedKey(db: Db) {if (!existing) {const key = `freellmapi-${crypto.randomBytes(24).toString('hex')}`;db.prepare("INSERT INTO settings (key, value) VALUES ('unified_api_key', ?)").run(key);- console.log(`\n Your unified API key: ${key}\n`);+ // Straight to stdout, deliberately bypassing the console redaction installed+ // in index.ts: this is the one intentional disclosure of the key, and the+ // operator needs to copy it to configure a client. Every other path that+ // echoes a credential is an accident and stays redacted.+ process.stdout.write(`\n Your unified API key: ${key}\n\n`);}}diff --git a/server/src/index.ts b/server/src/index.tsindex 09593842..b202c14a 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -13,6 +13,12 @@ import { restoreDbBackupIfNeeded, startDbBackupPump } from './lib/db-backup.js';import { userCount } from './services/auth.js';import { generateSetupCode } from './lib/setup-code.js';import { warnOnEnvDrift } from './lib/env-drift.js';+import { installLogRedaction } from './lib/log-redaction.js';++// Before any other statement runs, so no provider key can reach stdout — users+// paste server output into bug reports. Module scope, not inside main(), so it+// is active for the whole process lifetime including startup logging.+installLogRedaction();async function main() {const config = loadConfig();diff --git a/server/src/lib/log-redaction.ts b/server/src/lib/log-redaction.tsnew file mode 100644index 00000000..92155623--- /dev/null+++ b/server/src/lib/log-redaction.ts@@ -0,0 +1,145 @@+/**+ * Console-level credential redaction.+ *+ * Provider keys reach stdout through many paths that no single call site owns:+ * a provider adapter logging a failed URL, an undici error whose stack embeds+ * the request, a debug line someone adds during triage. Users routinely paste+ * that output into GitHub issues. Patching console once at boot is the only+ * place that covers every path, including code that has not been written yet.+ *+ * Distinct from lib/error-redaction.ts, which sanitises a single provider error+ * string for API responses: that one also strips every URL and truncates to 240+ * chars, which would make server logs unreadable. This module removes+ * credentials and nothing else.+ */++const REDACTED = '[redacted-key]';++// Ordered most-specific first: prefixed provider keys, then bearer tokens, then+// key=value forms, then a conservative high-entropy catch-all.+const PATTERNS: Array<[RegExp, string]> = [+ // Known provider key prefixes. Grouped by shape rather than by vendor so a new+ // provider using an existing convention is covered without an edit here.+ [/\bsk-[A-Za-z0-9_\-/+=]{8,}/g, REDACTED], // OpenAI-style: OpenRouter, SiliconFlow, Nara, navy, SEA-LION, Agnes, OpenCode+ [/\bsk_[A-Za-z0-9_\-]{8,}/g, REDACTED], // Pollinations+ [/\bgsk_[A-Za-z0-9_\-]{8,}/g, REDACTED], // Groq+ [/\bcsk-[A-Za-z0-9_\-]{8,}/g, REDACTED], // Cerebras+ [/\bnvapi-[A-Za-z0-9_\-]{8,}/g, REDACTED], // NVIDIA+ [/\bAIza[0-9A-Za-z_\-]{20,}/g, REDACTED], // Google+ [/\bgithub_pat_[A-Za-z0-9_]{20,}/g, REDACTED], // GitHub fine-grained+ [/\bghp_[A-Za-z0-9]{20,}/g, REDACTED], // GitHub classic+ [/\bhf_[A-Za-z0-9]{16,}/g, REDACTED], // HuggingFace+ [/\bcfut_[A-Za-z0-9]{16,}/g, REDACTED], // Cloudflare+ [/\bvck_[A-Za-z0-9]{16,}/g, REDACTED], // Vercel+ [/\bcpk_[A-Za-z0-9.]{16,}/g, REDACTED], // Chutes+ [/\balv2_[A-Za-z0-9]{16,}/g, REDACTED], // Aion Labs+ [/\brqsty-sk-[A-Za-z0-9_\-/+=]{16,}/g, REDACTED], // Requesty+ [/\bfreellmapi-[A-Za-z0-9_\-]{8,}/g, REDACTED], // Keys this gateway issues++ // Authorization headers, in prose or serialised objects. The (?!\[redacted)+ // guard keeps a value an earlier pattern already replaced from being matched a+ // second time, which would otherwise append a stray bracket to the marker.+ [/\bBearer\s+(?!\[redacted)[A-Za-z0-9._~+/\-]+=*/gi, 'Bearer [redacted]'],+ [/(\bx-goog-api-key\b["']?\s*[:=]\s*["']?)(?!\[redacted)[^"',\s}\]&]+/gi, `$1${REDACTED}`],+ [/(\bx-api-key\b["']?\s*[:=]\s*["']?)(?!\[redacted)[^"',\s}\]&]+/gi, `$1${REDACTED}`],++ // key=/token=/secret= in query strings, env dumps and JSON bodies. Bounded by+ // the delimiters that terminate a value in each of those contexts.+ [+ /(["']?\b(?:api[_-]?key|access[_-]?token|refresh[_-]?token|auth[_-]?token|token|secret|password|encryption[_-]?key|key)\b["']?\s*[:=]\s*["']?)(?!\[redacted)([^"',\s}\]&]{6,})/gi,+ `$1${REDACTED}`,+ ],++ // JWTs and other three-segment tokens.+ [/\b[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\b/g, '[redacted-token]'],++ // Dotted composite keys (Z.ai, Ollama cloud, Chutes) — hex id, dot, secret.+ [/\b[A-Za-z0-9]{24,}\.[A-Za-z0-9_\-]{16,}\b/g, '[redacted-token]'],++ // Last resort: an unbroken 32+ char alphanumeric run. Long enough to exclude+ // request ids, git SHAs (40 hex would match, which is an acceptable trade) and+ // model names, and it catches bare keys with no recognisable prefix.+ [/\b[A-Za-z0-9]{32,}\b/g, '[redacted-token]'],+];++/** Strip credentials from a string. Safe to call on anything; non-strings are+ * returned unchanged by the caller, not here. */+export function redactSecrets(input: string): string {+ let out = input;+ for (const [pattern, replacement] of PATTERNS) {+ out = out.replace(pattern, replacement);+ }+ return out;+}++// Beyond this, JSON round-tripping an argument costs more than it protects.+const MAX_OBJECT_REDACTION_BYTES = 128 * 1024;++function redactArg(arg: unknown): unknown {+ if (typeof arg === 'string') return redactSecrets(arg);++ if (arg instanceof Error) {+ // Rebuilding the Error would drop subclass fields (ProviderHttpError.status+ // and friends), so mutate the two string members in place instead.+ const clone = Object.create(+ Object.getPrototypeOf(arg),+ Object.getOwnPropertyDescriptors(arg),+ ) as Error;+ clone.message = redactSecrets(arg.message);+ if (typeof arg.stack === 'string') clone.stack = redactSecrets(arg.stack);+ return clone;+ }++ if (arg !== null && typeof arg === 'object') {+ // Round-trip through JSON so a key nested in a logged object is caught, but+ // keep the result an object so console formatting is unchanged. Anything+ // non-serialisable (cycles, BigInt, sockets) falls through untouched.+ try {+ const json = JSON.stringify(arg);+ if (!json || json.length > MAX_OBJECT_REDACTION_BYTES) return arg;+ const redacted = redactSecrets(json);+ return redacted === json ? arg : JSON.parse(redacted);+ } catch {+ return arg;+ }+ }++ return arg;+}++type ConsoleMethod = 'log' | 'info' | 'warn' | 'error' | 'debug' | 'trace';+const METHODS: ConsoleMethod[] = ['log', 'info', 'warn', 'error', 'debug', 'trace'];++let installed = false;++/**+ * Wrap the console writers so no provider credential reaches stdout. Idempotent,+ * and must run before anything else logs. Returns a restore function for tests.+ */+export function installLogRedaction(): () => void {+ if (installed) return () => undefined;+ installed = true;++ const originals = new Map<ConsoleMethod, (...args: unknown[]) => void>();++ for (const method of METHODS) {+ const original = console[method] as (...args: unknown[]) => void;+ if (typeof original !== 'function') continue;+ originals.set(method, original);+ console[method] = (...args: unknown[]) => {+ try {+ original(...args.map(redactArg));+ } catch {+ // Never let redaction swallow a log line.+ original(...args);+ }+ };+ }++ return () => {+ for (const [method, original] of originals) {+ console[method] = original;+ }+ installed = false;+ };+}diff --git a/server/src/providers/base.ts b/server/src/providers/base.tsindex d364f423..99e1b4de 100644--- a/server/src/providers/base.ts+++ b/server/src/providers/base.ts@@ -19,14 +19,23 @@ export interface ProviderHttpError extends Error {retryAfterMs?: number;}+/** Upper bound on a provider-supplied back-off. A malformed or hostile+ * `Retry-After` (e.g. 99999999999) would otherwise bench a key effectively+ * forever, since the value feeds the cooldown expiry directly. A day is longer+ * than any real free-tier reset window, so clamping cannot mask a genuine hint. */+const MAX_RETRY_AFTER_MS = 24 * 60 * 60 * 1000;+/** Parse an HTTP `Retry-After` header (delta-seconds or an HTTP-date) into a- * millisecond delay. Returns undefined when absent or unparseable. */+ * millisecond delay, clamped to MAX_RETRY_AFTER_MS. Returns undefined when+ * absent or unparseable. */export function parseRetryAfterMs(value: string | null | undefined): number | undefined {if (!value) return undefined;const trimmed = value.trim();- if (/^\d+$/.test(trimmed)) return Number(trimmed) * 1000;+ if (/^\d+$/.test(trimmed)) return Math.min(Number(trimmed) * 1000, MAX_RETRY_AFTER_MS);const when = Date.parse(trimmed);- if (!Number.isNaN(when)) return Math.max(0, when - Date.now());+ if (!Number.isNaN(when)) {+ return Math.min(Math.max(0, when - Date.now()), MAX_RETRY_AFTER_MS);+ }return undefined;}diff --git a/server/src/providers/google.ts b/server/src/providers/google.tsindex deb1db93..09d992bc 100644--- a/server/src/providers/google.ts+++ b/server/src/providers/google.ts@@ -568,10 +568,10 @@ export class GoogleProvider extends BaseProvider {};if (request.systemInstruction) body.systemInstruction = request.systemInstruction;- const url = `${API_BASE}/models/${modelId}:generateContent?key=${apiKey}`;+ const url = `${API_BASE}/models/${modelId}:generateContent`;const res = await this.fetchWithTimeout(url, {method: 'POST',- headers: { 'Content-Type': 'application/json' },+ headers: { 'Content-Type': 'application/json', 'x-goog-api-key': apiKey },body: JSON.stringify(body),}, options?.timeoutMs ?? this.timeoutMs);@@ -648,10 +648,10 @@ export class GoogleProvider extends BaseProvider {};if (request.systemInstruction) body.systemInstruction = request.systemInstruction;- const url = `${API_BASE}/models/${modelId}:streamGenerateContent?alt=sse&key=${apiKey}`;+ const url = `${API_BASE}/models/${modelId}:streamGenerateContent?alt=sse`;const res = await this.fetchWithTimeout(url, {method: 'POST',- headers: { 'Content-Type': 'application/json' },+ headers: { 'Content-Type': 'application/json', 'x-goog-api-key': apiKey },body: JSON.stringify(body),}, options?.timeoutMs ?? this.timeoutMs);@@ -797,8 +797,8 @@ export class GoogleProvider extends BaseProvider {// Transport errors propagate — health.ts marks status='error' without// counting toward auto-disable.const res = await this.fetchWithTimeout(- `${API_BASE}/models?key=${apiKey}`,- { method: 'GET' },+ `${API_BASE}/models`,+ { method: 'GET', headers: { 'x-goog-api-key': apiKey } },10000,);recordQuotaObservationsFromResponse(res, {diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex 324e2484..848c080d 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -9,6 +9,7 @@ import { encrypt, decrypt, maskKey } from '../lib/crypto.js';import { parseKeysFromFile, stripJsoncComments, stripTrailingCommas } from '../lib/key-parser.js';import { assessProviderUrl } from '../lib/url-guard.js';import { ensureModelInProfiles } from '../services/profile-models.js';+import { getActiveCooldownsForKeys, clearCooldownsForKey } from '../services/ratelimit.js';export const keysRouter = Router();@@ -189,6 +190,10 @@ keysRouter.get('/', (_req: Request, res: Response) => {});}+ // A cooling-down key reads as healthy and enabled while the router skips it,+ // so surface the cooldowns that explain the idleness. (#P0-7)+ const cooldownsByKeyId = getActiveCooldownsForKeys(rows.map(row => Number(row.id)));+const keys = rows.map(row => {let maskedKey = '****';try {@@ -197,6 +202,7 @@ keysRouter.get('/', (_req: Request, res: Response) => {} catch {maskedKey = '[decrypt failed]';}+ const cooldowns = cooldownsByKeyId.get(Number(row.id)) ?? [];return {id: row.id,platform: row.platform,@@ -210,12 +216,38 @@ keysRouter.get('/', (_req: Request, res: Response) => {lastCheckedAt: row.last_checked_at,lastHealthError: row.last_health_error ?? null,models: row.platform === 'custom' ? (modelsByKeyId.get(row.id) ?? []) : undefined,+ cooldowns: cooldowns.map(c => ({+ modelId: c.modelId,+ expiresAtMs: c.expiresAtMs,+ remainingMs: c.remainingMs,+ })),};});res.json(keys);});+// Clear every active cooldown for one key. An escalated cooldown can bench a key+// for up to 24h from a single bad window; once the operator has fixed the cause+// there is otherwise no way back short of restarting and waiting it out.+keysRouter.delete('/:id/cooldowns', (req: Request, res: Response) => {+ const id = Number(req.params.id);+ if (!Number.isInteger(id)) {+ res.status(400).json({ error: 'Invalid key id' });+ return;+ }++ const db = getDb();+ const exists = db.prepare('SELECT 1 FROM api_keys WHERE id = ?').get(id);+ if (!exists) {+ res.status(404).json({ error: 'Key not found' });+ return;+ }++ const cleared = clearCooldownsForKey(id);+ res.json({ cleared });+});+// Export keys — returns plaintext keys in the requested format.// GET /api/keys/export?format=json|env|csv&healthy=true// The response is the raw file download (Content-Type varies by format).diff --git a/server/src/services/declarative-config.ts b/server/src/services/declarative-config.tsindex 0ec0b039..3ea3743a 100644--- a/server/src/services/declarative-config.ts+++ b/server/src/services/declarative-config.ts@@ -5,6 +5,7 @@ import { getDb } from '../db/index.js';import { encrypt } from '../lib/crypto.js';import { resolveProvider } from '../providers/index.js';import { setCustomWeights, setRoutingStrategy } from './router.js';+import { ensureModelInProfiles } from './profile-models.js';import {clearCatalogModelTombstone,isCatalogManagedModel,@@ -188,6 +189,11 @@ function ensureFallbackRow(db: Db, modelDbId: number, enabled = true, updateExisconst max = db.prepare('SELECT COALESCE(MAX(priority), 0) AS m FROM fallback_config').get() as { m: number };db.prepare('INSERT INTO fallback_config (model_db_id, priority, enabled) VALUES (?, ?, ?)').run(modelDbId, max.m + 1, enabled ? 1 : 0);+ // A chain row alone is not enough to be routable: when a profile is active the+ // router reads profile_models, so a declaratively-added model would be present+ // in the dashboard yet never selected. routes/keys.ts does the same after its+ // own fallback_config insert.+ ensureModelInProfiles(db, modelDbId);}function registerCustomProvider(db: Db, input: z.infer<typeof customProviderSchema>): number {diff --git a/server/src/services/media.ts b/server/src/services/media.tsindex 8dc1422d..bcaa7ded 100644--- a/server/src/services/media.ts+++ b/server/src/services/media.ts@@ -421,12 +421,12 @@ async function callSpeechProvider(// Gemini TTS via generateContent (AUDIO modality) returns base64 PCM// (L16, mono, ~24kHz); wrap it in a WAV header so clients can play it.const r = await mediaFetch(- `https://generativelanguage.googleapis.com/v1beta/models/${row.model_id}:generateContent?key=${encodeURIComponent(key ?? '')}`,+ `https://generativelanguage.googleapis.com/v1beta/models/${row.model_id}:generateContent`,'google','audio',{method: 'POST',- headers: { 'Content-Type': 'application/json' },+ headers: { 'Content-Type': 'application/json', 'x-goog-api-key': key ?? '' },body: JSON.stringify({contents: [{ parts: [{ text: p.input }] }],generationConfig: {diff --git a/server/src/services/ratelimit.ts b/server/src/services/ratelimit.tsindex b05b6c8a..aa62e4db 100644--- a/server/src/services/ratelimit.ts+++ b/server/src/services/ratelimit.ts@@ -30,6 +30,13 @@ function pruneTimestamps(timestamps: number[], windowMs: number, now: number): nconst MINUTE = 60 * 1000;const DAY = 24 * 60 * MINUTE;+/** Milliseconds elapsed since the most recent midnight UTC. Used as the window+ * width for provider-account daily caps, which reset on a day boundary rather+ * than sliding. Never exceeds DAY, so it stays inside the usage-table retention. */+function msSinceUtcMidnight(now: number): number {+ return now - new Date(now).setUTCHours(0, 0, 0, 0);+}+function withDb<T>(fn: (db: RateLimitDb) => T): T | undefined {try {return fn(getDb());@@ -235,15 +242,20 @@ function countPersistedProviderRequests(}// Total requests today for a provider account+key, summed across every model.+// "Today" is the window since midnight UTC, not a sliding 24h: real provider+// account caps (OpenRouter, NVIDIA) reset on a wall-clock day boundary, so a+// sliding window keeps a provider benched well past its actual reset — a burst+// at 23:00 UTC would still be counted against the account at 22:00 the next day.export function providerDailyRequestCount(platform: string, keyId: number, now = Date.now()): number {- const persisted = countPersistedProviderRequests(platform, keyId, DAY, now);+ const windowMs = msSinceUtcMidnight(now);+ const persisted = countPersistedProviderRequests(platform, keyId, windowMs, now);if (persisted !== undefined) return persisted;// DB-unavailable fallback: sum the per-model rpd windows for this platform+key.// Window key format is "platform:modelId:keyId:rpd" (modelId may contain ':').let total = 0;for (const [key, w] of windows) {if (key.startsWith(`${platform}:`) && key.endsWith(`:${keyId}:rpd`)) {- total += pruneTimestamps(w.timestamps, DAY, now).length;+ total += pruneTimestamps(w.timestamps, windowMs, now).length;}}return total;@@ -323,8 +335,10 @@ function sumPersistedProviderTokens(});}+// Midnight-UTC boundary, for the same reason as providerDailyRequestCount.export function providerDailyTokenCount(platform: string, keyId: number, now = Date.now()): number {- const persisted = sumPersistedProviderTokens(platform, keyId, DAY, now);+ const windowMs = msSinceUtcMidnight(now);+ const persisted = sumPersistedProviderTokens(platform, keyId, windowMs, now);if (persisted !== undefined) return persisted;let total = 0;@@ -332,8 +346,11 @@ export function providerDailyTokenCount(platform: string, keyId: number, now = Dfor (const [key, w] of windows) {if (!key.startsWith(`${platform}:`) || !key.endsWith(suffix)) continue;const modelId = key.slice(platform.length + 1, -suffix.length);- w.tokenTimestamps = w.tokenTimestamps.filter(t => t.ts > now - DAY);- const raw = w.tokenTimestamps.reduce((sum, t) => sum + t.tokens, 0);+ // Read-only: the tpd window is shared with the per-model 24h token check, so+ // narrowing it to the midnight boundary here must not prune the stored entries.+ const raw = w.tokenTimestamps+ .filter(t => t.ts > now - windowMs)+ .reduce((sum, t) => sum + t.tokens, 0);total += providerBilledTokens(platform, modelId, raw);}return total;@@ -588,6 +605,83 @@ export function isOnCooldown(platform: string, modelId: string, keyId: number):return true;}+export interface ActiveCooldown {+ platform: string;+ modelId: string;+ keyId: number;+ expiresAtMs: number;+ remainingMs: number;+}++/**+ * Active cooldowns for the given keys, grouped by key id. Batched into one query+ * so the dashboard can render "why is this key idle?" without N round-trips.+ * Without this, a key benched by an escalated cooldown (up to 24h) is invisible:+ * it reads as healthy and enabled while the router silently skips it.+ */+export function getActiveCooldownsForKeys(+ keyIds: number[],+ now = Date.now(),+): Map<number, ActiveCooldown[]> {+ const grouped = new Map<number, ActiveCooldown[]>();+ if (keyIds.length === 0) return grouped;++ const unique = [...new Set(keyIds.filter(id => Number.isInteger(id)))];+ if (unique.length === 0) return grouped;++ const placeholders = unique.map(() => '?').join(', ');+ const rows = withDb(db => db.prepare(`+ SELECT platform, model_id, key_id, expires_at_ms+ FROM rate_limit_cooldowns+ WHERE expires_at_ms > ?+ AND key_id IN (${placeholders})+ ORDER BY expires_at_ms ASC+ `).all(now, ...unique) as { platform: string; model_id: string; key_id: number; expires_at_ms: number }[]) ?? [];++ for (const row of rows) {+ const list = grouped.get(row.key_id) ?? [];+ list.push({+ platform: row.platform,+ modelId: row.model_id,+ keyId: row.key_id,+ expiresAtMs: row.expires_at_ms,+ remainingMs: Math.max(0, row.expires_at_ms - now),+ });+ grouped.set(row.key_id, list);+ }+ return grouped;+}++/**+ * Drop every cooldown for one key, in memory and on disk, and return how many+ * were cleared. Escalated cooldowns can bench a key for up to 24h off a single+ * bad window; an operator who has fixed the cause (raised a quota, waited out a+ * provider incident) otherwise has no way back except restarting and waiting.+ */+export function clearCooldownsForKey(keyId: number): number {+ if (!Number.isInteger(keyId)) return 0;++ const cleared = withDb(db => {+ const result = db.prepare('DELETE FROM rate_limit_cooldowns WHERE key_id = ?').run(keyId);+ return Number(result.changes ?? 0);+ }) ?? 0;++ // The in-memory map is authoritative when the DB read fails, so purge it too.+ // Key format is "platform:modelId:keyId:cooldown" and modelId may contain ':',+ // so match on the trailing segments rather than splitting.+ const suffix = `:${keyId}:cooldown`;+ let memoryCleared = 0;+ for (const key of [...cooldowns.keys()]) {+ if (key.endsWith(suffix)) {+ cooldowns.delete(key);+ cooldownHits.delete(key.slice(0, -':cooldown'.length));+ memoryCleared++;+ }+ }++ return Math.max(cleared, memoryCleared);+}+/*** Soonest moment any active cooldown expires, in ms since epoch, or null when* nothing is cooling down. Used to tell an exhausted caller roughly when todiff --git a/shared/types.ts b/shared/types.tsindex 0684c6ef..3cae3d5f 100644--- a/shared/types.ts+++ b/shared/types.ts@@ -170,6 +170,14 @@ export interface ApiKeyModel {family?: string | null;}+/** An active rate-limit cooldown on one model for a key. A key can be healthy+ * and enabled yet still skipped by the router because of these. */+export interface ApiKeyCooldown {+ modelId: string;+ expiresAtMs: number;+ remainingMs: number;+}+export interface ApiKey {id: number;platform: Platform;@@ -183,6 +191,7 @@ export interface ApiKey {lastCheckedAt: string | null;lastHealthError: string | null;models?: ApiKeyModel[];+ cooldowns?: ApiKeyCooldown[];}export interface ApiKeyCreate {