Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

fix(keys,models,desktop): keep custom endpoints on export, scale the budget label, and fix the tray version (#687, #688, #703) (#717)

Tashfeen229dd32c9fb6
diff --git a/client/src/components/keys/export-keys-dialog.tsx b/client/src/components/keys/export-keys-dialog.tsx
index b299db05..ebf10c26 100644
--- a/client/src/components/keys/export-keys-dialog.tsx
+++ b/client/src/components/keys/export-keys-dialog.tsx
@@ -68,7 +68,10 @@ export function ExportKeysDialog({ open, onOpenChange }: { open: boolean; onOpen
queryFn: () => apiFetch('/api/keys'),
})
- const exportableKeys = keys.filter(k => !k.keyless)
+ // The server flags what the export will really write. Counting `!keyless`
+ // here instead promised keys the export then dropped — a no-auth custom
+ // endpoint is not a "keyless provider", so it was counted and skipped (#687).
+ const exportableKeys = keys.filter(k => k.exportable)
const exportCount = healthyOnly
? exportableKeys.filter(k => k.status === 'healthy').length
: exportableKeys.length
diff --git a/client/src/components/model-table.tsx b/client/src/components/model-table.tsx
index 21dd90c7..be623160 100644
--- a/client/src/components/model-table.tsx
+++ b/client/src/components/model-table.tsx
@@ -190,9 +190,20 @@ export function RowContent({
</div>
<div className="text-[11px] text-muted-foreground/70 tabular-nums mt-0.5">
{/* Token budget only when it's a real token count; rate-limited models
- (NVIDIA's "free · 40 RPM") show their rate, not "… tok/mo". */}
+ (NVIDIA's "free · 40 RPM") show their rate, not "… tok/mo".
+
+ The catalog figure is PER KEY. The router credits it once per key
+ it can rotate through, so an operator with three keys really does
+ have three times the budget — and reading the bare catalog string
+ back made it look like adding keys changed nothing (#688). The
+ multiplier is written as "× N" rather than a sentence so it needs
+ no translation, and the catalog's own wording ("~10-20M") is kept
+ instead of a computed total, which would state a range's high end
+ as if it were fact. */}
{[
- (row.monthlyTokenBudgetTokens ?? 0) > 0 ? t('models.tokPerMonth', { count: row.monthlyTokenBudget }) : null,
+ (row.monthlyTokenBudgetTokens ?? 0) > 0
+ ? t('models.tokPerMonth', { count: row.monthlyTokenBudget }) + (row.keyCount > 1 ? ` × ${row.keyCount}` : '')
+ : null,
row.rpmLimit ? t('models.rpmLimit', { count: row.rpmLimit }) : null,
row.rpdLimit ? t('models.rpdLimit', { count: row.rpdLimit }) : null,
].filter(Boolean).join(' · ') || cleanQuotaLabel(row.monthlyTokenBudget) || '—'}
diff --git a/client/src/components/settings-dialog.tsx b/client/src/components/settings-dialog.tsx
index e4157186..71f3403b 100644
--- a/client/src/components/settings-dialog.tsx
+++ b/client/src/components/settings-dialog.tsx
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
import {
+ ArrowRight,
Check,
ChevronsUpDown,
FlaskConical,
@@ -8,6 +9,7 @@ import {
Loader2,
Monitor,
Moon,
+ RefreshCw,
Search,
SlidersHorizontal,
Sun,
@@ -545,6 +547,104 @@ function PreviewSection({ state }: { state: CompressionState }) {
)
}
+const RELEASES_URL = 'https://github.com/tashfeenahmed/freellmapi/releases'
+const LATEST_RELEASE_API = 'https://api.github.com/repos/tashfeenahmed/freellmapi/releases/latest'
+
+/** Compare two dotted versions; > 0 when `a` is newer. Missing parts read as 0. */
+function compareVersions(a: string, b: string): number {
+ const pa = a.replace(/^v/, '').split('.').map(n => parseInt(n, 10) || 0)
+ const pb = b.replace(/^v/, '').split('.').map(n => parseInt(n, 10) || 0)
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
+ const diff = (pa[i] ?? 0) - (pb[i] ?? 0)
+ if (diff !== 0) return diff
+ }
+ return 0
+}
+
+/**
+ * Which build this is, and — on demand — whether a newer one has been published
+ * (#703: neither was reachable from the dashboard at all).
+ *
+ * Deliberately wordless: a proper noun for the label, version numbers, an arrow
+ * and icons. Every string a locale would have to translate is one this feature
+ * would ship untranslated in 59 of the 60 shipped languages, so it says the same
+ * thing in symbols instead.
+ *
+ * The check only runs when clicked. A dashboard that phoned GitHub on open would
+ * make an outbound request on behalf of self-hosted operators who never asked
+ * for one.
+ */
+function AppVersionRow() {
+ const version = typeof window !== 'undefined'
+ ? (window as { __FREEAPI_VERSION__?: string | null }).__FREEAPI_VERSION__
+ : null
+ const [latest, setLatest] = useState<string | null>(null)
+ const [state, setState] = useState<'idle' | 'checking' | 'current' | 'outdated' | 'failed'>('idle')
+
+ // Only the desktop shell knows the released version; a browser would have to
+ // guess from the server's own package version, which tracks something else.
+ if (!version) return null
+
+ async function check() {
+ setState('checking')
+ try {
+ const res = await fetch(LATEST_RELEASE_API, { headers: { Accept: 'application/vnd.github+json' } })
+ if (!res.ok) throw new Error(String(res.status))
+ const tag = String(((await res.json()) as { tag_name?: string }).tag_name ?? '').trim()
+ if (!tag) throw new Error('no tag')
+ setLatest(tag.replace(/^v/, ''))
+ setState(compareVersions(tag, version!) > 0 ? 'outdated' : 'current')
+ } catch {
+ setState('failed')
+ }
+ }
+
+ return (
+ <Row
+ label="FreeLLMAPI"
+ control={(
+ <div className="flex items-center gap-2 text-sm tabular-nums">
+ <span>v{version}</span>
+ {state === 'outdated' && latest && (
+ <a
+ href={RELEASES_URL}
+ target="_blank"
+ rel="noreferrer noopener"
+ title={RELEASES_URL}
+ className="flex items-center gap-1 text-primary underline underline-offset-2"
+ >
+ <ArrowRight className="size-3.5" aria-hidden />
+ <span>v{latest}</span>
+ </a>
+ )}
+ {state === 'current' && <Check className="size-4 text-emerald-600 dark:text-emerald-400" aria-hidden />}
+ {state === 'failed' && (
+ <a
+ href={RELEASES_URL}
+ target="_blank"
+ rel="noreferrer noopener"
+ title={RELEASES_URL}
+ className="text-primary underline underline-offset-2"
+ >
+ {RELEASES_URL.replace('https://', '')}
+ </a>
+ )}
+ <button
+ type="button"
+ onClick={check}
+ disabled={state === 'checking'}
+ title={RELEASES_URL}
+ aria-label={RELEASES_URL}
+ className="inline-flex rounded-full text-muted-foreground/70 outline-none transition-colors hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50"
+ >
+ <RefreshCw className={`size-3.5 ${state === 'checking' ? 'animate-spin' : ''}`} aria-hidden />
+ </button>
+ </div>
+ )}
+ />
+ )
+}
+
function GeneralSection() {
const { t } = useI18n()
const { theme, setTheme } = useTheme()
@@ -572,6 +672,7 @@ function GeneralSection() {
/>
)}
/>
+ <AppVersionRow />
</>
)
}
diff --git a/desktop/renderer/popover.html b/desktop/renderer/popover.html
index 5cf8005a..e4981c5b 100644
--- a/desktop/renderer/popover.html
+++ b/desktop/renderer/popover.html
@@ -25,7 +25,9 @@
}
body.light {
--fg: rgba(20, 20, 24, 0.92);
- --fg-dim: rgba(20, 20, 24, 0.56);
+ /* 0.56 measured 4.1:1 on the light panel — just under AA for the small text
+ that uses it (version, Quit). 0.62 takes it to 5.0:1. */
+ --fg-dim: rgba(20, 20, 24, 0.62);
--fg-faint: rgba(20, 20, 24, 0.34);
--hairline: rgba(0, 0, 0, 0.10);
--card: rgba(0, 0, 0, 0.05);
@@ -152,10 +154,14 @@
}
.switch.on { background: var(--ok); }
.switch.on::after { left: 14px; }
+ /* The version is information, not decoration, so it may not sit at the
+ --fg-faint level the ornamental hairlines use: white at 32% over the solid
+ Windows panel is 2.9:1, well under the 4.5:1 needed to be readable (#703).
+ --fg-dim clears it in both themes (6.1:1 dark, 5.0:1 light). */
.version {
flex: none;
margin-left: auto;
- color: var(--fg-faint);
+ color: var(--fg-dim);
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
diff --git a/desktop/src/preload.ts b/desktop/src/preload.ts
index 49526f91..a87905a3 100644
--- a/desktop/src/preload.ts
+++ b/desktop/src/preload.ts
@@ -19,6 +19,16 @@ if (arg) {
// no Sign out) when running inside the desktop shell.
contextBridge.exposeInMainWorld('__FREEAPI_DESKTOP__', true);
+// The running build's version, so the dashboard can show which one it is and
+// offer a check against the published releases (#703). Arrives the same way the
+// token does; absent in a browser, where the dashboard simply omits the row
+// rather than guessing from the server's own (unrelated) package version.
+const versionArg = process.argv.find((a) => a.startsWith('--freeapi-version='));
+contextBridge.exposeInMainWorld(
+ '__FREEAPI_VERSION__',
+ versionArg ? versionArg.slice('--freeapi-version='.length) : null,
+);
+
// `desktop` class on <html> activates the client's translucent backdrop
// (html.desktop in index.css). CAREFUL: for an http:// load the preload
// runs before the page's document is parsed — documentElement is null or
diff --git a/desktop/src/window.ts b/desktop/src/window.ts
index b05dd739..7db9fbf9 100644
--- a/desktop/src/window.ts
+++ b/desktop/src/window.ts
@@ -1,6 +1,6 @@
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { BrowserWindow } from 'electron';
+import { app, BrowserWindow } from 'electron';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -40,13 +40,22 @@ export function openDashboard(port: number, token: string): void {
visualEffectState: 'followWindow' as const,
backgroundColor: '#00000000',
}
- : { backgroundColor: '#09090b' }),
+ : {
+ backgroundColor: '#09090b',
+ // Windows and Linux otherwise carry Electron's stock File/Edit/View
+ // menu permanently — none of it does anything this app needs, and it
+ // cannot be dismissed (#703). Hidden rather than removed so the menu's
+ // clipboard accelerators keep working; Alt still reveals it.
+ autoHideMenuBar: true,
+ }),
webPreferences: {
preload: path.join(__dirname, 'preload.cjs'),
contextIsolation: true,
sandbox: false,
nodeIntegration: false,
- additionalArguments: [`--freeapi-token=${token}`],
+ // The dashboard has no other way to know which build is running: the
+ // server's own package version is not the released app version (#703).
+ additionalArguments: [`--freeapi-token=${token}`, `--freeapi-version=${app.getVersion()}`],
},
});
diff --git a/server/src/__tests__/lib/key-parser.test.ts b/server/src/__tests__/lib/key-parser.test.ts
index d1dc5711..6c299f6a 100644
--- a/server/src/__tests__/lib/key-parser.test.ts
+++ b/server/src/__tests__/lib/key-parser.test.ts
@@ -117,18 +117,28 @@ describe('key parser', () => {
expect(parseExportJson('not json')).toBeNull();
});
+ // The platform now rides along explicitly instead of being re-derived from
+ // the generated prefix: 'custom' has no PREFIX_MAP entry, so inference alone
+ // silently dropped every custom endpoint on import (#687).
it('parses CSV format with header', () => {
const csv = 'platform,key,label\n"google","AIza-test","Google Key"\n"groq","gsk-test","Groq Key"\n';
expect(parseCsv(csv)).toEqual([
- { key: 'GOOGLE_KEY', value: 'AIza-test' },
- { key: 'GROQ_KEY', value: 'gsk-test' },
+ { key: 'GOOGLE_KEY', value: 'AIza-test', platform: 'google' },
+ { key: 'GROQ_KEY', value: 'gsk-test', platform: 'groq' },
]);
});
it('parses CSV format without header', () => {
const csv = 'google,AIza-test,Google Key\n';
expect(parseCsv(csv)).toEqual([
- { key: 'GOOGLE_KEY', value: 'AIza-test' },
+ { key: 'GOOGLE_KEY', value: 'AIza-test', platform: 'google' },
+ ]);
+ });
+
+ it('parses the base_url column that makes a custom row importable', () => {
+ const csv = 'platform,key,label,base_url\n"custom","sk-local","LM Studio","http://192.168.1.5:1234/v1"\n';
+ expect(parseCsv(csv)).toEqual([
+ { key: 'CUSTOM_KEY', value: 'sk-local', platform: 'custom', baseUrl: 'http://192.168.1.5:1234/v1' },
]);
});
diff --git a/server/src/__tests__/routes/keys-export-custom-roundtrip.test.ts b/server/src/__tests__/routes/keys-export-custom-roundtrip.test.ts
new file mode 100644
index 00000000..8a1fad7a
--- /dev/null
+++ b/server/src/__tests__/routes/keys-export-custom-roundtrip.test.ts
@@ -0,0 +1,155 @@
+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 { encrypt, decrypt } from '../../lib/crypto.js';
+import { mintDashboardToken } from '../helpers/auth.js';
+
+// #687: exporting every key and importing the file back has to return the
+// custom OpenAI-compatible endpoints too. They were dropped three ways at once:
+// .env and .csv carried no base_url, the importer refused platform 'custom'
+// outright, and the dialog counted rows the export then skipped.
+
+let dashToken = '';
+
+async function exportText(app: Express, format: string): Promise<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=${format}`, {
+ headers: { Authorization: `Bearer ${dashToken}`, 'x-reauth-password': 'password123' },
+ });
+ const text = await res.text();
+ server.close();
+ return text;
+}
+
+async function importFile(app: Express, filename: string, content: string) {
+ const server = app.listen(0);
+ const addr = server.address() as { port: number };
+ const form = new FormData();
+ form.append('file', new Blob([content], { type: 'text/plain' }), filename);
+ const res = await fetch(`http://127.0.0.1:${addr.port}/api/keys/import`, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${dashToken}` },
+ body: form,
+ });
+ const body = await res.json();
+ server.close();
+ return { status: res.status, body };
+}
+
+async function listKeys(app: Express) {
+ 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`, {
+ headers: { Authorization: `Bearer ${dashToken}` },
+ });
+ const body = await res.json();
+ server.close();
+ return body as any[];
+}
+
+function addKey(platform: string, raw: string, label: string, baseUrl: string | null = null) {
+ const { encrypted, iv, authTag } = encrypt(raw);
+ getDb().prepare(`
+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled, base_url)
+ VALUES (?, ?, ?, ?, ?, 'healthy', 1, ?)
+ `).run(platform, label, encrypted, iv, authTag, baseUrl);
+}
+
+/** Every stored row as "platform|baseUrl|secret", for comparing before/after. */
+function snapshot(): string[] {
+ return (getDb().prepare('SELECT platform, base_url, encrypted_key, iv, auth_tag FROM api_keys').all() as any[])
+ .map(r => {
+ let secret = '';
+ try { secret = decrypt(r.encrypted_key, r.iv, r.auth_tag); } catch { secret = '[undecryptable]'; }
+ return `${r.platform}|${r.base_url ?? ''}|${secret}`;
+ })
+ .sort();
+}
+
+function seed() {
+ getDb().prepare('DELETE FROM api_keys').run();
+ addKey('google', 'goog-secret-1', 'first google');
+ addKey('google', 'goog-secret-2', 'second google');
+ addKey('custom', 'lmstudio-secret', 'LM Studio', 'http://192.168.1.5:1234/v1');
+ addKey('custom', 'vllm-secret', 'vLLM box', 'http://10.0.0.9:8000/v1');
+ addKey('custom', 'no-key', 'Local no-auth', 'http://127.0.0.1:8080/v1');
+}
+
+describe('#687 custom endpoints survive an export/import round trip', () => {
+ let app: Express;
+
+ beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ // Private addresses must stay importable — a custom endpoint is usually a
+ // box on the LAN. The SSRF guard only blocks them when this is set.
+ delete process.env.FREEAPI_BLOCK_PRIVATE_PROVIDER_URLS;
+ initDb(':memory:');
+ app = createApp();
+ dashToken = mintDashboardToken();
+ });
+
+ beforeEach(() => seed());
+
+ it('.env pairs each endpoint with its base_url and keeps repeat platforms apart', async () => {
+ const text = await exportText(app, 'env');
+ expect(text).toContain('CUSTOM_1_BASE_URL=http://192.168.1.5:1234/v1');
+ expect(text).toContain('CUSTOM_1_KEY=lmstudio-secret');
+ expect(text).toContain('CUSTOM_2_BASE_URL=http://10.0.0.9:8000/v1');
+ // Two Google keys must not collapse onto one name.
+ expect(text).toContain('GOOGLE_KEY=goog-secret-1');
+ expect(text).toContain('GOOGLE_KEY_2=goog-secret-2');
+ });
+
+ it('.csv carries base_url as a fourth column', async () => {
+ const text = await exportText(app, 'csv');
+ expect(text.split('\n')[0]).toBe('platform,key,label,base_url');
+ expect(text).toContain('"custom","lmstudio-secret","LM Studio","http://192.168.1.5:1234/v1"');
+ expect(text).toContain('"google","goog-secret-1","first google",""');
+ });
+
+ it.each(['env', 'csv', 'json'])('a %s export re-imports into the same set of keys', async (format) => {
+ const before = snapshot();
+ const text = await exportText(app, format);
+
+ getDb().prepare('DELETE FROM api_keys').run();
+ const { body } = await importFile(app, `keys.${format}`, text);
+ expect(body.errors).toEqual([]);
+
+ expect(snapshot()).toEqual(before);
+ });
+
+ it('a custom key with no base_url is skipped rather than orphaned', async () => {
+ getDb().prepare('DELETE FROM api_keys').run();
+ const { body } = await importFile(app, 'keys.csv', 'platform,key,label,base_url\n"custom","orphan","No URL",""\n');
+ expect(body.imported).toBe(0);
+ expect(body.skipped.length).toBe(1);
+ expect(getDb().prepare('SELECT COUNT(*) AS c FROM api_keys').get()).toEqual({ c: 0 });
+ });
+
+ it('an import file naming a blocked address is refused, not stored', async () => {
+ process.env.FREEAPI_BLOCK_PRIVATE_PROVIDER_URLS = '1';
+ try {
+ getDb().prepare('DELETE FROM api_keys').run();
+ const { body } = await importFile(
+ app, 'keys.csv',
+ 'platform,key,label,base_url\n"custom","k","Metadata","http://169.254.169.254/v1"\n',
+ );
+ expect(body.imported).toBe(0);
+ expect(body.errors[0].error).toMatch(/baseUrl rejected/);
+ expect(getDb().prepare('SELECT COUNT(*) AS c FROM api_keys').get()).toEqual({ c: 0 });
+ } finally {
+ delete process.env.FREEAPI_BLOCK_PRIVATE_PROVIDER_URLS;
+ }
+ });
+
+ it('the dialog count matches what the export writes', async () => {
+ const keys = await listKeys(app);
+ const promised = keys.filter(k => k.exportable).length;
+ const written = JSON.parse(await exportText(app, 'json')).keys.length;
+ expect(promised).toBe(written);
+ // All five rows, including the no-auth endpoint that used to be dropped.
+ expect(written).toBe(5);
+ });
+});
diff --git a/server/src/lib/key-parser.ts b/server/src/lib/key-parser.ts
index b19701f2..ba4b7730 100644
--- a/server/src/lib/key-parser.ts
+++ b/server/src/lib/key-parser.ts
@@ -2,6 +2,21 @@ export interface ParsedKey {
rawKey: string;
prefix: string;
platform: string | null;
+ /** Custom OpenAI-compatible endpoints are identified by their base_url, so a
+ * 'custom' key is meaningless without one — the importer refuses those. Set
+ * by the formats that can carry it (export JSON, CSV, and the paired
+ * CUSTOM_<n>_BASE_URL / CUSTOM_<n>_KEY convention in .env). */
+ baseUrl?: string;
+}
+
+/** A key/value pair on its way to becoming a ParsedKey. `platform` and
+ * `baseUrl` are set only by formats that state them outright (CSV names the
+ * platform in a column); otherwise the platform is inferred from the prefix. */
+interface KeyPair {
+ key: string;
+ value: string;
+ platform?: string;
+ baseUrl?: string;
}
export interface ParseResult {
@@ -261,7 +276,8 @@ export function parseExportJson(content: string): ParseResult | null {
const prefix = platform
? (Object.entries(PREFIX_MAP).find(([, v]) => v === platform)?.[0] ?? `${platform.toUpperCase()}_`)
: '';
- result.keys.push({ rawKey: `${label}=${keyValue}`, prefix, platform });
+ const baseUrl = typeof row.baseUrl === 'string' ? row.baseUrl.trim() : '';
+ result.keys.push({ rawKey: `${label}=${keyValue}`, prefix, platform, ...(baseUrl ? { baseUrl } : {}) });
}
return result;
}
@@ -270,13 +286,15 @@ export function parseExportJson(content: string): ParseResult | null {
}
/**
- * Parse CSV format: platform,key,label (with optional header row).
+ * Parse CSV format: platform,key,label[,base_url] (with optional header row).
+ * The trailing base_url column is what makes a 'custom' row importable — an
+ * endpoint is identified by its URL, so a custom key without one is orphaned.
*/
-export function parseCsv(content: string): Array<{ key: string; value: string }> {
+export function parseCsv(content: string): KeyPair[] {
const lines = content.split('\n').filter(l => l.trim());
if (lines.length === 0) return [];
- const result: Array<{ key: string; value: string }> = [];
+ const result: KeyPair[] = [];
// Skip header row if it looks like a CSV header
const startIdx = lines[0]!.toLowerCase().startsWith('platform,') ? 1 : 0;
@@ -284,17 +302,19 @@ export function parseCsv(content: string): Array<{ key: string; value: string }>
for (let i = startIdx; i < lines.length; i++) {
const line = lines[i]!;
// Simple CSV parsing: split on comma, strip quotes
- const match = line.match(/^"?([^"]*?)"?,"?([^"]*?)"?(?:,"?([^"]*?)"?)?$/);
+ const match = line.match(/^"?([^"]*?)"?,"?([^"]*?)"?(?:,"?([^"]*?)"?)?(?:,"?([^"]*?)"?)?$/);
if (!match) continue;
const platform = (match[1] ?? '').trim();
const key = (match[2] ?? '').trim();
- const label = (match[3] ?? '').trim() || platform;
+ const baseUrl = (match[4] ?? '').trim();
if (!key || !platform) continue;
const envKey = `${platform.toUpperCase()}_KEY`;
- result.push({ key: envKey, value: key });
+ // Name the platform outright rather than re-deriving it from the prefix:
+ // 'custom' has no PREFIX_MAP entry, so inference would drop the row.
+ result.push({ key: envKey, value: key, platform, ...(baseUrl ? { baseUrl } : {}) });
}
return result;
@@ -358,6 +378,31 @@ export function parseAuthJson(content: string): ParseResult {
return { keys, skipped };
}
+/**
+ * Fold the paired CUSTOM_<n>_BASE_URL / CUSTOM_<n>_KEY lines the .env export
+ * writes back into one custom key carrying its endpoint. A plain `CUSTOM_KEY=`
+ * with no URL beside it stays unpaired and is skipped downstream, which is the
+ * honest outcome: there is no endpoint to attach it to.
+ */
+function pairCustomEndpointEnv(pairs: Array<{ key: string; value: string }>): KeyPair[] {
+ const baseUrls = new Map<string, string>();
+ for (const { key, value } of pairs) {
+ const m = key.toUpperCase().match(/^CUSTOM_(.+)_BASE_URL$/);
+ if (m && value.trim()) baseUrls.set(m[1]!, value.trim());
+ }
+ if (baseUrls.size === 0) return pairs;
+
+ const out: KeyPair[] = [];
+ for (const pair of pairs) {
+ const upper = pair.key.toUpperCase();
+ if (/^CUSTOM_.+_BASE_URL$/.test(upper)) continue; // consumed above
+ const keyMatch = upper.match(/^CUSTOM_(.+)_KEY$/);
+ const baseUrl = keyMatch ? baseUrls.get(keyMatch[1]!) : undefined;
+ out.push(baseUrl ? { ...pair, platform: 'custom', baseUrl } : pair);
+ }
+ return out;
+}
+
function extractPrefix(key: string): string {
const upper = key.toUpperCase();
const direct = Object.keys(PREFIX_MAP)
@@ -382,16 +427,16 @@ export function looksLikeApiKey(value: string): boolean {
return /[a-z]/i.test(value);
}
-function toParsedKeys(pairs: Array<{ key: string; value: string }>): ParseResult {
+function toParsedKeys(pairs: KeyPair[]): ParseResult {
const keys: ParsedKey[] = [];
const skipped: string[] = [];
- for (const { key, value } of pairs) {
+ for (const { key, value, platform: statedPlatform, baseUrl } of pairs) {
const prefix = extractPrefix(key);
- const platform = detectPlatform(prefix);
+ const platform = statedPlatform ?? detectPlatform(prefix);
if (platform) {
- keys.push({ rawKey: `${key}=${value}`, prefix, platform });
+ keys.push({ rawKey: `${key}=${value}`, prefix, platform, ...(baseUrl ? { baseUrl } : {}) });
continue;
}
@@ -422,7 +467,7 @@ export function parseKeysFromFile(content: string, filename: string): ParseResul
try {
parsed = JSON.parse(clean);
} catch {
- return toParsedKeys(parseDotEnv(text));
+ return toParsedKeys(pairCustomEndpointEnv(parseDotEnv(text)));
}
if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) && 'credential_pool' in parsed) {
return parseAuthJson(clean);
@@ -434,5 +479,5 @@ export function parseKeysFromFile(content: string, filename: string): ParseResul
return toParsedKeys(parseCsv(text));
}
- return toParsedKeys(parseDotEnv(text));
+ return toParsedKeys(pairCustomEndpointEnv(parseDotEnv(text)));
}
diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.ts
index 16b434f6..af1b5aac 100644
--- a/server/src/routes/keys.ts
+++ b/server/src/routes/keys.ts
@@ -130,6 +130,22 @@ function insertImportedKey(platform: (typeof PLATFORMS)[number], keyName: string
// its models ship in the premium/live catalog and only appear for free-tier
// installs once they age into the monthly catalog, so a fresh install adds the
// key and silently sees nothing.
+/**
+ * Whether a stored row belongs in an export file. Kept in one place because the
+ * export dialog shows a count before downloading, and computing that count from
+ * a different rule than the export itself made it lie: it promised 40 keys and
+ * wrote 39 whenever a no-auth custom endpoint was in the list (#687).
+ *
+ * A custom endpoint is worth exporting even when it holds only the `no-key`
+ * placeholder — the endpoint IS the thing being backed up, and its base_url
+ * restores it. Anything else needs a real secret to be worth a line.
+ */
+export function isExportableKey(row: { platform: string; baseUrl: string | null; key: string }): boolean {
+ if (row.platform === 'custom') return Boolean(row.baseUrl);
+ const v = row.key.trim();
+ return v.length > 0 && v !== 'no-key';
+}
+
function enabledModelCount(platform: string): number {
const db = getDb();
const row = db.prepare(
@@ -254,8 +270,9 @@ keysRouter.get('/', (_req: Request, res: Response) => {
const keys = rows.map(row => {
let maskedKey = '****';
+ let realKey = '';
try {
- const realKey = decrypt(row.encrypted_key, row.iv, row.auth_tag);
+ realKey = decrypt(row.encrypted_key, row.iv, row.auth_tag);
maskedKey = maskKey(realKey);
} catch {
maskedKey = '[decrypt failed]';
@@ -270,6 +287,8 @@ keysRouter.get('/', (_req: Request, res: Response) => {
status: row.status,
enabled: row.enabled === 1,
keyless: resolveProvider(row.platform)?.keyless === true,
+ // Lets the export dialog count exactly what the export will write.
+ exportable: isExportableKey({ platform: row.platform, baseUrl: row.base_url ?? null, key: realKey }),
createdAt: row.created_at,
lastCheckedAt: row.last_checked_at,
lastHealthError: row.last_health_error ?? null,
@@ -344,10 +363,7 @@ keysRouter.get('/export', (req: Request, res: Response) => {
baseUrl: row.base_url || undefined,
};
})
- .filter(k => {
- const v = k.key.trim();
- return v.length > 0 && v !== 'no-key';
- });
+ .filter(k => isExportableKey({ platform: k.platform, baseUrl: k.baseUrl ?? null, key: k.key }));
if (decryptedKeys.length === 0) {
res.status(404).json({ error: { message: 'No keys to export' } });
@@ -356,8 +372,29 @@ keysRouter.get('/export', (req: Request, res: Response) => {
if (format === 'env') {
// .env format: GOOGLE_KEY=xxx\nGROQ_KEY=yyy
+ //
+ // Names have to stay unique. A .env is read back into a map keyed by name,
+ // so two rows sharing one name collapse into a single imported key — every
+ // second Google key was silently lost on a round trip. Repeats therefore
+ // take a numeric suffix (GOOGLE_KEY_2), which still resolves to the same
+ // platform through PREFIX_MAP.
+ //
+ // Custom endpoints get an indexed PAIR, because a custom key without its
+ // base_url cannot be restored — there is no endpoint to attach it to (#687).
+ const seenPerPlatform = new Map<string, number>();
+ let customIndex = 0;
const lines = decryptedKeys.map(k => {
- const envKey = `${k.platform.toUpperCase()}_KEY=${k.key}`;
+ if (k.platform === 'custom' && k.baseUrl) {
+ customIndex++;
+ return [
+ `# ${k.label || `custom endpoint ${customIndex}`}`,
+ `CUSTOM_${customIndex}_BASE_URL=${k.baseUrl}`,
+ `CUSTOM_${customIndex}_KEY=${k.key}`,
+ ].join('\n');
+ }
+ const n = (seenPerPlatform.get(k.platform) ?? 0) + 1;
+ seenPerPlatform.set(k.platform, n);
+ const envKey = `${k.platform.toUpperCase()}_KEY${n > 1 ? `_${n}` : ''}=${k.key}`;
return k.label ? `# ${k.label}\n${envKey}` : envKey;
});
const content = lines.join('\n\n') + '\n';
@@ -377,9 +414,13 @@ keysRouter.get('/export', (req: Request, res: Response) => {
// (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';
+ // base_url is the fourth column: a custom row is an ENDPOINT, and without
+ // its URL the key cannot be re-imported (#687). Blank for every other
+ // platform. The importer tolerates the three-column form too, so files
+ // written by older builds still load.
+ const header = 'platform,key,label,base_url';
const lines = decryptedKeys.map(k =>
- [escCsv(k.platform), escCsv(k.key), escCsv(neutralize(k.label))].join(',')
+ [escCsv(k.platform), escCsv(k.key), escCsv(neutralize(k.label)), escCsv(k.baseUrl ?? '')].join(',')
);
const content = [header, ...lines].join('\n') + '\n';
res.setHeader('Content-Type', 'text/csv; charset=utf-8');
@@ -888,7 +929,7 @@ keysRouter.post('/custom', async (req: Request, res: Response) => {
});
keysRouter.post('/import', (req: Request, res: Response, next: NextFunction) => {
- upload.single('file')(req, res, (err: any) => {
+ upload.single('file')(req, res, async (err: any) => {
if (handleUploadError(err, res, next)) return;
try {
@@ -901,6 +942,9 @@ keysRouter.post('/import', (req: Request, res: Response, next: NextFunction) =>
const imported: Array<{ keyName: string; platform: string }> = [];
const skipped = [...result.skipped];
const errors: Array<{ key: string; error: string }> = [];
+ // One SSRF verdict per endpoint, not per key: a pooled endpoint (#619)
+ // brings several keys to the same URL and each check costs a DNS lookup.
+ const urlVerdicts = new Map<string, { allowed: boolean; reason?: string }>();
for (const parsedKey of result.keys) {
const { keyName, keyValue } = splitRawKey(parsedKey.rawKey);
@@ -909,10 +953,44 @@ keysRouter.post('/import', (req: Request, res: Response, next: NextFunction) =>
continue;
}
const platformParse = z.enum(PLATFORMS).safeParse(parsedKey.platform);
- if (!platformParse.success || platformParse.data === 'custom') {
+ if (!platformParse.success) {
skipped.push(keyName);
continue;
}
+
+ // Custom rows name an ENDPOINT. They used to be dropped outright, which
+ // made every export/import round trip lose them (#687); they import now,
+ // but only with the base_url that says where the endpoint is.
+ if (platformParse.data === 'custom') {
+ if (!parsedKey.baseUrl) {
+ skipped.push(keyName);
+ continue;
+ }
+ const baseUrl = normalizeBaseUrl(parsedKey.baseUrl);
+ // Same SSRF guard the manual add path uses (#440) — an import file is
+ // just as capable of naming a cloud metadata address.
+ 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 {
+ // A placeholder value means "endpoint with auth off" — hand it to
+ // the resolver as "no key submitted" so it stores the sentinel once
+ // instead of treating 'no-key' as a real secret.
+ const secret = keyValue.trim() === 'no-key' ? undefined : keyValue.trim() || undefined;
+ resolveCustomEndpointKey(getDb(), baseUrl, secret, keyName);
+ imported.push({ keyName, platform: 'custom' });
+ } catch (insertErr) {
+ errors.push({ key: keyName, error: (insertErr as Error).message });
+ }
+ continue;
+ }
+
if (!keyValue.trim()) {
errors.push({ key: keyName, error: 'keyValue must be at least 1 character' });
continue;
diff --git a/shared/types.ts b/shared/types.ts
index 50139e3d..5d841a42 100644
--- a/shared/types.ts
+++ b/shared/types.ts
@@ -194,6 +194,9 @@ export interface ApiKey {
status: KeyStatus;
enabled: boolean;
keyless: boolean;
+ /** Whether an export file would actually contain this row. The server decides
+ * it so the dialog's "will export N keys" cannot drift from the export. */
+ exportable: boolean;
createdAt: string;
lastCheckedAt: string | null;
lastHealthError: string | null;