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(keys,csp): restore custom endpoints through the dashboard import, and unblock the theme bootstrap (#687, #682) (#721)
Tashfeena2993d95a7f8
diff --git a/client/src/components/keys/import-keys-section.tsx b/client/src/components/keys/import-keys-section.tsxindex 788db8bc..13328335 100644--- a/client/src/components/keys/import-keys-section.tsx+++ b/client/src/components/keys/import-keys-section.tsx@@ -10,7 +10,7 @@ import type { ImportKey, ImportSelectedResponse, Platform, PreviewKey, PreviewReimport { Upload } from 'lucide-react'import { useI18n } from '@/i18n'import { toast } from '@/lib/toast'-import { PLATFORMS } from './shared'+import { CUSTOM_GROUP, PLATFORMS } from './shared'interface ImportRow extends PreviewKey {selected: boolean@@ -29,9 +29,17 @@ export function ImportKeysSection({ onImported }: { onImported?: () => void } =const [rows, setRows] = useState<ImportRow[]>([])const [skipped, setSkipped] = useState<string[]>([])- const importablePlatforms = PLATFORMS.filter(p => !p.keyless)+ // 'custom' is not one of PLATFORMS — it is configured through its own form,+ // so it is deliberately absent from the generic provider dropdown. An+ // imported row is the one case where it belongs there: the file already+ // names the endpoint, and without the option the row can never be selected+ // and the endpoint can never be restored (#687).+ const importablePlatforms = [...PLATFORMS.filter(p => !p.keyless), CUSTOM_GROUP]function platformFromPreview(key: PreviewKey): Platform | '' {+ // A custom row is only importable with its base URL; there is nowhere to+ // route it otherwise.+ if (key.detectedPlatform === 'custom') return key.baseUrl ? 'custom' : ''return importablePlatforms.some(p => p.value === key.detectedPlatform)? key.detectedPlatform as Platform: ''@@ -85,6 +93,7 @@ export function ImportKeysSection({ onImported }: { onImported?: () => void } =keyName: row.keyName,keyValue: row.keyValue,platform: row.platform,+ ...(row.baseUrl ? { baseUrl: row.baseUrl } : {}),}))function updateRow(index: number, patch: Partial<ImportRow>) {diff --git a/server/src/__tests__/routes/csp-inline-bootstrap.test.ts b/server/src/__tests__/routes/csp-inline-bootstrap.test.tsnew file mode 100644index 00000000..99d66228--- /dev/null+++ b/server/src/__tests__/routes/csp-inline-bootstrap.test.ts@@ -0,0 +1,78 @@+import { describe, it, expect, beforeAll } from 'vitest';+import { createHash } from 'node:crypto';+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import type { Express } from 'express';+import { createApp, INLINE_BOOTSTRAP_SHA } from '../../app.js';+import { initDb } from '../../db/index.js';++// index.html ships one inline <script>: the theme/direction bootstrap that has+// to run before first paint so dark-mode users do not get a white flash.+// `script-src 'self'` blocked it on EVERY install, HTTPS included — the+// violation is visible in the console log pasted into #682, where it was read+// as part of the LAN/HTTP problem. It is not: it reproduces on localhost too.+//+// The hash is a literal in app.ts so the CSP header stays constant. These tests+// are the guard against drift: edit the inline script without updating the+// hash and the suite fails here rather than in a user's browser.++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const repoRoot = path.resolve(__dirname, '../../../..');++function inlineBootstrapFrom(html: string): string | null {+ // The bootstrap is the only <script> with no src attribute.+ const match = html.match(/<script>([\s\S]*?)<\/script>/);+ return match ? match[1]! : null;+}++function sha256Directive(source: string): string {+ return `'sha256-${createHash('sha256').update(source, 'utf8').digest('base64')}'`;+}++describe('CSP allows the inline theme bootstrap (#682)', () => {+ let app: Express;++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();+ });++ it('the hash in app.ts matches the inline script in client/index.html', () => {+ const html = fs.readFileSync(path.join(repoRoot, 'client/index.html'), 'utf8');+ const inline = inlineBootstrapFrom(html);+ expect(inline, 'no inline <script> found in client/index.html').not.toBeNull();+ expect(sha256Directive(inline!)).toBe(INLINE_BOOTSTRAP_SHA);+ });++ it('the hash also matches the built client, when one is present', () => {+ // Vite copies index.html through, but a future plugin could rewrite the+ // inline script — the browser enforces the hash against the BUILT file, so+ // that is the one that really has to match.+ const built = path.join(repoRoot, 'client/dist/index.html');+ if (!fs.existsSync(built)) return;+ const inline = inlineBootstrapFrom(fs.readFileSync(built, 'utf8'));+ expect(inline, 'no inline <script> found in client/dist/index.html').not.toBeNull();+ expect(sha256Directive(inline!)).toBe(INLINE_BOOTSTRAP_SHA);+ });++ it('serves that hash in the script-src directive', async () => {+ const server = app.listen(0);+ const addr = server.address() as { port: number };+ const res = await fetch(`http://127.0.0.1:${addr.port}/api/ping`);+ server.close();+ const csp = res.headers.get('content-security-policy')!;+ expect(csp).toContain(`script-src 'self' ${INLINE_BOOTSTRAP_SHA}`);+ });++ it('still refuses inline scripts generally — no unsafe-inline for scripts', async () => {+ const server = app.listen(0);+ const addr = server.address() as { port: number };+ const res = await fetch(`http://127.0.0.1:${addr.port}/api/ping`);+ server.close();+ const csp = res.headers.get('content-security-policy')!;+ const scriptSrc = csp.split(';').find(d => d.trim().startsWith('script-src '))!;+ expect(scriptSrc).not.toContain("'unsafe-inline'");+ });+});diff --git a/server/src/__tests__/routes/keys-import-selected-custom.test.ts b/server/src/__tests__/routes/keys-import-selected-custom.test.tsnew file mode 100644index 00000000..9bb1d9ef--- /dev/null+++ b/server/src/__tests__/routes/keys-import-selected-custom.test.ts@@ -0,0 +1,159 @@+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { initDb, getDb } from '../../db/index.js';+import { encrypt } from '../../lib/crypto.js';+import { mintDashboardToken } from '../helpers/auth.js';++// #687, second half. #717 taught POST /api/keys/import about custom endpoints,+// but the dashboard never calls that route — the Add-key dialog does+// /preview then /import-selected, and /import-selected rejected every custom+// row outright. So a custom endpoint still could not be restored from its own+// export file through the UI. These cover the route the dashboard actually uses.++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 json = await res.json().catch(() => null);+ server.close();+ return { status: res.status, body: json as any };+}++async function previewFile(app: Express, filename: string, content: string) {+ const server = app.listen(0);+ const addr = server.address() as { port: number };+ const form = new FormData();+ form.append('files', new Blob([content], { type: 'text/plain' }), filename);+ const res = await fetch(`http://127.0.0.1:${addr.port}/api/keys/preview`, {+ method: 'POST',+ headers: { Authorization: `Bearer ${dashToken}` },+ body: form,+ });+ const json = await res.json().catch(() => null);+ server.close();+ return { status: res.status, body: json as any };+}++function customRows() {+ return getDb()+ .prepare("SELECT id, platform, label, base_url FROM api_keys WHERE platform = 'custom' ORDER BY id")+ .all() as Array<{ id: number; platform: string; label: string; base_url: string | null }>;+}++describe('POST /api/keys/import-selected — custom endpoints (#687)', () => {+ 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('restores a custom endpoint when the row carries its base URL', async () => {+ const { status, body } = await post(app, '/api/keys/import-selected', {+ keys: [{+ keyName: 'My Relay',+ keyValue: 'sk-relay-123',+ platform: 'custom',+ baseUrl: 'https://relay.example.com/v1',+ }],+ });++ expect(status).toBe(200);+ expect(body.imported).toBe(1);+ expect(body.errors).toEqual([]);+ expect(customRows()).toEqual([+ expect.objectContaining({ platform: 'custom', base_url: 'https://relay.example.com/v1' }),+ ]);+ });++ it('still refuses a custom row with no base URL — there is nowhere to route it', async () => {+ const { status, body } = await post(app, '/api/keys/import-selected', {+ keys: [{ keyName: 'My Relay', keyValue: 'sk-relay-123', platform: 'custom' }],+ });++ expect(status).toBe(200);+ expect(body.imported).toBe(0);+ expect(body.errors[0].error).toContain('base URL');+ expect(customRows()).toHaveLength(0);+ });++ it('applies the SSRF guard the manual add path uses (#440)', async () => {+ const { status, body } = await post(app, '/api/keys/import-selected', {+ keys: [{+ keyName: 'metadata',+ keyValue: 'sk-x',+ platform: 'custom',+ baseUrl: 'http://169.254.169.254/latest/meta-data',+ }],+ });++ expect(status).toBe(200);+ expect(body.imported).toBe(0);+ expect(body.errors[0].error).toContain('baseUrl rejected');+ expect(customRows()).toHaveLength(0);+ });++ it('keeps auth-less local servers on the no-key sentinel', async () => {+ const { body } = await post(app, '/api/keys/import-selected', {+ keys: [{+ keyName: 'Local Ollama',+ keyValue: 'no-key',+ platform: 'custom',+ baseUrl: 'http://192.168.1.10:11434/v1',+ }],+ });++ expect(body.imported).toBe(1);+ expect(customRows()).toHaveLength(1);+ });++ it('pools re-imports of the same endpoint instead of duplicating the row (#619)', async () => {+ const row = {+ keyName: 'My Relay',+ keyValue: 'sk-relay-123',+ platform: 'custom',+ baseUrl: 'https://relay.example.com/v1',+ };+ await post(app, '/api/keys/import-selected', { keys: [row] });+ await post(app, '/api/keys/import-selected', { keys: [row] });++ // Importing the same backup twice is an ordinary thing to do; it must not+ // leave two rows pointing at one endpoint.+ expect(customRows()).toHaveLength(1);+ });++ it('carries baseUrl from /preview so the dialog can pass it back', async () => {+ const db = getDb();+ const { encrypted, iv, authTag } = encrypt('sk-relay-123');+ db.prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled, base_url)+ VALUES ('custom', 'My Relay', ?, ?, ?, 'unknown', 1, ?)+ `).run(encrypted, iv, authTag, 'https://relay.example.com/v1');++ const exportFile = JSON.stringify({+ version: 1,+ exportedAt: '2026-08-02T00:00:00Z',+ source: 'freellmapi',+ keys: [{ platform: 'custom', key: 'sk-relay-123', label: 'My Relay', baseUrl: 'https://relay.example.com/v1' }],+ });++ const { status, body } = await previewFile(app, 'freellmapi-keys.json', exportFile);+ expect(status).toBe(200);+ const custom = body.keys.find((k: any) => k.detectedPlatform === 'custom');+ expect(custom).toBeTruthy();+ expect(custom.baseUrl).toBe('https://relay.example.com/v1');+ });+});diff --git a/server/src/app.ts b/server/src/app.tsindex db663aa2..f3cce45b 100644--- a/server/src/app.ts+++ b/server/src/app.ts@@ -45,6 +45,12 @@ const DEFAULT_DASHBOARD_ORIGINS = ['http://[::1]:5173',];+// SHA-256 of the inline theme/direction bootstrap in client/index.html, which+// must run before first paint. Kept as a literal so the CSP header stays a+// constant string; csp-inline-bootstrap.test.ts recomputes it from the real+// index.html (source and build) and fails if the two ever drift apart.+export const INLINE_BOOTSTRAP_SHA = "'sha256-4Mz/yZAENQGlTAAeE1WqXruXCripvlvl0s+Q9S1VS4A='";+// A build asset is safe to cache forever+immutable when its URL is// content-addressed. Vite parks every hashed chunk (JS, CSS, fonts, images)// under assets/, so that directory is the reliable signal; the -<hash>.<ext>@@ -81,7 +87,13 @@ export function createApp(config?: Config) {contentSecurityPolicy: {directives: {defaultSrc: ["'self'"],- scriptSrc: ["'self'"],+ // index.html carries one inline <script>: the theme/direction bootstrap+ // that has to run before first paint, or every dark-mode user gets a+ // white flash. 'self' alone blocks it on every install, HTTPS included,+ // so it is allowed by hash — nothing else inline is. INLINE_BOOTSTRAP_SHA+ // is asserted against the real index.html in csp-inline-bootstrap.test.ts,+ // so editing that script fails the suite instead of silently breaking it.+ scriptSrc: ["'self'", INLINE_BOOTSTRAP_SHA],styleSrc: ["'self'", "'unsafe-inline'"],imgSrc: ["'self'", "data:"],connectSrc: ["'self'"],diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex af1b5aac..81ca1523 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -63,6 +63,9 @@ const importKeySchema = z.object({keyName: z.string().optional(),keyValue: z.string().min(1),platform: z.enum(PLATFORMS),+ // A custom row names an ENDPOINT, so it only means something with the URL+ // the export file carried alongside it (#687).+ baseUrl: z.string().optional(),});function handleUploadError(err: any, res: Response, next: NextFunction): boolean {@@ -1027,7 +1030,7 @@ keysRouter.post('/preview', (req: Request, res: Response, next: NextFunction) =>return;}- const keys: Array<{ keyName: string; keyValue: string; detectedPlatform: string | null; prefix: string; isDuplicate: boolean }> = [];+ const keys: Array<{ keyName: string; keyValue: string; detectedPlatform: string | null; prefix: string; baseUrl?: string; isDuplicate: boolean }> = [];const skipped: string[] = [];// Build a set of existing decrypted key values for duplicate detection@@ -1053,6 +1056,10 @@ keysRouter.post('/preview', (req: Request, res: Response, next: NextFunction) =>keyValue,detectedPlatform: parsedKey.platform,prefix: parsedKey.prefix,+ // Without this the dialog can show a custom row but never restore+ // it — the endpoint it belongs to would be lost between the two+ // calls the dashboard actually makes (#687).+ ...(parsedKey.baseUrl ? { baseUrl: parsedKey.baseUrl } : {}),isDuplicate,});}@@ -1066,7 +1073,7 @@ keysRouter.post('/preview', (req: Request, res: Response, next: NextFunction) =>});});-keysRouter.post('/import-selected', (req: Request, res: Response) => {+keysRouter.post('/import-selected', async (req: Request, res: Response) => {const parsed = z.object({ keys: z.array(importKeySchema).max(100) }).safeParse(req.body);if (!parsed.success) {res.status(400).json({ error: { message: parsed.error.errors.map(e => e.message).join(', ') } });@@ -1087,10 +1094,45 @@ keysRouter.post('/import-selected', (req: Request, res: Response) => {} catch { /* skip undecryptable rows */ }}+ // One SSRF verdict per endpoint, not per key — same reasoning as /import: a+ // pooled endpoint brings several keys to one URL and each check costs a DNS+ // lookup.+ const urlVerdicts = new Map<string, { allowed: boolean; reason?: string }>();+for (const key of parsed.data.keys) {const keyName = key.keyName?.trim() || key.platform;+ // This is the route the dashboard actually uses (preview → import-selected),+ // so a custom endpoint could not be restored from its own export file until+ // it handled one — /import alone was never reachable from the UI (#687).if (key.platform === 'custom') {- errors.push({ key: keyName, error: 'Custom providers must be added with a base URL' });+ if (!key.baseUrl) {+ errors.push({ key: keyName, error: 'Custom providers must be added with a base URL' });+ continue;+ }+ const baseUrl = normalizeBaseUrl(key.baseUrl);+ // An import file can name a cloud metadata address just as easily as the+ // manual add form can (#440), so it gets the same guard.+ let verdict = urlVerdicts.get(baseUrl);+ if (!verdict) {+ verdict = await assessProviderUrl(baseUrl);+ urlVerdicts.set(baseUrl, verdict);+ }+ if (!verdict.allowed) {+ errors.push({ key: keyName, error: `baseUrl rejected: ${verdict.reason}` });+ continue;+ }+ try {+ // 'no-key' is the auth-less-local-server placeholder, not a secret —+ // hand it over as "no key submitted" so the resolver stores the+ // sentinel once instead of encrypting the literal string. Going+ // through the resolver (not a raw INSERT) keeps endpoint pooling+ // intact, so re-importing does not duplicate the row (#619).+ const secret = key.keyValue.trim() === 'no-key' ? undefined : key.keyValue.trim() || undefined;+ resolveCustomEndpointKey(db, baseUrl, secret, keyName);+ imported++;+ } catch (err) {+ errors.push({ key: keyName, error: (err as Error).message });+ }continue;}diff --git a/shared/types.ts b/shared/types.tsindex 5d841a42..df6688c6 100644--- a/shared/types.ts+++ b/shared/types.ts@@ -5,6 +5,8 @@ export interface PreviewKey {keyValue: string;detectedPlatform: string | null;prefix: string;+ /** Custom endpoints only: the upstream URL the export file carried (#687). */+ baseUrl?: string;isDuplicate?: boolean;}@@ -12,6 +14,7 @@ export interface ImportKey {keyName: string;keyValue: string;platform: string;+ baseUrl?: string;}export interface PreviewResponse {