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

feat(key-import): add provider key import flow

Aldo5918efc6b3ce
diff --git a/client/src/i18n/locales/en.json b/client/src/i18n/locales/en.json
index 7e0269c4..ef44650a 100644
--- a/client/src/i18n/locales/en.json
+++ b/client/src/i18n/locales/en.json
@@ -275,6 +275,24 @@
"keyCountOther": "{count} keys",
"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.",
+ "importFiles": "Files",
+ "importFileCount": "{count} selected",
+ "previewFiles": "Preview",
+ "previewing": "Previewing…",
+ "selected": "Selected",
+ "provider": "Provider",
+ "keyName": "Key name",
+ "keyValue": "Key value",
+ "chooseProvider": "Choose provider",
+ "noPreviewKeys": "No keys found in those files.",
+ "skippedItems": "Skipped:",
+ "moreItems": "+{count} more",
+ "importSelected": "Import {count}",
+ "importing": "Importing…",
+ "noImportSelection": "Select at least one row with a provider.",
+ "importResult": "Imported {imported}; failed {failed}.",
"confirmRemove": "Confirm?"
},
"status": {
diff --git a/client/src/lib/api.ts b/client/src/lib/api.ts
index 319f9df0..9a6751b9 100644
--- a/client/src/lib/api.ts
+++ b/client/src/lib/api.ts
@@ -17,16 +17,20 @@ export const UNAUTHORIZED_EVENT = 'freellmapi:unauthorized';
export async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {
const token = getToken();
+ const headers = new Headers(options?.headers);
+ const isFormData = typeof FormData !== 'undefined' && options?.body instanceof FormData;
+ if (!isFormData && !headers.has('Content-Type')) {
+ headers.set('Content-Type', 'application/json');
+ }
+ if (token) {
+ headers.set('Authorization', `Bearer ${token}`);
+ }
const res = await fetch(`${BASE}${path}`, {
// `...options` first so an explicit method/body/signal applies, but headers
// are merged last — otherwise an options.headers would clobber the
// Content-Type and Authorization we set here.
...options,
- headers: {
- 'Content-Type': 'application/json',
- ...(token ? { Authorization: `Bearer ${token}` } : {}),
- ...options?.headers,
- },
+ headers,
});
if (res.status === 401) {
// Session missing/expired — drop the token and let the AuthGate re-render.
diff --git a/client/src/pages/KeysPage.tsx b/client/src/pages/KeysPage.tsx
index 48e44457..a11074fe 100644
--- a/client/src/pages/KeysPage.tsx
+++ b/client/src/pages/KeysPage.tsx
@@ -7,9 +7,10 @@ import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { PageHeader } from '@/components/page-header'
-import type { ApiKey, ApiKeyModel, Platform, ProviderQuotaState } from '../../../shared/types'
-import { ChevronDown, Pencil, ExternalLink, Globe, Trash2 } from 'lucide-react'
+import type { ApiKey, ApiKeyModel, ImportKey, ImportSelectedResponse, Platform, PreviewKey, PreviewResponse, ProviderQuotaState } from '../../../shared/types'
+import { ChevronDown, Pencil, ExternalLink, Globe, Trash2, Upload } from 'lucide-react'
import { formatSqliteUtcToLocalTime } from '@/lib/utils'
import { useI18n } from '@/i18n'
@@ -358,6 +359,239 @@ function ProxySettingsSection() {
)
}
+interface ImportRow extends PreviewKey {
+ selected: boolean
+ platform: Platform | ''
+ visible: boolean
+}
+
+function ImportKeysSection() {
+ const { t } = useI18n()
+ const queryClient = useQueryClient()
+ const [files, setFiles] = useState<File[]>([])
+ const [rows, setRows] = useState<ImportRow[]>([])
+ const [skipped, setSkipped] = useState<string[]>([])
+ const [result, setResult] = useState<ImportSelectedResponse | null>(null)
+
+ const importablePlatforms = PLATFORMS.filter(p => !p.keyless)
+
+ function platformFromPreview(key: PreviewKey): Platform | '' {
+ return importablePlatforms.some(p => p.value === key.detectedPlatform)
+ ? key.detectedPlatform as Platform
+ : ''
+ }
+
+ const preview = useMutation({
+ mutationFn: async (nextFiles: File[]) => {
+ const formData = new FormData()
+ nextFiles.forEach(file => formData.append('files', file))
+ return apiFetch<PreviewResponse>('/api/keys/preview', { method: 'POST', body: formData })
+ },
+ onSuccess: (data) => {
+ setRows(data.keys.map(key => {
+ const detected = platformFromPreview(key)
+ return {
+ ...key,
+ platform: detected,
+ selected: detected !== '',
+ visible: false,
+ }
+ }))
+ setSkipped(data.skipped)
+ setResult(null)
+ },
+ })
+
+ const importSelected = useMutation({
+ mutationFn: (keys: ImportKey[]) =>
+ apiFetch<ImportSelectedResponse>('/api/keys/import-selected', {
+ method: 'POST',
+ body: JSON.stringify({ keys }),
+ }),
+ onSuccess: (data) => {
+ setResult(data)
+ queryClient.invalidateQueries({ queryKey: ['keys'] })
+ queryClient.invalidateQueries({ queryKey: ['health'] })
+ queryClient.invalidateQueries({ queryKey: ['fallback'] })
+ },
+ })
+
+ const selectedKeys: ImportKey[] = rows
+ .filter(row => row.selected && row.platform && row.keyValue.trim())
+ .map(row => ({
+ keyName: row.keyName,
+ keyValue: row.keyValue,
+ platform: row.platform,
+ }))
+
+ function updateRow(index: number, patch: Partial<ImportRow>) {
+ setRows(prev => prev.map((row, i) => (i === index ? { ...row, ...patch } : row)))
+ }
+
+ function chooseFiles(e: React.ChangeEvent<HTMLInputElement>) {
+ const nextFiles = Array.from(e.target.files ?? [])
+ setFiles(nextFiles)
+ setRows([])
+ setSkipped([])
+ setResult(null)
+ preview.reset()
+ importSelected.reset()
+ }
+
+ return (
+ <section>
+ <div className="mb-3 flex flex-wrap items-center justify-between gap-3">
+ <div>
+ <h2 className="text-sm font-medium">{t('keys.importKeys')}</h2>
+ <p className="text-xs text-muted-foreground mt-0.5">{t('keys.importKeysDescription')}</p>
+ </div>
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={() => preview.mutate(files)}
+ disabled={files.length === 0 || preview.isPending}
+ >
+ <Upload className="size-3.5" />
+ {preview.isPending ? t('keys.previewing') : t('keys.previewFiles')}
+ </Button>
+ </div>
+
+ <div className="rounded-3xl border bg-card p-4">
+ <div className="flex flex-wrap items-end gap-3">
+ <div className="min-w-[260px] flex-1 space-y-1.5">
+ <Label className="text-xs">{t('keys.importFiles')}</Label>
+ <Input
+ type="file"
+ multiple
+ accept=".env,.json,.jsonc,.md,.txt"
+ onChange={chooseFiles}
+ className="cursor-pointer text-xs file:mr-2"
+ />
+ </div>
+ {files.length > 0 && (
+ <span className="pb-1 text-xs text-muted-foreground">
+ {t('keys.importFileCount', { count: files.length })}
+ </span>
+ )}
+ </div>
+
+ {preview.isError && (
+ <p className="mt-3 text-xs text-destructive">{(preview.error as Error).message}</p>
+ )}
+
+ {rows.length > 0 && (
+ <div className="mt-4 overflow-hidden rounded-2xl border">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-10">{t('keys.selected')}</TableHead>
+ <TableHead>{t('keys.provider')}</TableHead>
+ <TableHead>{t('keys.keyName')}</TableHead>
+ <TableHead>{t('keys.keyValue')}</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {rows.map((row, index) => (
+ <TableRow key={`${row.keyName}:${index}`}>
+ <TableCell>
+ <input
+ type="checkbox"
+ checked={row.selected}
+ onChange={() => updateRow(index, { selected: !row.selected })}
+ className="size-4 accent-primary"
+ />
+ </TableCell>
+ <TableCell>
+ <Select
+ value={row.platform}
+ onValueChange={(value) => updateRow(index, { platform: value as Platform, selected: true })}
+ >
+ <SelectTrigger className="w-[190px]">
+ <SelectValue placeholder={t('keys.chooseProvider')} />
+ </SelectTrigger>
+ <SelectContent>
+ {importablePlatforms.map(p => (
+ <SelectItem key={p.value} value={p.value}>{p.label}</SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </TableCell>
+ <TableCell>
+ <Input
+ value={row.keyName}
+ onChange={e => updateRow(index, { keyName: e.target.value })}
+ className="w-[220px] font-mono text-xs"
+ />
+ </TableCell>
+ <TableCell>
+ <div className="flex min-w-[280px] items-center gap-2">
+ <Input
+ type={row.visible ? 'text' : 'password'}
+ value={row.keyValue}
+ onChange={e => updateRow(index, { keyValue: e.target.value })}
+ className="font-mono text-xs"
+ />
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ onClick={() => updateRow(index, { visible: !row.visible })}
+ >
+ {row.visible ? t('common.hide') : t('common.show')}
+ </Button>
+ </div>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ )}
+
+ {rows.length === 0 && preview.isSuccess && (
+ <p className="mt-3 text-xs text-muted-foreground">{t('keys.noPreviewKeys')}</p>
+ )}
+
+ {skipped.length > 0 && (
+ <div className="mt-3 text-xs text-muted-foreground">
+ <span className="font-medium text-foreground">{t('keys.skippedItems')}</span>
+ <span> {skipped.slice(0, 5).join(', ')}</span>
+ {skipped.length > 5 && <span> {t('keys.moreItems', { count: skipped.length - 5 })}</span>}
+ </div>
+ )}
+
+ {rows.length > 0 && (
+ <div className="mt-4 flex flex-wrap items-center gap-3">
+ <Button
+ type="button"
+ size="sm"
+ onClick={() => importSelected.mutate(selectedKeys)}
+ disabled={selectedKeys.length === 0 || importSelected.isPending}
+ >
+ {importSelected.isPending
+ ? t('keys.importing')
+ : t('keys.importSelected', { count: selectedKeys.length })}
+ </Button>
+ {selectedKeys.length === 0 && (
+ <span className="text-xs text-muted-foreground">{t('keys.noImportSelection')}</span>
+ )}
+ </div>
+ )}
+
+ {importSelected.isError && (
+ <p className="mt-3 text-xs text-destructive">{(importSelected.error as Error).message}</p>
+ )}
+ {result && (
+ <p className="mt-3 text-xs text-muted-foreground">
+ {t('keys.importResult', { imported: result.imported, failed: result.errors.length })}
+ </p>
+ )}
+ </div>
+ </section>
+ )
+}
+
// Split a free-text model field on commas / newlines into a clean id list,
// dropping blanks and duplicates so one endpoint can take several models. (#281)
function parseModelList(raw: string): string[] {
@@ -838,6 +1072,8 @@ export default function KeysPage() {
<>
<QuotaSignalsSection states={(healthData?.quotaStates ?? []).slice(0, 24)} />
+ <ImportKeysSection />
+
<section>
<h2 className="text-sm font-medium mb-3">{t('keys.addProvider')}</h2>
<form onSubmit={handleSubmit} className="flex flex-wrap gap-3 rounded-3xl border p-4 bg-card">
diff --git a/package-lock.json b/package-lock.json
index 665ef193..0f50e064 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -3493,6 +3493,16 @@
"integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
"license": "MIT"
},
+ "node_modules/@types/multer": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/@types/multer/-/multer-2.1.0.tgz",
+ "integrity": "sha512-zYZb0+nJhOHtPpGDb3vqPjwpdeGlGC157VpkqNQL+UU2qwoacoQ7MpsAmUptI/0Oa127X32JzWDqQVEXp2RcIA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/express": "*"
+ }
+ },
"node_modules/@types/node": {
"version": "24.12.4",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.4.tgz",
@@ -4138,6 +4148,12 @@
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
+ "node_modules/append-field": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
+ "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",
+ "license": "MIT"
+ },
"node_modules/argparse": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
@@ -4357,7 +4373,6 @@
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
- "dev": true,
"license": "MIT"
},
"node_modules/bundle-name": {
@@ -4375,6 +4390,17 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/busboy": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
+ "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
+ "dependencies": {
+ "streamsearch": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=10.16.0"
+ }
+ },
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
@@ -4686,6 +4712,21 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/concat-stream": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
+ "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",
+ "engines": [
+ "node >= 6.0"
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "buffer-from": "^1.0.0",
+ "inherits": "^2.0.3",
+ "readable-stream": "^3.0.2",
+ "typedarray": "^0.0.6"
+ }
+ },
"node_modules/concurrently": {
"version": "9.2.1",
"resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.1.tgz",
@@ -8994,6 +9035,68 @@
"integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==",
"license": "MIT"
},
+ "node_modules/multer": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/multer/-/multer-2.2.0.tgz",
+ "integrity": "sha512-6rdyFg2kLrMh9Jee7/BMPuV9lEAd7lLW2YUpF9/YxR7njyoUwwQ0ZPh3TaIY50Sw6vlyD2HW3wGOkTS4P79xrQ==",
+ "license": "MIT",
+ "dependencies": {
+ "append-field": "^1.0.0",
+ "busboy": "^1.6.0",
+ "concat-stream": "^2.0.0",
+ "type-is": "^1.6.18"
+ },
+ "engines": {
+ "node": ">= 10.16.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/multer/node_modules/media-typer": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
+ "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/multer/node_modules/mime-db": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/multer/node_modules/mime-types": {
+ "version": "2.1.35",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": "1.52.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/multer/node_modules/type-is": {
+ "version": "1.6.18",
+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
+ "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
+ "license": "MIT",
+ "dependencies": {
+ "media-typer": "0.3.0",
+ "mime-types": "~2.1.24"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"node_modules/mute-stream": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-3.0.0.tgz",
@@ -10714,6 +10817,14 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/streamsearch": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
+ "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
"node_modules/strict-event-emitter": {
"version": "0.5.1",
"resolved": "https://registry.npmjs.org/strict-event-emitter/-/strict-event-emitter-0.5.1.tgz",
@@ -11232,6 +11343,12 @@
"url": "https://opencollective.com/express"
}
},
+ "node_modules/typedarray": {
+ "version": "0.0.6",
+ "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
+ "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
+ "license": "MIT"
+ },
"node_modules/typescript": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
@@ -13067,6 +13184,7 @@
"drizzle-orm": "^0.44.2",
"express": "^5.1.0",
"helmet": "^8.1.0",
+ "multer": "^2.2.0",
"socks-proxy-agent": "^10.0.0",
"undici": "^6.21.0",
"zod": "^3.24.4"
@@ -13075,6 +13193,7 @@
"@types/better-sqlite3": "^7.6.13",
"@types/cors": "^2.8.17",
"@types/express": "^5.0.2",
+ "@types/multer": "^2.1.0",
"@types/node": "^22.15.3",
"drizzle-kit": "^0.31.1",
"tsx": "^4.19.4",
diff --git a/server/package.json b/server/package.json
index 4cb7a9e1..59f65807 100644
--- a/server/package.json
+++ b/server/package.json
@@ -25,6 +25,7 @@
"drizzle-orm": "^0.44.2",
"express": "^5.1.0",
"helmet": "^8.1.0",
+ "multer": "^2.2.0",
"socks-proxy-agent": "^10.0.0",
"undici": "^6.21.0",
"zod": "^3.24.4"
@@ -33,6 +34,7 @@
"@types/better-sqlite3": "^7.6.13",
"@types/cors": "^2.8.17",
"@types/express": "^5.0.2",
+ "@types/multer": "^2.1.0",
"@types/node": "^22.15.3",
"drizzle-kit": "^0.31.1",
"tsx": "^4.19.4",
diff --git a/server/src/__tests__/lib/key-parser.test.ts b/server/src/__tests__/lib/key-parser.test.ts
new file mode 100644
index 00000000..c00c85a6
--- /dev/null
+++ b/server/src/__tests__/lib/key-parser.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from 'vitest';
+import {
+ AUTH_JSON_PROVIDER_MAP,
+ detectPlatform,
+ looksLikeApiKey,
+ parseAuthJson,
+ parseDotEnv,
+ parseJson,
+ parseKeysFromFile,
+ stripJsoncComments,
+ stripTrailingCommas,
+} from '../../lib/key-parser.js';
+
+describe('key parser', () => {
+ it('parses dotenv key/value files', () => {
+ expect(parseDotEnv('GOOGLE_API_KEY="ai-test"\nGROQ_API_KEY=gsk-test # comment')).toEqual([
+ { key: 'GOOGLE_API_KEY', value: 'ai-test' },
+ { key: 'GROQ_API_KEY', value: 'gsk-test' },
+ ]);
+ });
+
+ it('parses flat JSON string values', () => {
+ expect(parseJson(JSON.stringify({ MISTRAL_API_KEY: 'mist-test', PORT: 3001 }))).toEqual([
+ { key: 'MISTRAL_API_KEY', value: 'mist-test' },
+ ]);
+ });
+
+ it('strips JSONC comments and trailing commas', () => {
+ const jsonc = '{\n // comment\n "GROQ_API_KEY": "gsk-test",\n}';
+ expect(JSON.parse(stripTrailingCommas(stripJsoncComments(jsonc)))).toEqual({
+ GROQ_API_KEY: 'gsk-test',
+ });
+ });
+
+ it('detects current provider prefixes', () => {
+ expect(detectPlatform('GOOGLE_')).toBe('google');
+ expect(detectPlatform('OLLAMA_CLOUD_')).toBe('ollama');
+ expect(detectPlatform('SAMBANOVA_')).toBeNull();
+ });
+
+ it('parses Hermes/OpenCode auth.json provider names', () => {
+ expect(AUTH_JSON_PROVIDER_MAP['ollama-cloud']).toBe('ollama');
+ const result = parseAuthJson(JSON.stringify({
+ credential_pool: {
+ gemini: [{ id: '1', label: 'Gemini', auth_type: 'api_key', access_token: 'AIza-test' }],
+ github: [{ id: '2', label: 'GitHub', auth_type: 'oauth', access_token: 'gho-test' }],
+ },
+ }));
+ expect(result.keys).toEqual([
+ { rawKey: 'Gemini=AIza-test', prefix: 'GOOGLE_', platform: 'google' },
+ ]);
+ expect(result.skipped[0]).toContain('auth_type is oauth');
+ });
+
+ it('keeps unknown but key-like values for preview', () => {
+ const result = parseKeysFromFile('ANTHROPIC_API_KEY=sk-ant-test-value\nPORT=3001', 'keys.env');
+ expect(result.keys).toEqual([
+ { rawKey: 'ANTHROPIC_API_KEY=sk-ant-test-value', prefix: 'ANTHROPIC_', platform: null },
+ ]);
+ expect(result.skipped).toEqual(['PORT: value does not look like an API key']);
+ });
+
+ it('filters obvious non-key values', () => {
+ expect(looksLikeApiKey('true')).toBe(false);
+ expect(looksLikeApiKey('https://example.com')).toBe(false);
+ expect(looksLikeApiKey('sk-valid-token')).toBe(true);
+ });
+});
diff --git a/server/src/__tests__/routes/keys.test.ts b/server/src/__tests__/routes/keys.test.ts
index db8caeed..c9d5aa1a 100644
--- a/server/src/__tests__/routes/keys.test.ts
+++ b/server/src/__tests__/routes/keys.test.ts
@@ -25,6 +25,37 @@ async function request(app: Express, method: string, path: string, body?: any) {
return { status: res.status, body: data };
}
+async function multipartRequest(
+ app: Express,
+ path: string,
+ field: 'file' | 'files',
+ files: Array<{ filename: string; content: string; type?: string }>,
+) {
+ const server = app.listen(0);
+ const addr = server.address() as any;
+ const url = `http://127.0.0.1:${addr.port}${path}`;
+ const form = new FormData();
+ for (const file of files) {
+ form.append(
+ field,
+ new Blob([file.content], { type: file.type ?? 'text/plain' }),
+ file.filename,
+ );
+ }
+
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: {
+ ...(isGatedApiPath(path) ? { Authorization: `Bearer ${dashToken}` } : {}),
+ },
+ body: form,
+ });
+
+ const data = await res.json().catch(() => null);
+ server.close();
+ return { status: res.status, body: data };
+}
+
describe('Keys API', () => {
let app: Express;
@@ -177,4 +208,64 @@ describe('Keys API', () => {
const { status } = await request(app, 'PATCH', '/api/keys/99999', { label: 'test' });
expect(status).toBe(404);
});
+
+ describe('key import', () => {
+ it('previews keys from multiple supported files', async () => {
+ const { status, body } = await multipartRequest(app, '/api/keys/preview', 'files', [
+ { filename: 'keys.env', content: 'GROQ_API_KEY=gsk_test123\nANTHROPIC_API_KEY=sk-ant-test' },
+ { filename: 'more.jsonc', content: '{ // comment\n "MISTRAL_API_KEY": "mist_test456",\n}' },
+ ]);
+
+ 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_' },
+ ]);
+ expect(body.total).toBe(3);
+ });
+
+ it('imports selected preview rows', async () => {
+ const { status, body } = await request(app, 'POST', '/api/keys/import-selected', {
+ keys: [
+ { keyName: 'GROQ_API_KEY', keyValue: 'gsk_test123', platform: 'groq' },
+ { keyName: 'MISTRAL_API_KEY', keyValue: 'mist_test456', platform: 'mistral' },
+ ],
+ });
+
+ expect(status).toBe(200);
+ expect(body).toMatchObject({ imported: 2, skipped: [], errors: [], total: 2 });
+
+ const { body: keys } = await request(app, 'GET', '/api/keys');
+ expect(keys.map((key: any) => key.platform).sort()).toEqual(['groq', 'mistral']);
+ });
+
+ it('auto-imports recognized keys from one file and skips unknown providers', async () => {
+ const { status, body } = await multipartRequest(app, '/api/keys/import', 'file', [
+ { filename: 'keys.env', content: 'GROQ_API_KEY=gsk_test123\nANTHROPIC_API_KEY=sk-ant-test' },
+ ]);
+
+ expect(status).toBe(200);
+ expect(body.imported).toBe(1);
+ expect(body.skipped).toContain('ANTHROPIC_API_KEY');
+
+ const { body: keys } = await request(app, 'GET', '/api/keys');
+ expect(keys).toHaveLength(1);
+ expect(keys[0].platform).toBe('groq');
+ });
+
+ it('rejects unsupported files and malformed JSON uploads', async () => {
+ const unsupported = await multipartRequest(app, '/api/keys/preview', 'files', [
+ { filename: 'keys.js', content: 'module.exports = {}' },
+ ]);
+ expect(unsupported.status).toBe(400);
+ expect(unsupported.body.error.message).toBe('Unsupported file type');
+
+ const malformed = await multipartRequest(app, '/api/keys/import', 'file', [
+ { filename: 'keys.json', content: '{bad json' },
+ ]);
+ expect(malformed.status).toBe(400);
+ expect(malformed.body.error.message).toBe('Invalid JSON format');
+ });
+ });
});
diff --git a/server/src/lib/key-parser.ts b/server/src/lib/key-parser.ts
new file mode 100644
index 00000000..111b3b95
--- /dev/null
+++ b/server/src/lib/key-parser.ts
@@ -0,0 +1,317 @@
+export interface ParsedKey {
+ rawKey: string;
+ prefix: string;
+ platform: string | null;
+}
+
+export interface ParseResult {
+ keys: ParsedKey[];
+ skipped: string[];
+}
+
+export const PREFIX_MAP: Record<string, string> = {
+ GOOGLE_: 'google',
+ GEMINI_: 'google',
+ GROQ_: 'groq',
+ CEREBRAS_: 'cerebras',
+ NVIDIA_: 'nvidia',
+ MISTRAL_: 'mistral',
+ OPENROUTER_: 'openrouter',
+ GITHUB_: 'github',
+ COHERE_: 'cohere',
+ CLOUDFLARE_: 'cloudflare',
+ ZHIPU_: 'zhipu',
+ OLLAMA_: 'ollama',
+ OLLAMA_CLOUD_: 'ollama',
+ HF_: 'huggingface',
+ HUGGINGFACE_: 'huggingface',
+ OPENCODE_: 'opencode',
+ AGNES_: 'agnes',
+ REKA_: 'reka',
+ SILICONFLOW_: 'siliconflow',
+ ROUTEWAY_: 'routeway',
+ BAZAARLINK_: 'bazaarlink',
+ AINATIVE_: 'ainative',
+ AIHORDE_: 'aihorde',
+};
+
+export const AUTH_JSON_PROVIDER_MAP: Record<string, string> = {
+ gemini: 'google',
+ google: 'google',
+ groq: 'groq',
+ openrouter: 'openrouter',
+ 'ollama-cloud': 'ollama',
+ ollama: 'ollama',
+ nvidia: 'nvidia',
+ 'opencode-zen': 'opencode',
+ opencode: 'opencode',
+};
+
+export function detectPlatform(prefix: string): string | null {
+ return PREFIX_MAP[prefix] ?? null;
+}
+
+export function parseDotEnv(content: string): Array<{ key: string; value: string }> {
+ let text = content;
+ if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
+ text = text.replace(/\r\n/g, '\n');
+
+ const result = new Map<string, string>();
+ for (let line of text.split('\n')) {
+ line = line.trim();
+ if (!line || line.startsWith('#')) continue;
+
+ const eqIndex = line.indexOf('=');
+ if (eqIndex === -1) continue;
+
+ const key = line.slice(0, eqIndex).trim();
+ let value = line.slice(eqIndex + 1).trimStart();
+ const doubleQuoted = value.startsWith('"') && value.endsWith('"');
+ const singleQuoted = value.startsWith("'") && value.endsWith("'");
+
+ if (doubleQuoted || singleQuoted) {
+ value = value.slice(1, -1);
+ } else {
+ const commentIndex = value.indexOf(' #');
+ if (commentIndex !== -1) value = value.slice(0, commentIndex);
+ value = value.trimEnd();
+ }
+
+ result.set(key, value);
+ }
+
+ return Array.from(result.entries()).map(([key, value]) => ({ key, value }));
+}
+
+export function stripJsoncComments(text: string): string {
+ const out: string[] = [];
+ let i = 0;
+
+ while (i < text.length) {
+ if (text[i] === '"') {
+ out.push('"');
+ i++;
+ while (i < text.length) {
+ out.push(text[i]);
+ if (text[i] === '\\') {
+ i++;
+ if (i < text.length) {
+ out.push(text[i]);
+ i++;
+ }
+ } else if (text[i] === '"') {
+ i++;
+ break;
+ } else {
+ i++;
+ }
+ }
+ continue;
+ }
+
+ if (text[i] === '/' && text[i + 1] === '/') {
+ i += 2;
+ while (i < text.length && text[i] !== '\n') i++;
+ continue;
+ }
+
+ if (text[i] === '/' && text[i + 1] === '*') {
+ i += 2;
+ while (i + 1 < text.length && !(text[i] === '*' && text[i + 1] === '/')) i++;
+ i += 2;
+ continue;
+ }
+
+ out.push(text[i]);
+ i++;
+ }
+
+ return out.join('');
+}
+
+export function stripTrailingCommas(text: string): string {
+ const out: string[] = [];
+ let i = 0;
+
+ while (i < text.length) {
+ if (text[i] === '"') {
+ out.push('"');
+ i++;
+ while (i < text.length) {
+ out.push(text[i]);
+ if (text[i] === '\\') {
+ i++;
+ if (i < text.length) {
+ out.push(text[i]);
+ i++;
+ }
+ } else if (text[i] === '"') {
+ i++;
+ break;
+ } else {
+ i++;
+ }
+ }
+ continue;
+ }
+
+ if (text[i] === ',') {
+ let j = i + 1;
+ while (j < text.length && /\s/.test(text[j]!)) j++;
+ if (text[j] === '}' || text[j] === ']') {
+ i++;
+ continue;
+ }
+ }
+
+ out.push(text[i]);
+ i++;
+ }
+
+ return out.join('');
+}
+
+export function parseJson(content: string): Array<{ key: string; value: string }> {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(content);
+ } catch {
+ return [];
+ }
+
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
+ return [];
+ }
+
+ return Object.entries(parsed)
+ .filter((entry): entry is [string, string] => typeof entry[1] === 'string')
+ .map(([key, value]) => ({ key, value }));
+}
+
+export function parseAuthJson(content: string): ParseResult {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(content);
+ } catch {
+ return { keys: [], skipped: [] };
+ }
+
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
+ return { keys: [], skipped: [] };
+ }
+
+ const pool = (parsed as Record<string, unknown>).credential_pool;
+ if (typeof pool !== 'object' || pool === null || Array.isArray(pool)) {
+ return { keys: [], skipped: [] };
+ }
+
+ const keys: ParsedKey[] = [];
+ const skipped: string[] = [];
+
+ for (const [providerName, credentials] of Object.entries(pool)) {
+ if (!Array.isArray(credentials)) {
+ skipped.push(`${providerName}: not an array`);
+ continue;
+ }
+
+ for (const credential of credentials) {
+ if (typeof credential !== 'object' || credential === null) continue;
+ const row = credential as Record<string, unknown>;
+ const label = typeof row.label === 'string'
+ ? row.label
+ : typeof row.id === 'string'
+ ? row.id
+ : providerName;
+
+ if ('auth_type' in row && row.auth_type !== 'api_key') {
+ skipped.push(`${providerName}/${label}: auth_type is ${String(row.auth_type)}`);
+ continue;
+ }
+ if (typeof row.access_token !== 'string' || row.access_token.trim() === '') {
+ skipped.push(`${providerName}/${label}: no access_token`);
+ continue;
+ }
+
+ const platform = AUTH_JSON_PROVIDER_MAP[providerName] ?? null;
+ if (!platform) {
+ skipped.push(`${providerName}/${label}: no platform mapping`);
+ continue;
+ }
+
+ const prefix = Object.entries(PREFIX_MAP).find(([, value]) => value === platform)?.[0] ?? `${platform.toUpperCase()}_`;
+ keys.push({ rawKey: `${label}=${row.access_token}`, prefix, platform });
+ }
+ }
+
+ return { keys, skipped };
+}
+
+function extractPrefix(key: string): string {
+ const upper = key.toUpperCase();
+ const direct = Object.keys(PREFIX_MAP)
+ .sort((a, b) => b.length - a.length)
+ .find(prefix => upper.startsWith(prefix));
+ if (direct) return direct;
+
+ const firstUnderscore = upper.indexOf('_');
+ if (firstUnderscore === -1) return '';
+ const candidate = upper.slice(0, firstUnderscore + 1);
+ const rest = upper.slice(firstUnderscore + 1);
+ return rest.includes('_') ? candidate : '';
+}
+
+export function looksLikeApiKey(value: string): boolean {
+ if (value.length < 8) return false;
+ const lower = value.toLowerCase();
+ if (['true', 'false', 'yes', 'no'].includes(lower)) return false;
+ if (/^-?\d+(\.\d+)?$/.test(value)) return false;
+ if (/^https?:\/\//i.test(value)) return false;
+ if (value.includes('/')) return false;
+ return /[a-z]/i.test(value);
+}
+
+function toParsedKeys(pairs: Array<{ key: string; value: string }>): ParseResult {
+ const keys: ParsedKey[] = [];
+ const skipped: string[] = [];
+
+ for (const { key, value } of pairs) {
+ const prefix = extractPrefix(key);
+ const platform = detectPlatform(prefix);
+
+ if (platform) {
+ keys.push({ rawKey: `${key}=${value}`, prefix, platform });
+ continue;
+ }
+
+ if (looksLikeApiKey(value)) {
+ keys.push({ rawKey: `${key}=${value}`, prefix, platform: null });
+ } else {
+ skipped.push(`${key}: value does not look like an API key`);
+ }
+ }
+
+ return { keys, skipped };
+}
+
+export function parseKeysFromFile(content: string, filename: string): ParseResult {
+ let text = content;
+ if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
+ text = text.replace(/\r\n/g, '\n');
+
+ const ext = filename.includes('.') ? filename.slice(filename.lastIndexOf('.')).toLowerCase() : '';
+ if (ext === '.json' || ext === '.jsonc') {
+ const clean = stripTrailingCommas(stripJsoncComments(text));
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(clean);
+ } catch {
+ return toParsedKeys(parseDotEnv(text));
+ }
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) && 'credential_pool' in parsed) {
+ return parseAuthJson(clean);
+ }
+ return toParsedKeys(parseJson(clean));
+ }
+
+ return toParsedKeys(parseDotEnv(text));
+}
diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.ts
index d373e662..8fd76956 100644
--- a/server/src/routes/keys.ts
+++ b/server/src/routes/keys.ts
@@ -1,9 +1,12 @@
import { Router } from 'express';
-import type { Request, Response } from 'express';
+import type { NextFunction, Request, Response } from 'express';
import { z } from 'zod';
+import multer from 'multer';
+import path from 'path';
import { getDb } from '../db/index.js';
import { resolveProvider } from '../providers/index.js';
import { encrypt, decrypt, maskKey } from '../lib/crypto.js';
+import { parseKeysFromFile, stripJsoncComments, stripTrailingCommas } from '../lib/key-parser.js';
export const keysRouter = Router();
@@ -18,6 +21,21 @@ const PLATFORMS = [
'routeway', 'bazaarlink', 'ainative', 'aihorde', 'custom',
] as const;
+const ALLOWED_IMPORT_EXTENSIONS = new Set(['.env', '.json', '.jsonc', '.md', '.txt']);
+
+const upload = multer({
+ storage: multer.memoryStorage(),
+ limits: { fileSize: 5 * 1024 * 1024, files: 10 },
+ fileFilter: (_req, file, cb) => {
+ const ext = path.extname(file.originalname).toLowerCase();
+ if (!ALLOWED_IMPORT_EXTENSIONS.has(ext)) {
+ cb(new Error('Unsupported file type'));
+ return;
+ }
+ cb(null, true);
+ },
+});
+
// `key` is optional so keyless providers (Kilo's anonymous gateway) can be added
// without one; the handler enforces a non-empty key for everyone else.
const addKeySchema = z.object({
@@ -33,6 +51,71 @@ const updateKeySchema = z.object({
message: 'At least one of enabled or label must be provided',
});
+const importKeySchema = z.object({
+ keyName: z.string().optional(),
+ keyValue: z.string().min(1),
+ platform: z.enum(PLATFORMS),
+});
+
+function handleUploadError(err: any, res: Response, next: NextFunction): boolean {
+ if (!err) return false;
+ if (err.code === 'LIMIT_FILE_SIZE') {
+ res.status(413).json({ error: { message: 'File too large. Maximum size is 5MB' } });
+ return true;
+ }
+ if (err.code === 'LIMIT_FILE_COUNT') {
+ res.status(413).json({ error: { message: 'Too many files. Maximum is 10' } });
+ return true;
+ }
+ if (err.message?.includes('Unsupported file type')) {
+ res.status(400).json({ error: { message: 'Unsupported file type' } });
+ return true;
+ }
+ next(err);
+ return true;
+}
+
+function parseUpload(file: Express.Multer.File) {
+ const content = file.buffer.toString('utf8');
+ if (!content.trim()) {
+ throw Object.assign(new Error('File contains no data'), { status: 400 });
+ }
+
+ if (/\.jsonc?$/i.test(file.originalname)) {
+ try {
+ JSON.parse(stripTrailingCommas(stripJsoncComments(content)));
+ } catch {
+ throw Object.assign(new Error('Invalid JSON format'), { status: 400 });
+ }
+ }
+
+ return parseKeysFromFile(content, file.originalname);
+}
+
+function splitRawKey(rawKey: string) {
+ const eqIndex = rawKey.indexOf('=');
+ return {
+ keyName: eqIndex === -1 ? rawKey : rawKey.slice(0, eqIndex),
+ keyValue: eqIndex === -1 ? '' : rawKey.slice(eqIndex + 1),
+ };
+}
+
+function insertImportedKey(platform: (typeof PLATFORMS)[number], keyName: string, keyValue: string) {
+ if (platform === 'custom') {
+ throw new Error('Custom providers must be added with a base URL');
+ }
+ if (!resolveProvider(platform)) {
+ throw new Error(`Unsupported platform: ${platform}`);
+ }
+
+ const db = getDb();
+ const { encrypted, iv, authTag } = encrypt(keyValue.trim());
+ db.prepare(`
+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)
+ VALUES (?, ?, ?, ?, ?, 'unknown', 1)
+ `).run(platform, keyName, encrypted, iv, authTag);
+}
+
// List all keys (masked)
keysRouter.get('/', (_req: Request, res: Response) => {
const db = getDb();
@@ -303,6 +386,125 @@ keysRouter.post('/custom', (req: Request, res: Response) => {
});
});
+keysRouter.post('/import', (req: Request, res: Response, next: NextFunction) => {
+ upload.single('file')(req, res, (err: any) => {
+ if (handleUploadError(err, res, next)) return;
+
+ try {
+ if (!req.file) {
+ res.status(400).json({ error: { message: 'No file uploaded' } });
+ return;
+ }
+
+ const result = parseUpload(req.file);
+ const imported: Array<{ keyName: string; platform: string }> = [];
+ const skipped = [...result.skipped];
+ const errors: Array<{ key: string; error: string }> = [];
+
+ for (const parsedKey of result.keys) {
+ const { keyName, keyValue } = splitRawKey(parsedKey.rawKey);
+ if (!parsedKey.platform) {
+ skipped.push(keyName);
+ continue;
+ }
+ const platformParse = z.enum(PLATFORMS).safeParse(parsedKey.platform);
+ if (!platformParse.success || platformParse.data === 'custom') {
+ skipped.push(keyName);
+ continue;
+ }
+ if (!keyValue.trim()) {
+ errors.push({ key: keyName, error: 'keyValue must be at least 1 character' });
+ continue;
+ }
+
+ try {
+ insertImportedKey(platformParse.data, keyName, keyValue);
+ imported.push({ keyName, platform: platformParse.data });
+ } catch (insertErr) {
+ errors.push({ key: keyName, error: (insertErr as Error).message });
+ }
+ }
+
+ res.json({
+ imported: imported.length,
+ skipped,
+ errors,
+ total: result.keys.length + result.skipped.length,
+ });
+ } catch (handlerErr: any) {
+ res.status(handlerErr.status ?? 500).json({ error: { message: handlerErr.message } });
+ }
+ });
+});
+
+keysRouter.post('/preview', (req: Request, res: Response, next: NextFunction) => {
+ upload.array('files', 10)(req, res, (err: any) => {
+ if (handleUploadError(err, res, next)) return;
+
+ try {
+ const files = req.files as Express.Multer.File[] | undefined;
+ if (!files || files.length === 0) {
+ res.status(400).json({ error: { message: 'No files uploaded' } });
+ return;
+ }
+
+ const keys: Array<{ keyName: string; keyValue: string; detectedPlatform: string | null; prefix: string }> = [];
+ const skipped: string[] = [];
+
+ for (const file of files) {
+ const result = parseUpload(file);
+ for (const parsedKey of result.keys) {
+ const { keyName, keyValue } = splitRawKey(parsedKey.rawKey);
+ keys.push({
+ keyName,
+ keyValue,
+ detectedPlatform: parsedKey.platform,
+ prefix: parsedKey.prefix,
+ });
+ }
+ skipped.push(...result.skipped);
+ }
+
+ res.json({ keys, total: keys.length, skipped });
+ } catch (handlerErr: any) {
+ res.status(handlerErr.status ?? 500).json({ error: { message: handlerErr.message } });
+ }
+ });
+});
+
+keysRouter.post('/import-selected', (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(', ') } });
+ return;
+ }
+
+ let imported = 0;
+ const errors: Array<{ key: string; error: string }> = [];
+
+ for (const key of parsed.data.keys) {
+ const keyName = key.keyName?.trim() || key.platform;
+ if (key.platform === 'custom') {
+ errors.push({ key: keyName, error: 'Custom providers must be added with a base URL' });
+ continue;
+ }
+
+ try {
+ insertImportedKey(key.platform, keyName, key.keyValue);
+ imported++;
+ } catch (err) {
+ errors.push({ key: keyName, error: (err as Error).message });
+ }
+ }
+
+ res.json({
+ imported,
+ skipped: [],
+ errors,
+ total: parsed.data.keys.length,
+ });
+});
+
// Delete a key
keysRouter.delete('/:id', (req: Request, res: Response) => {
const id = parseInt(req.params.id as string, 10);
diff --git a/shared/types.ts b/shared/types.ts
index 122b4d57..e80bd94b 100644
--- a/shared/types.ts
+++ b/shared/types.ts
@@ -1,5 +1,35 @@
// ---- Platform & Model Types ----
+export interface PreviewKey {
+ keyName: string;
+ keyValue: string;
+ detectedPlatform: string | null;
+ prefix: string;
+}
+
+export interface ImportKey {
+ keyName: string;
+ keyValue: string;
+ platform: string;
+}
+
+export interface PreviewResponse {
+ keys: PreviewKey[];
+ total: number;
+ skipped: string[];
+}
+
+export interface ImportSelectedRequest {
+ keys: ImportKey[];
+}
+
+export interface ImportSelectedResponse {
+ imported: number;
+ skipped: string[];
+ errors: Array<{ key: string; error: string }>;
+ total: number;
+}
+
// Active platforms — must match server/src/providers/index.ts and
// server/src/routes/keys.ts PLATFORMS allowlist.
// Moonshot and MiniMax direct integrations were dropped in migrateModelsV4