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
feat(keys): export/import API keys with duplicate detection (#473)
Ariful Anik95dda1ed11da
diff --git a/client/src/components/keys/export-keys-dialog.tsx b/client/src/components/keys/export-keys-dialog.tsxnew file mode 100644index 00000000..f458789c--- /dev/null+++ b/client/src/components/keys/export-keys-dialog.tsx@@ -0,0 +1,138 @@+import { useState } from 'react'+import { useQuery } from '@tanstack/react-query'+import { X, Download } from 'lucide-react'+import { Dialog, DialogClose, DialogPopup, DialogTitle } from '@/components/ui/dialog'+import { Button } from '@/components/ui/button'+import { Label } from '@/components/ui/label'+import { Switch } from '@/components/ui/switch'+import { useI18n } from '@/i18n'+import { apiFetch, getToken } from '@/lib/api'+import { toast } from '@/lib/toast'+import type { ApiKey } from '../../../../shared/types'++type ExportFormat = 'json' | 'env' | 'csv'++const FORMAT_OPTIONS: { value: ExportFormat; label: string; ext: string }[] = [+ { value: 'json', label: 'JSON', ext: 'json' },+ { value: 'env', label: '.env', ext: 'env' },+ { value: 'csv', label: 'CSV', ext: 'csv' },+]++const BASE = import.meta.env.BASE_URL.replace(/\/$/, '');++async function downloadExport(format: ExportFormat, healthyOnly: boolean) {+ const token = getToken()+ const params = new URLSearchParams({ format })+ if (healthyOnly) params.set('healthy', 'true')+ const res = await fetch(`${BASE}/api/keys/export?${params}`, {+ headers: token ? { Authorization: `Bearer ${token}` } : {},+ })+ if (!res.ok) {+ const body = await res.json().catch(() => ({ error: { message: res.statusText } }))+ throw new Error(body.error?.message ?? `HTTP ${res.status}`)+ }+ const blob = await res.blob()+ const ext = FORMAT_OPTIONS.find(f => f.value === format)?.ext ?? format+ const url = URL.createObjectURL(blob)+ const a = document.createElement('a')+ a.href = url+ a.download = `freellmapi-keys.${ext}`+ a.click()+ URL.revokeObjectURL(url)+}++export function ExportKeysDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) {+ const { t } = useI18n()+ const [format, setFormat] = useState<ExportFormat>('json')+ const [healthyOnly, setHealthyOnly] = useState(false)+ const [exporting, setExporting] = useState(false)++ const { data: keys = [] } = useQuery<ApiKey[]>({+ queryKey: ['keys'],+ queryFn: () => apiFetch('/api/keys'),+ })++ const exportableKeys = keys.filter(k => !k.keyless)+ const exportCount = healthyOnly+ ? exportableKeys.filter(k => k.status === 'healthy').length+ : exportableKeys.length++ async function handleExport() {+ setExporting(true)+ try {+ await downloadExport(format, healthyOnly)+ toast.success(t('keys.exportSuccess', { count: exportCount }))+ onOpenChange(false)+ } catch (err) {+ toast.error((err as Error).message)+ } finally {+ setExporting(false)+ }+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogPopup maxWidth="max-w-md">+ <div className="mb-4 flex items-center justify-between gap-4">+ <DialogTitle>{t('keys.exportKeys')}</DialogTitle>+ <DialogClose+ aria-label={t('common.dismiss')}+ className="-mr-1 rounded-lg p-1 text-muted-foreground/70 transition-colors outline-none hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50"+ >+ <X className="size-4" />+ </DialogClose>+ </div>++ <div className="space-y-5">+ <div className="space-y-2">+ <Label className="text-xs">{t('keys.exportFormat')}</Label>+ <div className="flex gap-2">+ {FORMAT_OPTIONS.map(opt => (+ <Button+ key={opt.value}+ type="button"+ size="sm"+ variant={format === opt.value ? 'default' : 'outline'}+ onClick={() => setFormat(opt.value)}+ >+ {opt.label}+ </Button>+ ))}+ </div>+ </div>++ <div className="flex items-center justify-between gap-4 rounded-lg border p-3">+ <div className="space-y-0.5">+ <Label className="text-xs">{t('keys.exportHealthyOnly')}</Label>+ <p className="text-xs text-muted-foreground">+ {t('keys.exportHealthyOnlyDesc')}+ </p>+ </div>+ <Switch+ size="sm"+ checked={healthyOnly}+ onCheckedChange={setHealthyOnly}+ />+ </div>++ <div className="flex items-center justify-between rounded-lg bg-muted/50 px-3 py-2 text-xs text-muted-foreground">+ <span>{t('keys.exportWillExport')}</span>+ <span className="font-medium text-foreground">+ {exportCount} {exportCount === 1 ? t('keys.exportKey') : t('keys.exportKeys plural')}+ </span>+ </div>++ <Button+ type="button"+ className="w-full"+ onClick={handleExport}+ disabled={exporting || exportCount === 0}+ >+ <Download className="size-3.5" />+ {exporting ? t('keys.exporting') : t('keys.exportDownload')}+ </Button>+ </div>+ </DialogPopup>+ </Dialog>+ )+}diff --git a/client/src/components/keys/import-keys-section.tsx b/client/src/components/keys/import-keys-section.tsxindex 229c7cdd..788db8bc 100644--- a/client/src/components/keys/import-keys-section.tsx+++ b/client/src/components/keys/import-keys-section.tsx@@ -16,6 +16,7 @@ interface ImportRow extends PreviewKey {selected: booleanplatform: Platform | ''visible: boolean+ isDuplicate: boolean}// Always rendered inside the Add key dialog: no outer section chrome/heading.@@ -49,8 +50,9 @@ export function ImportKeysSection({ onImported }: { onImported?: () => void } =return {...key,platform: detected,- selected: detected !== '',+ selected: detected !== '' && !key.isDuplicate,visible: false,+ isDuplicate: key.isDuplicate ?? false,}}))setSkipped(data.skipped)@@ -119,7 +121,7 @@ export function ImportKeysSection({ onImported }: { onImported?: () => void } =<Inputtype="file"multiple- accept=".env,.json,.jsonc,.md,.txt"+ accept=".env,.json,.jsonc,.md,.txt,.csv"onChange={chooseFiles}className="cursor-pointer text-xs file:mr-2"/>@@ -148,11 +150,12 @@ export function ImportKeysSection({ onImported }: { onImported?: () => void } =</TableHeader><TableBody>{rows.map((row, index) => (- <TableRow key={`${row.keyName}:${index}`}>+ <TableRow key={`${row.keyName}:${index}`} className={row.isDuplicate ? 'bg-muted/50' : ''}><TableCell><inputtype="checkbox"checked={row.selected}+ disabled={row.isDuplicate}onChange={() => updateRow(index, { selected: !row.selected })}className="size-4 accent-primary"/>@@ -173,11 +176,18 @@ export function ImportKeysSection({ onImported }: { onImported?: () => void } =</Select></TableCell><TableCell>- <Input- value={row.keyName}- onChange={e => updateRow(index, { keyName: e.target.value })}- className="w-[220px] font-mono text-xs"- />+ <div className="flex items-center gap-2">+ <Input+ value={row.keyName}+ onChange={e => updateRow(index, { keyName: e.target.value })}+ className="w-[220px] font-mono text-xs"+ />+ {row.isDuplicate && (+ <span className="shrink-0 rounded bg-amber-500/15 px-1.5 py-0.5 text-[10px] font-medium text-amber-600 dark:text-amber-400">+ {t('keys.duplicate')}+ </span>+ )}+ </div></TableCell><TableCell><div className="flex min-w-[280px] items-center gap-2">@@ -218,6 +228,11 @@ export function ImportKeysSection({ onImported }: { onImported?: () => void } ={rows.length > 0 && (<div className="mt-4 flex flex-wrap items-center gap-3">+ {rows.some(r => r.isDuplicate) && (+ <span className="text-xs text-amber-600 dark:text-amber-400">+ {t('keys.duplicatesFound', { count: rows.filter(r => r.isDuplicate).length })}+ </span>+ )}<Buttontype="button"size="sm"diff --git a/client/src/i18n/locales/en.json b/client/src/i18n/locales/en.jsonindex c81718ce..6ef574ba 100644--- a/client/src/i18n/locales/en.json+++ b/client/src/i18n/locales/en.json@@ -222,6 +222,19 @@"selectPlatform": "Select a provider","addKey": "Add key","keyAdded": "Key added",+ "export": "Export",+ "exportAll": "All keys",+ "exportHealthy": "Healthy only",+ "exportKeys": "Export API keys",+ "exportFormat": "Format",+ "exportHealthyOnly": "Healthy keys only",+ "exportHealthyOnlyDesc": "Exclude keys that are currently failing health checks",+ "exportWillExport": "Will export",+ "exportKey": "key",+ "exportKeys plural": "keys",+ "exporting": "Exporting…",+ "exportDownload": "Download",+ "exportSuccess": "Exported {count} keys","adding": "Adding…","selectProvider": "Select a provider…","accountId": "Account ID",@@ -293,7 +306,7 @@"proxyEnvHintBefore": "Also configurable via the ","proxyEnvHintAfter": " environment variable (takes precedence). Leave blank to disable. Examples:","importKeys": "Import provider keys",- "importKeysDescription": "Upload .env, JSON, JSONC, Markdown, or text files.",+ "importKeysDescription": "Upload .env, JSON, JSONC, CSV, Markdown, or text files.","importFiles": "Files","importFileCount": "{count} selected","previewFiles": "Preview",@@ -309,6 +322,8 @@"importSelected": "Import {count}","importing": "Importing…","noImportSelection": "Select at least one row with a provider.",+ "duplicate": "Duplicate",+ "duplicatesFound": "{count} duplicate(s) detected — already exist and will be skipped.","importResult": "Imported {imported}; failed {failed}.","confirmRemove": "Confirm?","quotaSignalsTitle": "Quota signals",diff --git a/client/src/i18n/locales/es.json b/client/src/i18n/locales/es.jsonindex 382deed4..810c339b 100644--- a/client/src/i18n/locales/es.json+++ b/client/src/i18n/locales/es.json@@ -285,7 +285,7 @@"addImageModel": "Agregar modelo de imagen","addAudioModel": "Agregar modelo de audio","importKeys": "Importar claves de proveedor",- "importKeysDescription": "Sube archivos .env, JSON, JSONC, Markdown o de texto.",+ "importKeysDescription": "Sube archivos .env, JSON, JSONC, CSV, Markdown o de texto.","importFiles": "Archivos","importFileCount": "{count} seleccionados","previewFiles": "Vista previa",@@ -301,7 +301,26 @@"importSelected": "Importar {count}","importing": "Importando…","noImportSelection": "Selecciona al menos una fila con un proveedor.",- "importResult": "Importados {imported}; fallidos {failed}."+ "duplicate": "Duplicado",+ "duplicatesFound": "{count} duplicado(s) detectado(s) — ya existen y se omitirán.",+ "importResult": "Importados {imported}; fallidos {failed}.",+ "export": {+ "json": "JSON",+ "env": ".env",+ "csv": "CSV"+ },+ "exportAll": "All keys",+ "exportHealthy": "Healthy only",+ "exportKeys": "Export API keys",+ "exportFormat": "Format",+ "exportHealthyOnly": "Healthy keys only",+ "exportHealthyOnlyDesc": "Exclude keys that are currently failing health checks",+ "exportWillExport": "Will export",+ "exportKey": "key",+ "exportKeys plural": "keys",+ "exporting": "Exporting…",+ "exportDownload": "Download",+ "exportSuccess": "Exported {count} keys"},"status": {"healthy": "correcto",diff --git a/client/src/i18n/locales/fr.json b/client/src/i18n/locales/fr.jsonindex 77d3a964..3840f862 100644--- a/client/src/i18n/locales/fr.json+++ b/client/src/i18n/locales/fr.json@@ -285,7 +285,7 @@"addImageModel": "Ajouter un modèle d'image","addAudioModel": "Ajouter un modèle audio","importKeys": "Importer des clés de fournisseur",- "importKeysDescription": "Téléversez des fichiers .env, JSON, JSONC, Markdown ou texte.",+ "importKeysDescription": "Téléversez des fichiers .env, JSON, JSONC, CSV, Markdown ou texte.","importFiles": "Fichiers","importFileCount": "{count} sélectionnés","previewFiles": "Aperçu",@@ -301,7 +301,26 @@"importSelected": "Importer {count}","importing": "Importation en cours…","noImportSelection": "Sélectionnez au moins une ligne avec un fournisseur.",- "importResult": "Importés : {imported}. Échecs : {failed}."+ "duplicate": "Doublon",+ "duplicatesFound": "{count} doublon(s) détecté(s) — existent déjà et seront ignorés.",+ "importResult": "Importés : {imported}. Échecs : {failed}.",+ "export": {+ "json": "JSON",+ "env": ".env",+ "csv": "CSV"+ },+ "exportAll": "All keys",+ "exportHealthy": "Healthy only",+ "exportKeys": "Export API keys",+ "exportFormat": "Format",+ "exportHealthyOnly": "Healthy keys only",+ "exportHealthyOnlyDesc": "Exclude keys that are currently failing health checks",+ "exportWillExport": "Will export",+ "exportKey": "key",+ "exportKeys plural": "keys",+ "exporting": "Exporting…",+ "exportDownload": "Download",+ "exportSuccess": "Exported {count} keys"},"status": {"healthy": "sain",diff --git a/client/src/i18n/locales/it.json b/client/src/i18n/locales/it.jsonindex 0b30ecca..33746736 100644--- a/client/src/i18n/locales/it.json+++ b/client/src/i18n/locales/it.json@@ -285,7 +285,7 @@"addImageModel": "Aggiungi modello immagine","addAudioModel": "Aggiungi modello audio","importKeys": "Importa chiavi provider",- "importKeysDescription": "Carica file .env, JSON, JSONC, Markdown o di testo.",+ "importKeysDescription": "Carica file .env, JSON, JSONC, CSV, Markdown o di testo.","importFiles": "File","importFileCount": "{count} selezionati","previewFiles": "Anteprima",@@ -301,7 +301,26 @@"importSelected": "Importa {count}","importing": "Importazione in corso…","noImportSelection": "Seleziona almeno una riga con un provider.",- "importResult": "Importati {imported}; falliti {failed}."+ "duplicate": "Duplicato",+ "duplicatesFound": "{count} duplicato/i rilevato/i — già esistente/i e verrà/no saltato/i.",+ "importResult": "Importati {imported}; falliti {failed}.",+ "export": {+ "json": "JSON",+ "env": ".env",+ "csv": "CSV"+ },+ "exportAll": "All keys",+ "exportHealthy": "Healthy only",+ "exportKeys": "Export API keys",+ "exportFormat": "Format",+ "exportHealthyOnly": "Healthy keys only",+ "exportHealthyOnlyDesc": "Exclude keys that are currently failing health checks",+ "exportWillExport": "Will export",+ "exportKey": "key",+ "exportKeys plural": "keys",+ "exporting": "Exporting…",+ "exportDownload": "Download",+ "exportSuccess": "Exported {count} keys"},"status": {"healthy": "funzionante",diff --git a/client/src/i18n/locales/pt-BR.json b/client/src/i18n/locales/pt-BR.jsonindex 4dd8bb06..180720c6 100644--- a/client/src/i18n/locales/pt-BR.json+++ b/client/src/i18n/locales/pt-BR.json@@ -285,7 +285,7 @@"addImageModel": "Adicionar modelo de imagem","addAudioModel": "Adicionar modelo de áudio","importKeys": "Importar chaves de provedor",- "importKeysDescription": "Envie arquivos .env, JSON, JSONC, Markdown ou texto.",+ "importKeysDescription": "Envie arquivos .env, JSON, JSONC, CSV, Markdown ou texto.","importFiles": "Arquivos","importFileCount": "{count} selecionados","previewFiles": "Pré-visualizar",@@ -301,7 +301,26 @@"importSelected": "Importar {count}","importing": "Importando…","noImportSelection": "Selecione pelo menos uma linha com um provedor.",- "importResult": "Importados {imported}; falharam {failed}."+ "duplicate": "Duplicado",+ "duplicatesFound": "{count} duplicado(s) detectado(s) — já existem e serão ignorados.",+ "importResult": "Importados {imported}; falharam {failed}.",+ "export": {+ "json": "JSON",+ "env": ".env",+ "csv": "CSV"+ },+ "exportAll": "All keys",+ "exportHealthy": "Healthy only",+ "exportKeys": "Export API keys",+ "exportFormat": "Format",+ "exportHealthyOnly": "Healthy keys only",+ "exportHealthyOnlyDesc": "Exclude keys that are currently failing health checks",+ "exportWillExport": "Will export",+ "exportKey": "key",+ "exportKeys plural": "keys",+ "exporting": "Exporting…",+ "exportDownload": "Download",+ "exportSuccess": "Exported {count} keys"},"status": {"healthy": "saudável",diff --git a/client/src/i18n/locales/zh-CN.json b/client/src/i18n/locales/zh-CN.jsonindex af5f2160..8134a051 100644--- a/client/src/i18n/locales/zh-CN.json+++ b/client/src/i18n/locales/zh-CN.json@@ -285,7 +285,7 @@"addImageModel": "添加图像模型","addAudioModel": "添加音频模型","importKeys": "导入提供方密钥",- "importKeysDescription": "上传 .env、JSON、JSONC、Markdown 或文本文件。",+ "importKeysDescription": "上传 .env、JSON、JSONC、CSV、Markdown 或文本文件。","importFiles": "文件","importFileCount": "已选择 {count} 个","previewFiles": "预览",@@ -301,7 +301,26 @@"importSelected": "导入 {count} 个","importing": "导入中…","noImportSelection": "请至少选择一行包含提供方的记录。",- "importResult": "已导入 {imported} 个;失败 {failed} 个。"+ "duplicate": "重复",+ "duplicatesFound": "检测到 {count} 个重复项 — 已存在,将被跳过。",+ "importResult": "已导入 {imported} 个;失败 {failed} 个。",+ "export": {+ "json": "JSON",+ "env": ".env",+ "csv": "CSV"+ },+ "exportAll": "All keys",+ "exportHealthy": "Healthy only",+ "exportKeys": "Export API keys",+ "exportFormat": "Format",+ "exportHealthyOnly": "Healthy keys only",+ "exportHealthyOnlyDesc": "Exclude keys that are currently failing health checks",+ "exportWillExport": "Will export",+ "exportKey": "key",+ "exportKeys plural": "keys",+ "exporting": "Exporting…",+ "exportDownload": "Download",+ "exportSuccess": "Exported {count} keys"},"status": {"healthy": "健康",diff --git a/client/src/pages/KeysPage.tsx b/client/src/pages/KeysPage.tsxindex c4f26ee3..fe347dff 100644--- a/client/src/pages/KeysPage.tsx+++ b/client/src/pages/KeysPage.tsx@@ -5,7 +5,7 @@ import { Button } from '@/components/ui/button'import { SegmentedControl } from '@/components/ui/segmented-control'import { PageHeader } from '@/components/page-header'import type { ApiKey } from '../../../shared/types'-import { Plus } from 'lucide-react'+import { Plus, Download } from 'lucide-react'import { useI18n } from '@/i18n'import type { HealthData } from '@/components/keys/shared'import { QuotaSignalsSection } from '@/components/keys/quota-signals-section'@@ -14,6 +14,7 @@ import { ProxySettingsSection } from '@/components/keys/proxy-settings-section'import { AnthropicSection } from '@/components/keys/anthropic-section'import { ProviderList } from '@/components/keys/provider-list'import { AddKeyDialog } from '@/components/keys/add-key-dialog'+import { ExportKeysDialog } from '@/components/keys/export-keys-dialog'type KeysTab = 'providers' | 'quotaSignals' | 'apiKey' | 'anthropic'const KEYS_TABS: { id: KeysTab; labelKey: string }[] = [@@ -28,6 +29,7 @@ export default function KeysPage() {const queryClient = useQueryClient()const [tab, setTab] = useState<KeysTab>('providers')const [addOpen, setAddOpen] = useState(false)+ const [exportOpen, setExportOpen] = useState(false)// Kept at page level for the header's "Check all" gate; ProviderList runs the// same query (deduped by react-query) for the list itself.@@ -62,6 +64,12 @@ export default function KeysPage() {{checkAll.isPending ? t('keys.checking') : t('keys.checkAll')}</Button>)}+ {keys.length > 0 && (+ <Button variant="outline" size="sm" onClick={() => setExportOpen(true)}>+ <Download className="size-3.5" />+ {t('keys.export')}+ </Button>+ )}{tab === 'providers' && (<Button size="sm" onClick={() => setAddOpen(true)}><Plus className="size-3.5" />@@ -96,6 +104,7 @@ export default function KeysPage() {</div><AddKeyDialog open={addOpen} onOpenChange={setAddOpen} />+ <ExportKeysDialog open={exportOpen} onOpenChange={setExportOpen} /></div>)}diff --git a/server/src/__tests__/lib/key-parser.test.ts b/server/src/__tests__/lib/key-parser.test.tsindex c00c85a6..50c2b421 100644--- a/server/src/__tests__/lib/key-parser.test.ts+++ b/server/src/__tests__/lib/key-parser.test.ts@@ -4,7 +4,9 @@ import {detectPlatform,looksLikeApiKey,parseAuthJson,+ parseCsv,parseDotEnv,+ parseExportJson,parseJson,parseKeysFromFile,stripJsoncComments,@@ -65,4 +67,64 @@ describe('key parser', () => {expect(looksLikeApiKey('https://example.com')).toBe(false);expect(looksLikeApiKey('sk-valid-token')).toBe(true);});++ it('parses FreeLLMAPI export JSON format', () => {+ const exportJson = JSON.stringify({+ version: 1,+ exportedAt: '2026-07-06T12:00:00Z',+ source: 'freellmapi',+ keys: [+ { platform: 'google', key: 'AIza-test-key', label: 'Google Key' },+ { platform: 'groq', key: 'gsk-test-key', label: 'Groq Key' },+ ],+ });+ 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!.skipped).toHaveLength(0);+ });++ it('returns null for non-export JSON', () => {+ expect(parseExportJson('{"foo":"bar"}')).toBeNull();+ expect(parseExportJson('[1,2,3]')).toBeNull();+ expect(parseExportJson('not json')).toBeNull();+ });++ 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' },+ ]);+ });++ it('parses CSV format without header', () => {+ const csv = 'google,AIza-test,Google Key\n';+ expect(parseCsv(csv)).toEqual([+ { key: 'GOOGLE_KEY', value: 'AIza-test' },+ ]);+ });++ it('handles export JSON via parseKeysFromFile', () => {+ const exportJson = JSON.stringify({+ version: 1,+ exportedAt: '2026-07-06T12:00:00Z',+ source: 'freellmapi',+ keys: [+ { platform: 'mistral', key: 'mist-test', label: 'Mistral Key' },+ ],+ });+ 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' });+ });++ 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' });+ });});diff --git a/server/src/__tests__/routes/keys.test.ts b/server/src/__tests__/routes/keys.test.tsindex f1941a8e..18203226 100644--- a/server/src/__tests__/routes/keys.test.ts+++ b/server/src/__tests__/routes/keys.test.ts@@ -245,11 +245,12 @@ describe('Keys API', () => {expect(status).toBe(200);expect(body.keys).toEqual([- { keyName: 'GROQ_API_KEY', keyValue: 'gsk_test123', detectedPlatform: 'groq', prefix: 'GROQ_' },- { keyName: 'ANTHROPIC_API_KEY', keyValue: 'sk-ant-test', detectedPlatform: null, prefix: 'ANTHROPIC_' },- { keyName: 'MISTRAL_API_KEY', keyValue: 'mist_test456', detectedPlatform: 'mistral', prefix: 'MISTRAL_' },+ { keyName: 'GROQ_API_KEY', keyValue: 'gsk_test123', detectedPlatform: 'groq', prefix: 'GROQ_', isDuplicate: false },+ { keyName: 'ANTHROPIC_API_KEY', keyValue: 'sk-ant-test', detectedPlatform: null, prefix: 'ANTHROPIC_', isDuplicate: false },+ { keyName: 'MISTRAL_API_KEY', keyValue: 'mist_test456', detectedPlatform: 'mistral', prefix: 'MISTRAL_', isDuplicate: false },]);expect(body.total).toBe(3);+ expect(body.duplicates).toBe(0);});it('imports selected preview rows', async () => {diff --git a/server/src/lib/key-parser.ts b/server/src/lib/key-parser.tsindex 111b3b95..19fbab3c 100644--- a/server/src/lib/key-parser.ts+++ b/server/src/lib/key-parser.ts@@ -188,6 +188,86 @@ export function parseJson(content: string): Array<{ key: string; value: string }.map(([key, value]) => ({ key, value }));}+/**+ * Parse the FreeLLMAPI export JSON format:+ * { version: 1, exportedAt, source, keys: [{ platform, key, label, baseUrl? }] }+ * Returns key-value pairs compatible with toParsedKeys().+ */+export function parseExportJson(content: string): ParseResult | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(content);+ } catch {+ return null;+ }++ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {+ return null;+ }++ const obj = parsed as Record<string, unknown>;+ if (!('keys' in obj) || !Array.isArray(obj.keys)) {+ return null;+ }++ // Validate it looks like our export format (has version + keys array of objects)+ const keys = obj.keys as unknown[];+ if (keys.length > 0 && typeof keys[0] === 'object' && keys[0] !== null && 'platform' in (keys[0] as any) && 'key' in (keys[0] as any)) {+ const result: ParseResult = { keys: [], skipped: [] };+ for (const entry of keys) {+ if (typeof entry !== 'object' || entry === null) continue;+ const row = entry as Record<string, unknown>;+ const platform = typeof row.platform === 'string' ? row.platform : null;+ const keyValue = typeof row.key === 'string' ? row.key : '';+ const label = typeof row.label === 'string' ? row.label : platform ?? 'imported';++ if (!keyValue.trim()) {+ result.skipped.push(`${label}: empty key value`);+ continue;+ }++ const prefix = platform+ ? (Object.entries(PREFIX_MAP).find(([, v]) => v === platform)?.[0] ?? `${platform.toUpperCase()}_`)+ : '';+ result.keys.push({ rawKey: `${label}=${keyValue}`, prefix, platform });+ }+ return result;+ }++ return null;+}++/**+ * Parse CSV format: platform,key,label (with optional header row).+ */+export function parseCsv(content: string): Array<{ key: string; value: string }> {+ const lines = content.split('\n').filter(l => l.trim());+ if (lines.length === 0) return [];++ const result: Array<{ key: string; value: string }> = [];++ // Skip header row if it looks like a CSV header+ const startIdx = lines[0]!.toLowerCase().startsWith('platform,') ? 1 : 0;++ for (let i = startIdx; i < lines.length; i++) {+ const line = lines[i]!;+ // Simple CSV parsing: split on comma, strip quotes+ const match = line.match(/^"?([^"]*?)"?,"?([^"]*?)"?(?:,"?([^"]*?)"?)?$/);+ if (!match) continue;++ const platform = (match[1] ?? '').trim();+ const key = (match[2] ?? '').trim();+ const label = (match[3] ?? '').trim() || platform;++ if (!key || !platform) continue;++ const envKey = `${platform.toUpperCase()}_KEY`;+ result.push({ key: envKey, value: key });+ }++ return result;+}+export function parseAuthJson(content: string): ParseResult {let parsed: unknown;try {@@ -301,6 +381,11 @@ export function parseKeysFromFile(content: string, filename: string): ParseResulconst ext = filename.includes('.') ? filename.slice(filename.lastIndexOf('.')).toLowerCase() : '';if (ext === '.json' || ext === '.jsonc') {const clean = stripTrailingCommas(stripJsoncComments(text));++ // Check for FreeLLMAPI export format first (version + keys array)+ const exportResult = parseExportJson(clean);+ if (exportResult) return exportResult;+let parsed: unknown;try {parsed = JSON.parse(clean);@@ -313,5 +398,9 @@ export function parseKeysFromFile(content: string, filename: string): ParseResulreturn toParsedKeys(parseJson(clean));}+ if (ext === '.csv') {+ return toParsedKeys(parseCsv(text));+ }+return toParsedKeys(parseDotEnv(text));}diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex 8c97e2fe..5fa62431 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -22,7 +22,7 @@ const PLATFORMS = ['routeway', 'bazaarlink', 'ainative', 'aihorde', 'custom',] as const;-const ALLOWED_IMPORT_EXTENSIONS = new Set(['.env', '.json', '.jsonc', '.md', '.txt']);+const ALLOWED_IMPORT_EXTENSIONS = new Set(['.env', '.json', '.jsonc', '.md', '.txt', '.csv']);const upload = multer({storage: multer.memoryStorage(),@@ -204,6 +204,7 @@ keysRouter.get('/', (_req: Request, res: Response) => {baseUrl: row.base_url ?? null,status: row.status,enabled: row.enabled === 1,+ keyless: resolveProvider(row.platform)?.keyless === true,createdAt: row.created_at,lastCheckedAt: row.last_checked_at,models: row.platform === 'custom' ? (modelsByKeyId.get(row.id) ?? []) : undefined,@@ -213,6 +214,86 @@ keysRouter.get('/', (_req: Request, res: Response) => {res.json(keys);});+// 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).+keysRouter.get('/export', (req: Request, res: Response) => {+ const db = getDb();+ const format = (req.query.format as string) ?? 'json';+ const healthyOnly = req.query.healthy === 'true';++ let whereClause = '';+ if (healthyOnly) {+ whereClause = "WHERE status = 'healthy'";+ }++ const rows = db.prepare(`SELECT * FROM api_keys ${whereClause} ORDER BY platform, created_at ASC`).all() as any[];++ // Decrypt and filter — only export keys with a real value+ const decryptedKeys = rows+ .map(row => {+ let key = '';+ try {+ key = decrypt(row.encrypted_key, row.iv, row.auth_tag);+ } catch {+ key = '';+ }+ return {+ platform: row.platform,+ key,+ label: row.label || '',+ baseUrl: row.base_url || undefined,+ };+ })+ .filter(k => {+ const v = k.key.trim();+ return v.length > 0 && v !== 'no-key';+ });++ if (decryptedKeys.length === 0) {+ res.status(404).json({ error: { message: 'No keys to export' } });+ return;+ }++ if (format === 'env') {+ // .env format: GOOGLE_KEY=xxx\nGROQ_KEY=yyy+ const lines = decryptedKeys.map(k => {+ const envKey = `${k.platform.toUpperCase()}_KEY=${k.key}`;+ return k.label ? `# ${k.label}\n${envKey}` : envKey;+ });+ const content = lines.join('\n\n') + '\n';+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');+ res.setHeader('Content-Disposition', 'attachment; filename="freellmapi-keys.env"');+ res.send(content);+ return;+ }++ if (format === 'csv') {+ // CSV format: platform,key,label+ const escCsv = (v: string) => `"${v.replace(/"/g, '""')}"`;+ const header = 'platform,key,label';+ const lines = decryptedKeys.map(k =>+ [escCsv(k.platform), escCsv(k.key), escCsv(k.label)].join(',')+ );+ const content = [header, ...lines].join('\n') + '\n';+ res.setHeader('Content-Type', 'text/csv; charset=utf-8');+ res.setHeader('Content-Disposition', 'attachment; filename="freellmapi-keys.csv"');+ res.send(content);+ return;+ }++ // Default: JSON format (round-trip safe — can be imported directly)+ const jsonExport = {+ version: 1,+ exportedAt: new Date().toISOString(),+ source: 'freellmapi',+ keys: decryptedKeys,+ };+ res.setHeader('Content-Type', 'application/json; charset=utf-8');+ res.setHeader('Content-Disposition', 'attachment; filename="freellmapi-keys.json"');+ res.json(jsonExport);+});+// Add a keykeysRouter.post('/', (req: Request, res: Response) => {const parsed = addKeySchema.safeParse(req.body);@@ -490,24 +571,39 @@ keysRouter.post('/preview', (req: Request, res: Response, next: NextFunction) =>return;}- const keys: Array<{ keyName: string; keyValue: string; detectedPlatform: string | null; prefix: string }> = [];+ const keys: Array<{ keyName: string; keyValue: string; detectedPlatform: string | null; prefix: string; isDuplicate: boolean }> = [];const skipped: string[] = [];+ // Build a set of existing decrypted key values for duplicate detection+ const db = getDb();+ const existingRows = db.prepare('SELECT encrypted_key, iv, auth_tag FROM api_keys').all() as any[];+ const existingKeys = new Set<string>();+ for (const row of existingRows) {+ try {+ existingKeys.add(decrypt(row.encrypted_key, row.iv, row.auth_tag));+ } catch { /* skip undecryptable rows */ }+ }++ let duplicateCount = 0;+for (const file of files) {const result = parseUpload(file);for (const parsedKey of result.keys) {const { keyName, keyValue } = splitRawKey(parsedKey.rawKey);+ const isDuplicate = existingKeys.has(keyValue.trim());+ if (isDuplicate) duplicateCount++;keys.push({keyName,keyValue,detectedPlatform: parsedKey.platform,prefix: parsedKey.prefix,+ isDuplicate,});}skipped.push(...result.skipped);}- res.json({ keys, total: keys.length, skipped });+ res.json({ keys, total: keys.length, skipped, duplicates: duplicateCount });} catch (handlerErr: any) {res.status(handlerErr.status ?? 500).json({ error: { message: handlerErr.message } });}@@ -522,8 +618,19 @@ keysRouter.post('/import-selected', (req: Request, res: Response) => {}let imported = 0;+ let duplicateSkipped = 0;const errors: Array<{ key: string; error: string }> = [];+ // Build a set of existing decrypted key values for duplicate detection+ const db = getDb();+ const existingRows = db.prepare('SELECT encrypted_key, iv, auth_tag FROM api_keys').all() as any[];+ const existingKeys = new Set<string>();+ for (const row of existingRows) {+ try {+ existingKeys.add(decrypt(row.encrypted_key, row.iv, row.auth_tag));+ } catch { /* skip undecryptable rows */ }+ }+for (const key of parsed.data.keys) {const keyName = key.keyName?.trim() || key.platform;if (key.platform === 'custom') {@@ -531,9 +638,16 @@ keysRouter.post('/import-selected', (req: Request, res: Response) => {continue;}+ if (existingKeys.has(key.keyValue.trim())) {+ duplicateSkipped++;+ errors.push({ key: keyName, error: 'Duplicate key — already exists' });+ continue;+ }+try {insertImportedKey(key.platform, keyName, key.keyValue);imported++;+ existingKeys.add(key.keyValue.trim());} catch (err) {errors.push({ key: keyName, error: (err as Error).message });}diff --git a/shared/types.ts b/shared/types.tsindex e80bd94b..5c737d99 100644--- a/shared/types.ts+++ b/shared/types.ts@@ -5,6 +5,7 @@ export interface PreviewKey {keyValue: string;detectedPlatform: string | null;prefix: string;+ isDuplicate?: boolean;}export interface ImportKey {@@ -17,6 +18,7 @@ export interface PreviewResponse {keys: PreviewKey[];total: number;skipped: string[];+ duplicates: number;}export interface ImportSelectedRequest {@@ -159,6 +161,7 @@ export interface ApiKey {baseUrl: string | null;status: KeyStatus;enabled: boolean;+ keyless: boolean;createdAt: string;lastCheckedAt: string | null;models?: ApiKeyModel[];