Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions frontend/src/i18n/locales/en/dashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
9 changes: 9 additions & 0 deletions frontend/src/i18n/locales/zh/dashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: '名称',
Expand Down
99 changes: 99 additions & 0 deletions frontend/src/utils/__tests__/magpieImport.spec.ts
Original file line number Diff line number Diff line change
@@ -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<typeof buildMagpieImportLink>[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<string, string>]> = [
['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' })
})
})
112 changes: 112 additions & 0 deletions frontend/src/utils/magpieImport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import type { ApiKey } from '@/types'

type ImportKey = Pick<ApiKey, 'id' | 'name' | 'key' | 'group_id' | 'group_ids' | 'group'>
type Endpoint = 'chat' | 'responses' | 'anthropic' | 'gemini'
type Endpoints = Partial<Record<Endpoint, string>>
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}` }
}
42 changes: 42 additions & 0 deletions frontend/src/views/user/KeysView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,17 @@
<Icon name="upload" size="sm" />
<span class="text-xs">{{ t('keys.importToCcSwitch') }}</span>
</button>
<button
type="button"
@click="importToMagpie(row)"
:disabled="publicSettingsLoading"
data-testid="magpie-import-button"
class="flex flex-col items-center gap-0.5 rounded-lg p-1.5 text-gray-500 transition-colors hover:bg-blue-50 hover:text-blue-600 disabled:opacity-50 dark:hover:bg-blue-900/20 dark:hover:text-blue-400"
:title="t('keys.magpieImport.preview')"
>
<Icon name="externalLink" size="sm" />
<span class="text-xs">{{ t('keys.importToMagpie') }}</span>
</button>
<!-- Toggle Status Button -->
<button
@click="toggleKeyStatus(row)"
Expand Down Expand Up @@ -1387,6 +1398,7 @@ import {
type CcSwitchClientType
} from '@/utils/ccswitchImport'
import { isCodexQuickConfigPlatform } from '@/utils/codexQuickConfig'
import { buildMagpieImportLink } from '@/utils/magpieImport'

// Helper to format date for datetime-local input
const formatDateTimeLocal = (isoDate: string): string => {
Expand Down Expand Up @@ -1677,6 +1689,7 @@ const selectedCodexQuickConfigPlatform = computed(() => {
const copiedKeyId = ref<number | null>(null)
const groupSelectorKeyId = ref<number | null>(null)
const publicSettings = ref<PublicSettings | null>(null)
const publicSettingsLoading = ref(true)
const dropdownRef = ref<HTMLElement | null>(null)
const columnDropdownRef = ref<HTMLElement | null>(null)
const dropdownPosition = ref<{ top?: number; bottom?: number; left: number } | null>(null)
Expand Down Expand Up @@ -1983,6 +1996,8 @@ const loadPublicSettings = async () => {
publicSettings.value = await authAPI.getPublicSettings()
} catch (error) {
console.error('Failed to load public settings:', error)
} finally {
publicSettingsLoading.value = false
}
}

Expand Down Expand Up @@ -2372,6 +2387,33 @@ const resetRateLimitUsage = async () => {
}
}

const importToMagpie = (row: ApiKey) => {
const settings = publicSettings.value
if (!settings) {
appStore.showError(t('keys.magpieImport.settingsUnavailable'))
return
}
const result = buildMagpieImportLink({
dashboardOrigin: window.location.origin,
baseUrl: settings.api_base_url,
siteName: settings.site_name,
row
})
if ('error' in result) {
appStore.showError(t(`keys.magpieImport.${result.error}`))
return
}

// Launch from the click itself. Browsers cannot confirm whether the app opened.
try {
window.open(result.url, '_self')
} catch {
appStore.showError(t('keys.magpieImport.openHelp'))
return
}
appStore.showInfo(t('keys.magpieImport.openHelp'), 6500)
}

const importToCcswitch = (row: ApiKey) => {
const platform = row.group?.platform || 'anthropic'

Expand Down
Loading
Loading