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
Keep CSV labels on import (export/import round trip no longer renames keys) (#1303)
tashdroidde343c029016
diff --git a/server/src/__tests__/lib/key-parser.test.ts b/server/src/__tests__/lib/key-parser.test.tsindex 058f406a..27d1c6b8 100644--- a/server/src/__tests__/lib/key-parser.test.ts+++ b/server/src/__tests__/lib/key-parser.test.ts@@ -166,8 +166,8 @@ describe('key parser', () => {const result = parseExportJson(exportJson);expect(result).not.toBeNull();expect(result!.keys).toHaveLength(2);- expect(result!.keys[0]).toEqual({ rawKey: 'Google Key=AIza-test-key', prefix: 'GOOGLE_', platform: 'google' });- expect(result!.keys[1]).toEqual({ rawKey: 'Groq Key=gsk-test-key', prefix: 'GROQ_', platform: 'groq' });+ expect(result!.keys[0]).toEqual({ rawKey: 'Google Key=AIza-test-key', prefix: 'GOOGLE_', platform: 'google', label: 'Google Key' });+ expect(result!.keys[1]).toEqual({ rawKey: 'Groq Key=gsk-test-key', prefix: 'GROQ_', platform: 'groq', label: 'Groq Key' });expect(result!.skipped).toHaveLength(0);});@@ -183,22 +183,22 @@ describe('key parser', () => {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', platform: 'google' },- { key: 'GROQ_KEY', value: 'gsk-test', platform: 'groq' },+ { key: 'GOOGLE_KEY', value: 'AIza-test', platform: 'google', label: 'Google Key' },+ { key: 'GROQ_KEY', value: 'gsk-test', platform: 'groq', label: 'Groq Key' },]);});it('parses CSV format without header', () => {const csv = 'google,AIza-test,Google Key\n';expect(parseCsv(csv)).toEqual([- { key: 'GOOGLE_KEY', value: 'AIza-test', platform: 'google' },+ { key: 'GOOGLE_KEY', value: 'AIza-test', platform: 'google', label: 'Google Key' },]);});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' },+ { key: 'CUSTOM_KEY', value: 'sk-local', platform: 'custom', label: 'LM Studio', baseUrl: 'http://192.168.1.5:1234/v1' },]);});@@ -210,8 +210,8 @@ describe('key parser', () => {'"groq","gsk-abc","work, primary",""\n' +'"google","AIza-test","say ""hi""",""\n';expect(parseCsv(csv)).toEqual([- { key: 'GROQ_KEY', value: 'gsk-abc', platform: 'groq' },- { key: 'GOOGLE_KEY', value: 'AIza-test', platform: 'google' },+ { key: 'GROQ_KEY', value: 'gsk-abc', platform: 'groq', label: 'work, primary' },+ { key: 'GOOGLE_KEY', value: 'AIza-test', platform: 'google', label: 'say "hi"' },]);});@@ -224,6 +224,11 @@ describe('key parser', () => {expect(result.skipped).toEqual([]);expect(result.keys.map(k => k.platform)).toEqual(['groq', 'custom']);expect(result.keys[1]!.baseUrl).toBe('http://192.168.1.5:1234/v1');+ // Labels survive the round trip: rawKey's name half is what the import+ // route stores as the key label, so an export/import cycle used to+ // rename every key to the generated GROQ_KEY / CUSTOM_KEY.+ expect(result.keys[0]!.rawKey).toBe('work, primary=gsk-abc');+ expect(result.keys[1]!.rawKey).toBe('say "hi"=sk-local');});it('handles export JSON via parseKeysFromFile', () => {@@ -237,13 +242,15 @@ describe('key parser', () => {});const result = parseKeysFromFile(exportJson, 'freellmapi-keys.json');expect(result.keys).toHaveLength(1);- expect(result.keys[0]).toEqual({ rawKey: 'Mistral Key=mist-test', prefix: 'MISTRAL_', platform: 'mistral' });+ expect(result.keys[0]).toEqual({ rawKey: 'Mistral Key=mist-test', prefix: 'MISTRAL_', platform: 'mistral', label: 'Mistral Key' });});it('handles CSV via parseKeysFromFile', () => {const csv = 'platform,key,label\n"nvidia","nv-test","Nvidia Key"\n';const result = parseKeysFromFile(csv, 'freellmapi-keys.csv');expect(result.keys).toHaveLength(1);- expect(result.keys[0]).toEqual({ rawKey: 'NVIDIA_KEY=nv-test', prefix: 'NVIDIA_', platform: 'nvidia' });+ // The CSV label wins over the generated name, matching the export JSON+ // path above: the import route stores the rawKey name as the label.+ expect(result.keys[0]).toEqual({ rawKey: 'Nvidia Key=nv-test', prefix: 'NVIDIA_', platform: 'nvidia', label: 'Nvidia Key' });});});diff --git a/server/src/__tests__/routes/keys-export-custom-roundtrip.test.ts b/server/src/__tests__/routes/keys-export-custom-roundtrip.test.tsindex 98d57cb6..6af886be 100644--- a/server/src/__tests__/routes/keys-export-custom-roundtrip.test.ts+++ b/server/src/__tests__/routes/keys-export-custom-roundtrip.test.ts@@ -123,6 +123,27 @@ describe('#687 custom endpoints survive an export/import round trip', () => {expect(snapshot()).toEqual(before);});+ it.each(['csv', 'json'])('a %s export keeps awkward labels and secrets intact on re-import', async (format) => {+ getDb().prepare('DELETE FROM api_keys').run();+ // '=' in a label used to split the stored rawKey in the wrong place,+ // truncating the label and prepending its tail to the secret. The export's+ // formula guard also writes =/+/-/@ labels with a leading quote.+ addKey('groq', 'gsk-eq', 'team=alpha');+ addKey('groq', 'gsk-formula', '=HYPERLINK("x")');+ addKey('google', 'goog-comma', 'work, "primary"');+ addKey('google', 'goog-dash', '-backup');+ const labelled = () => (getDb().prepare('SELECT platform, label, encrypted_key, iv, auth_tag FROM api_keys').all() as any[])+ .map(r => `${r.platform}|${r.label}|${decrypt(r.encrypted_key, r.iv, r.auth_tag)}`)+ .sort();+ const before = labelled();+ 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(labelled()).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');diff --git a/server/src/lib/key-parser.ts b/server/src/lib/key-parser.tsindex dcc02676..353bbf4b 100644--- a/server/src/lib/key-parser.ts+++ b/server/src/lib/key-parser.ts@@ -19,6 +19,11 @@ export interface ParsedKey {/** Custom endpoints only: models declared beside the key via* CUSTOM_<n>_MODELS / <PREFIX>_CUSTOM_MODELS (#382). */models?: ParsedModelEntry[];+ /** Display name carried by a format that has one (CSV column 3, export+ * JSON `label`). The import route stores it when present instead of+ * falling back to the generated env-var-style name — without it a CSV+ * round trip renamed every key. */+ label?: string;}/** A key/value pair on its way to becoming a ParsedKey. `platform` and@@ -29,6 +34,7 @@ interface KeyPair {value: string;platform?: string;baseUrl?: string;+ label?: string;models?: ParsedModelEntry[];}@@ -393,7 +399,7 @@ export function parseExportJson(content: string): ParseResult | null {? (Object.entries(PREFIX_MAP).find(([, v]) => v === platform)?.[0] ?? `${platform.toUpperCase()}_`): '';const baseUrl = typeof row.baseUrl === 'string' ? row.baseUrl.trim() : '';- result.keys.push({ rawKey: `${label}=${keyValue}`, prefix, platform, ...(baseUrl ? { baseUrl } : {}) });+ result.keys.push({ rawKey: `${label}=${keyValue}`, prefix, platform, label, ...(baseUrl ? { baseUrl } : {}) });}return result;}@@ -448,6 +454,9 @@ export function parseCsv(content: string): KeyPair[] {const fields = splitCsvLine(lines[i]!);const platform = (fields[0] ?? '').trim();const key = (fields[1] ?? '').trim();+ // Undo the export's CSV formula guard (a leading ' before =, +, -, @, tab+ // or CR) so a guarded label comes back as the user typed it.+ const label = (fields[2] ?? '').trim().replace(/^'(?=[=+\-@\t\r])/, '');const baseUrl = (fields[3] ?? '').trim();if (!key || !platform) continue;@@ -455,7 +464,9 @@ export function parseCsv(content: string): KeyPair[] {const envKey = `${platform.toUpperCase()}_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 } : {}) });+ // The label (column 3) is carried so an export→import round trip keeps+ // display names: without it every groq key came back named GROQ_KEY.+ result.push({ key: envKey, value: key, platform, ...(label ? { label } : {}), ...(baseUrl ? { baseUrl } : {}) });}return result;@@ -668,13 +679,19 @@ function toParsedKeys(pairs: KeyPair[]): ParseResult {const keys: ParsedKey[] = [];const skipped: string[] = [];- for (const { key, value, platform: statedPlatform, baseUrl, models } of pairs) {+ for (const { key, value, platform: statedPlatform, baseUrl, label, models } of pairs) {const prefix = extractPrefix(key);const platform = statedPlatform ?? detectPlatform(prefix);+ // The name before `=` becomes the stored label (splitRawKey in the import+ // route). Formats that carry a display name — export JSON and CSV column 3+ // — use it here, exactly as parseExportJson does, so an export/import+ // round trip does not rename every key to the generated <PLATFORM>_KEY.+ const name = label?.trim() || key;if (platform) {keys.push({- rawKey: `${key}=${value}`, prefix, platform,+ rawKey: `${name}=${value}`, prefix, platform,+ ...(label ? { label } : {}),...(baseUrl ? { baseUrl } : {}),...(models?.length ? { models } : {}),});@@ -682,7 +699,7 @@ function toParsedKeys(pairs: KeyPair[]): ParseResult {}if (looksLikeApiKey(value)) {- keys.push({ rawKey: `${key}=${value}`, prefix, platform: null });+ keys.push({ rawKey: `${name}=${value}`, prefix, platform: null, ...(label ? { label } : {}) });} else {skipped.push(`${key}: value does not look like an API key`);}diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex 60500516..68ecba82 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -138,6 +138,18 @@ function parseUpload(file: Express.Multer.File) {return parseKeysFromFile(content, file.originalname);}+/** Name/value halves of a parsed key. A format that carries a label (CSV,+ * export JSON) names it outright: splitting `label=value` on the first '='+ * would cut a label like `team=alpha` short and prepend its tail to the+ * stored secret. */+function splitParsedKey(parsedKey: { rawKey: string; label?: string }) {+ const { rawKey, label } = parsedKey;+ if (label !== undefined && rawKey.startsWith(`${label}=`)) {+ return { keyName: label, keyValue: rawKey.slice(label.length + 1) };+ }+ return splitRawKey(rawKey);+}+function splitRawKey(rawKey: string) {const eqIndex = rawKey.indexOf('=');return {@@ -1191,7 +1203,7 @@ keysRouter.post('/import', (req: Request, res: Response, next: NextFunction) =>const urlVerdicts = new Map<string, { allowed: boolean; reason?: string }>();for (const parsedKey of result.keys) {- const { keyName, keyValue } = splitRawKey(parsedKey.rawKey);+ const { keyName, keyValue } = splitParsedKey(parsedKey);if (!parsedKey.platform) {skipped.push(keyName);continue;@@ -1300,7 +1312,7 @@ keysRouter.post('/preview', (req: Request, res: Response, next: NextFunction) =>for (const file of files) {const result = parseUpload(file);for (const parsedKey of result.keys) {- const { keyName, keyValue } = splitRawKey(parsedKey.rawKey);+ const { keyName, keyValue } = splitParsedKey(parsedKey);const isDuplicate = existingKeys.has(keyValue.trim());if (isDuplicate) duplicateCount++;keys.push({