diff --git a/frontend/src/i18n/locales/en/dashboard.ts b/frontend/src/i18n/locales/en/dashboard.ts index fe3c43bd6a61..0539426f2406 100644 --- a/frontend/src/i18n/locales/en/dashboard.ts +++ b/frontend/src/i18n/locales/en/dashboard.ts @@ -129,6 +129,15 @@ export default { copyToClipboard: 'Copy to clipboard', copied: 'Copied!', importToCcSwitch: 'Import to CCS', + importToMagpie: 'Import to Magpie', + magpieImport: { + preview: 'Preview the provider in Magpie before saving', + openHelp: 'If Magpie did not open, make sure the desktop app is installed and allow your browser to open it.', + settingsUnavailable: 'Could not load the API address settings. Refresh the page and try again.', + unsupportedGroup: 'This key’s group can’t be imported automatically. Select Use Key to see available configurations.', + invalidBase: 'Use an HTTPS API address without credentials, a query, or a fragment. Local addresses may use HTTP.', + invalidKey: 'This key is empty or invalid and can’t be imported into Magpie.' + }, enable: 'Enable', disable: 'Disable', nameLabel: 'Name', diff --git a/frontend/src/i18n/locales/zh/dashboard.ts b/frontend/src/i18n/locales/zh/dashboard.ts index d521c9a16b50..21f39ce9c6c3 100644 --- a/frontend/src/i18n/locales/zh/dashboard.ts +++ b/frontend/src/i18n/locales/zh/dashboard.ts @@ -129,6 +129,15 @@ export default { copyToClipboard: '复制到剪贴板', copied: '已复制!', importToCcSwitch: '导入到 CCS', + importToMagpie: '导入到 Magpie', + magpieImport: { + preview: '在 Magpie 桌面端预览供应商配置,确认后才会保存', + openHelp: '如果 Magpie 没有打开,请确认桌面端已安装,并允许浏览器打开它。', + settingsUnavailable: '无法读取站点的 API 地址设置。请刷新页面后重试。', + unsupportedGroup: '此密钥的分组无法自动导入。请通过「使用密钥」查看可用配置。', + invalidBase: 'API 地址无效。请使用不含账号、查询参数或片段的 HTTPS 地址;本机或局域网可使用 HTTP。', + invalidKey: '此密钥为空或格式无效,无法导入到 Magpie。' + }, enable: '启用', disable: '禁用', nameLabel: '名称', diff --git a/frontend/src/utils/__tests__/magpieImport.spec.ts b/frontend/src/utils/__tests__/magpieImport.spec.ts new file mode 100644 index 000000000000..cbb6898dc3b4 --- /dev/null +++ b/frontend/src/utils/__tests__/magpieImport.spec.ts @@ -0,0 +1,99 @@ +import { describe, expect, it } from 'vitest' +import type { Group, GroupPlatform } from '@/types' +import { buildMagpieImportLink } from '../magpieImport' + +const endpointNames = ['chat', 'responses', 'anthropic', 'gemini'] +const dashboardOrigin = 'https://dashboard.example' + +function keyFor(platform: GroupPlatform, allowMessages = false) { + return { + id: 21, + name: '开发密钥', + key: 'sk-test-a+b&c=d%#', + group_id: 9, + group_ids: [9], + group: { id: 9, platform, allow_messages_dispatch: allowMessages } as Group + } +} + +function parse(input: Parameters[0]) { + const result = buildMagpieImportLink(input) + if (!('url' in result)) throw new Error(`No import link: ${result.error}`) + const url = new URL(result.url) + expect(url.protocol).toBe('magpie:') + expect(url.host).toBe('import') + return url.searchParams +} + +const root = 'https://api.example/relay' +const openai = { chat: `${root}/v1`, responses: `${root}/v1` } +const compatible = { ...openai, anthropic: root } +const cases: Array<[GroupPlatform, boolean, Record]> = [ + ['anthropic', false, { anthropic: root }], + ['openai', false, openai], + ['openai', true, compatible], + ['gemini', false, { gemini: `${root}/v1beta` }], + ['antigravity', false, { anthropic: `${root}/antigravity`, gemini: `${root}/antigravity/v1beta` }], + ['grok', false, compatible], + ['deepseek', false, compatible], + ['opencode_go', false, compatible], + ['command_code', false, compatible] +] + +describe('Magpie import link', () => { + it.each(cases)('sets endpoints for %s (Messages dispatch: %s)', (platform, allowMessages, expected) => { + const row = keyFor(platform, allowMessages) + const query = parse({ dashboardOrigin, baseUrl: `${root}/v1/`, siteName: '中转站', row }) + expect(Object.fromEntries([...query].filter(([k]) => endpointNames.includes(k)))).toEqual(expected) + expect(query.get('name')).toBe('开发密钥 · 中转站') + expect(query.get('key')).toBe(row.key) + expect(query.get('id')).toMatch(/^sub2api-[a-f0-9]{16}-21$/) + }) + + it('normalizes a dedicated Antigravity URL without adding its path twice', () => { + const query = parse({ dashboardOrigin, baseUrl: `${root}/antigravity/v1beta/`, row: keyFor('antigravity') }) + expect(query.get('anthropic')).toBe(`${root}/antigravity`) + expect(query.get('gemini')).toBe(`${root}/antigravity/v1beta`) + }) + + it('keeps provider IDs distinct by instance and row and stable across rename or rotation', () => { + const row = keyFor('openai') + const input = { dashboardOrigin, baseUrl: root, row } + const id = parse(input).get('id') + expect(parse({ ...input, row: { ...row, name: '新名字', key: 'sk-rotated' } }).get('id')).toBe(id) + expect(parse({ ...input, row: { ...row, id: 22 } }).get('id')).not.toBe(id) + expect(parse({ ...input, baseUrl: 'https://api.example/other' }).get('id')).not.toBe(id) + expect(parse({ ...input, dashboardOrigin: 'https://other.example' }).get('id')).not.toBe(id) + }) + + it('uses the dashboard origin when there is no configured API address', () => { + const query = parse({ dashboardOrigin, baseUrl: ' ', row: keyFor('openai') }) + expect(query.get('responses')).toBe(`${dashboardOrigin}/v1`) + }) + + it.each(['http://localhost:8484', 'http://127.0.0.1', 'http://192.168.1.50', 'http://relay.local', 'http://[::1]:8484', 'http://[fd12:3456::1]'])('allows local HTTP at %s', baseUrl => { + const query = parse({ dashboardOrigin, baseUrl, row: keyFor('anthropic') }) + expect(query.get('anthropic')).toBe(baseUrl) + }) + + it.each([ + 'http://api.example', 'http://10.example', 'http://172.32.0.1', 'http://[fe80::1]', + 'https://user:pass@api.example', 'https://a\tpi.example', `${root}?q=a`, `${root}?`, `${root}#section`, + '//api.example', 'https:///api.example', 'javascript:void(0)' + ])('rejects an invalid base at %s', baseUrl => { + expect(buildMagpieImportLink({ dashboardOrigin, baseUrl, row: keyFor('openai') })).toEqual({ error: 'invalidBase' }) + }) + + it.each([ + keyFor('typesafe'), keyFor('composite'), keyFor('unknown'), + { ...keyFor('openai'), group_id: null, group: undefined }, + { ...keyFor('openai'), group_ids: [9, 10] }, + { ...keyFor('anthropic'), group: { ...keyFor('anthropic').group, claude_code_only: true } } + ])('does not guess endpoints for an unsupported group', row => { + expect(buildMagpieImportLink({ dashboardOrigin, row })).toEqual({ error: 'unsupportedGroup' }) + }) + + it.each(['', ' \t', 'sk-test\nother', '密'.repeat(1400)])('rejects an empty, malformed or oversized key', key => { + expect(buildMagpieImportLink({ dashboardOrigin, row: { ...keyFor('openai'), key } })).toEqual({ error: 'invalidKey' }) + }) +}) diff --git a/frontend/src/utils/magpieImport.ts b/frontend/src/utils/magpieImport.ts new file mode 100644 index 000000000000..ed9eaed626e1 --- /dev/null +++ b/frontend/src/utils/magpieImport.ts @@ -0,0 +1,112 @@ +import type { ApiKey } from '@/types' + +type ImportKey = Pick +type Endpoint = 'chat' | 'responses' | 'anthropic' | 'gemini' +type Endpoints = Partial> +type ImportResult = + | { url: string } + | { error: 'unsupportedGroup' | 'invalidBase' | 'invalidKey' } + +function resolveEndpoints(row: ImportKey, root: string): Endpoints | undefined { + const group = row.group + // Multi-group and composite routing can choose a different platform per model. + if (!group || row.group_id == null || (row.group_ids?.length ?? 0) > 1 || group.claude_code_only) { + return + } + + const v1 = `${root}/v1` + const openai = { chat: v1, responses: v1 } + switch (group.platform) { + case 'anthropic': + return { anthropic: root } + case 'openai': + return group.allow_messages_dispatch ? { ...openai, anthropic: root } : openai + case 'gemini': + return { gemini: `${root}/v1beta` } + case 'antigravity': { + const dedicated = root.endsWith('/antigravity') ? root : `${root}/antigravity` + return { anthropic: dedicated, gemini: `${dedicated}/v1beta` } + } + // These platforms serve Messages without the OpenAI group dispatch switch. + case 'grok': + case 'kimi': + case 'zhipu': + case 'deepseek': + case 'minimax': + case 'opencode_go': + case 'command_code': + case 'cline': + case 'mistral': + case 'qwen': + return { ...openai, anthropic: root } + } +} + +// Match the desktop importer's HTTP exception for loopback and private hosts. +// URL.hostname has already normalized IP literals and lowercased any DNS name. +function isLocalHost(hostname: string): boolean { + if (hostname === 'localhost' || hostname.endsWith('.local') || hostname === '[::1]' || /^\[f[cd][0-9a-f]{2}:/.test(hostname)) { + return true + } + const mapped = /^\[::ffff:([0-9a-f]+):([0-9a-f]+)\]$/.exec(hostname) + if (!mapped && !/^\d+\.\d+\.\d+\.\d+$/.test(hostname)) return false + const firstWord = mapped ? parseInt(mapped[1], 16) : 0 + const [a, b] = mapped ? [firstWord >> 8, firstWord & 255] : hostname.split('.').map(Number) + return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) +} + +function normalizeRoot(baseUrl: string): string | undefined { + const value = baseUrl.trim() + // Check the raw separators too: URL.search/hash are empty for a lone ? or #. + if (!/^https?:\/\/[^/]/i.test(value) || /[?#\\\s]/.test(value)) return + + try { + const url = new URL(value) + if (!url.hostname || url.username || url.password || (url.protocol === 'http:' && !isLocalHost(url.hostname))) { + return + } + const path = url.pathname.replace(/\/+$/, '').replace(/\/v1(?:beta)?$/, '') + return `${url.origin}${path}` + } catch { + return + } +} + +function instanceId(dashboardOrigin: string, root: string): string { + // A synchronous fingerprint of public addresses keeps dispatch in the click + // event. Never derive the provider ID from the credential or display name. + let hash = 0xcbf29ce484222325n + for (const byte of new TextEncoder().encode(JSON.stringify([dashboardOrigin, root]))) { + hash = BigInt.asUintN(64, (hash ^ BigInt(byte)) * 0x100000001b3n) + } + return hash.toString(16).padStart(16, '0') +} + +export function buildMagpieImportLink(input: { + dashboardOrigin: string + baseUrl?: string + siteName?: string + row: ImportKey +}): ImportResult { + const { row, dashboardOrigin } = input + const root = normalizeRoot(input.baseUrl?.trim() || dashboardOrigin) + if (!root) return { error: 'invalidBase' } + + const endpoints = resolveEndpoints(row, root) + if (!endpoints) return { error: 'unsupportedGroup' } + + const key = row.key.trim() + if (!key || [...row.key].some(c => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127) || new TextEncoder().encode(key).length > 4096) { + return { error: 'invalidKey' } + } + + const site = input.siteName?.trim() || 'Sub2API' + const name = row.name.trim() ? `${row.name.trim()} · ${site}` : site + const query = new URLSearchParams({ + name, + id: `sub2api-${instanceId(dashboardOrigin, root)}-${row.id}`, + ...endpoints, + key + }) + return { url: `magpie://import?${query}` } +} diff --git a/frontend/src/views/user/KeysView.vue b/frontend/src/views/user/KeysView.vue index a82a44d53437..aca1abb58d7b 100644 --- a/frontend/src/views/user/KeysView.vue +++ b/frontend/src/views/user/KeysView.vue @@ -487,6 +487,17 @@ {{ t('keys.importToCcSwitch') }} +