Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(providers): 扩展自定义供应商路由与鉴权地基 (#525)
Chris Zhang32eee51fda41
diff --git a/apps/desktop/src/main/im/shared/__tests__/authCheck.test.ts b/apps/desktop/src/main/im/shared/__tests__/authCheck.test.tsindex 9ee7b8deda..2d76d73a48 100644--- a/apps/desktop/src/main/im/shared/__tests__/authCheck.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/authCheck.test.ts@@ -182,6 +182,19 @@ describe('checkImRouteAuth', () => {});});+ it('allows an explicitly connected no-auth proxy without API key material', async () => {+ const providerSnapshot = [+ provider({ id: 'local-proxy', strategy: 'none', connected: true }),+ ];++ await expect(+ checkImRouteAuth(row({ providerId: 'local-proxy' }), providerSnapshot, deps()),+ ).resolves.toEqual({+ ok: true,+ missing: null,+ });+ });+it('reports provider-key when an api-key provider is connected without key material', async () => {const providerSnapshot = [provider({ id: 'custom-anthropic', strategy: 'api-key-header', connected: true }),diff --git a/apps/desktop/src/main/im/shared/authCheck.ts b/apps/desktop/src/main/im/shared/authCheck.tsindex 0b89101867..a76852926d 100644--- a/apps/desktop/src/main/im/shared/authCheck.ts+++ b/apps/desktop/src/main/im/shared/authCheck.ts@@ -78,6 +78,11 @@ async function checkImRouteAuthWithResolution(? { ok: true, missing: null }: { ok: false, missing: 'provider-disconnected' };}+ if (routing?.authStrategy === 'none') {+ return resolution.provider.connected+ ? { ok: true, missing: null }+ : { ok: false, missing: 'provider-disconnected' };+ }if (routing?.authStrategy === 'api-key-header') {if (!resolution.provider.connected) return { ok: false, missing: 'provider-disconnected' };return hasCustomProviderAuth(resolution.provider, row.agentKind, deps)diff --git a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.tsindex 9c9a1ae955..350a5d0305 100644--- a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts@@ -104,6 +104,21 @@ describe('validateCustomProviderConfig (per-runtime)', () => {expect(validateCustomProviderConfig({ ...valid, runtimes: { codex: { baseUrl: 'ftp://x', models: [] } } }).ok,).toBe(false);+ expect(+ validateCustomProviderConfig({+ ...valid,+ runtimes: {+ codex: {+ baseUrl: 'https://user:secret@x/v1',+ models: [{ id: 'm', name: 'M' }],+ },+ },+ }),+ ).toEqual({+ ok: false,+ code: 'INVALID_PARAMS',+ message: "runtime 'codex' baseUrl must not contain embedded credentials",+ });expect(validateCustomProviderConfig({...valid,@@ -205,6 +220,42 @@ describe('custom-provider-store CRUD (per-runtime)', () => {expect((await getCustomProvider('openrouter'))?.runtimes.codex?.wireProtocol).toBe('openai-chat');});+ it('round-trips a validated exact inference request path', async () => {+ mountDb();+ await createCustomProvider({+ ...valid,+ runtimes: {+ codex: {+ ...valid.runtimes.codex!,+ requestPath: '/tenant/acme/v2/infer?stream=1',+ },+ },+ });+ expect((await getCustomProvider('openrouter'))?.runtimes.codex?.requestPath)+ .toBe('/tenant/acme/v2/infer?stream=1');+ });++ it.each([+ '//evil.example/infer',+ '/infer#fragment',+ '/infer\r\nx: y',+ '/my path',+ '/infer\tmode',+ '/infer\u0000mode',+ '/模型',+ 'responses',+ ])(+ 'rejects unsafe or non-path requestPath %s',+ (requestPath) => {+ expect(validateCustomProviderConfig({+ ...valid,+ runtimes: {+ codex: { ...valid.runtimes.codex!, requestPath },+ },+ }).ok).toBe(false);+ },+ );+it('rejects unsupported protocol/runtime combinations', () => {expect(validateCustomProviderConfig({...valid,diff --git a/apps/desktop/src/main/maker-host/__tests__/customProviderOAuth.test.ts b/apps/desktop/src/main/maker-host/__tests__/customProviderOAuth.test.tsindex 6d396fd182..44bdcb9684 100644--- a/apps/desktop/src/main/maker-host/__tests__/customProviderOAuth.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/customProviderOAuth.test.ts@@ -18,6 +18,13 @@ const OAUTH = {clientId: 'c1',scopes: 'openid',};+const DEVICE_OAUTH = {+ flow: 'device-code' as const,+ deviceAuthorizationUrl: 'https://auth.acme.example/device',+ tokenUrl: 'https://auth.acme.example/token',+ clientId: 'device-client',+ scopes: 'openid',+};const BASE: CustomProviderConfig = {id: 'acme-sub',@@ -48,6 +55,15 @@ describe('validateCustomProviderConfig auth 段', () => {expect(bad({ ...OAUTH, clientId: '' }).ok).toBe(false);expect(bad({ ...OAUTH, tokenUrl: 'http://auth.acme.example/token' }).ok).toBe(false);expect(bad({ ...OAUTH, redirectPort: 70000 }).ok).toBe(false);+ expect(+ validateCustomProviderConfig({+ ...BASE,+ auth: { method: 'oauth', oauth: DEVICE_OAUTH },+ }).ok,+ ).toBe(true);+ expect(bad({ ...DEVICE_OAUTH, deviceAuthorizationUrl: 'http://auth.acme.example/device' }).ok)+ .toBe(false);+ expect(bad({ ...DEVICE_OAUTH, redirectPort: 9123 }).ok).toBe(false);});it('apiKey method 不允许携带 oauth 描述符;非法 method 拒绝', () => {@@ -56,6 +72,56 @@ describe('validateCustomProviderConfig auth 段', () => {expect(validateCustomProviderConfig({ ...BASE, auth: { method: 'apiKey' } }).ok).toBe(true);});+ it('none method 明确允许无密钥代理,但不允许夹带 OAuth 描述符', () => {+ expect(validateCustomProviderConfig({ ...BASE, auth: { method: 'none' } }).ok).toBe(true);+ expect(+ validateCustomProviderConfig({+ ...BASE,+ auth: { method: 'none', oauth: OAUTH },+ }).ok,+ ).toBe(false);+ });++ it('拒绝扩展参数覆盖 OAuth 标准字段', () => {+ expect(+ validateCustomProviderConfig({+ ...BASE,+ auth: {+ method: 'oauth',+ oauth: { ...DEVICE_OAUTH, extraDeviceParams: { client_id: 'other-client' } },+ },+ }).ok,+ ).toBe(false);+ expect(+ validateCustomProviderConfig({+ ...BASE,+ auth: {+ method: 'oauth',+ oauth: { ...OAUTH, extraAuthParams: { state: 'fixed-state' } },+ },+ }).ok,+ ).toBe(false);+ });++ it('拒绝与 OAuth flow 不兼容的字段和带 userinfo 的上游地址', () => {+ const bad = (oauth: object) =>+ validateCustomProviderConfig({ ...BASE, auth: { method: 'oauth', oauth } });+ expect(bad({ ...OAUTH, deviceAuthorizationUrl: DEVICE_OAUTH.deviceAuthorizationUrl }).ok)+ .toBe(false);+ expect(bad({ ...DEVICE_OAUTH, authorizeUrl: OAUTH.authorizeUrl }).ok).toBe(false);+ expect(+ validateCustomProviderConfig({+ ...BASE,+ runtimes: {+ 'claude-code': {+ ...BASE.runtimes['claude-code']!,+ baseUrl: 'https://user:[email protected]/anthropic',+ },+ },+ }).ok,+ ).toBe(false);+ });+it('OAuth 形态模型可留空(授权后自动发现填充,用户免手填)', () => {const noModels = {...BASE,diff --git a/apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.ts b/apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.tsindex 1384449fe1..248d55694b 100644--- a/apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.ts@@ -50,6 +50,14 @@ const OAUTH: OAuthProviderDescriptor = {scopes: 'openid offline_access',modelsDiscoveryUrl: 'https://api.acme.example/v1/models',};+const DEVICE_OAUTH: OAuthProviderDescriptor = {+ flow: 'device-code',+ deviceAuthorizationUrl: 'https://auth.acme.example/oauth2/device',+ tokenUrl: 'https://auth.acme.example/oauth2/token',+ clientId: 'device-client-1',+ scopes: 'openid offline_access',+ modelsDiscoveryUrl: 'https://api.acme.example/v1/models',+};function memStorage(): GenericOAuthStorage & { map: Map<string, string> } {const map = new Map<string, string>();@@ -70,11 +78,13 @@ let storage = memStorage();let nowMs = 1_000_000;let fetchCalls: { url: string; body?: string; headers?: Record<string, string> }[] = [];let fetchResponder: (url: string) => Response = () => new Response('{}', { status: 500 });+let openedUrls: string[] = [];beforeEach(() => {storage = memStorage();nowMs = 1_000_000;fetchCalls = [];+ openedUrls = [];resetGenericOAuthMemoryCache();configureGenericOAuth({storage,@@ -87,6 +97,12 @@ beforeEach(() => {});return fetchResponder(String(url));}) as typeof fetch,+ openExternal: async (url) => {+ openedUrls.push(url);+ },+ sleep: async (ms) => {+ nowMs += ms;+ },});});@@ -202,6 +218,196 @@ describe('登录流与凭证落盘失败', () => {expect(readCachedGenericOAuthAccessToken('acme', OAUTH)).toBe('new'); // 内存态已是新 tokenexpect(JSON.parse(storage.map.get('acme')!).access_token).toBe('old'); // 盘上还是旧值});++ it('Device Grant:展示一次性代码,按 pending / slow_down 轮询并安全落盘', async () => {+ const waits: number[] = [];+ configureGenericOAuth({ sleep: async (ms) => void waits.push(ms) });+ let tokenPolls = 0;+ fetchResponder = (url) => {+ if (url === DEVICE_OAUTH.deviceAuthorizationUrl) {+ return new Response(+ JSON.stringify({+ device_code: 'secret-device-code',+ user_code: 'ABCD-EFGH',+ verification_uri: 'https://auth.acme.example/device',+ verification_uri_complete: 'https://auth.acme.example/device?user_code=ABCD-EFGH',+ expires_in: 600,+ interval: 1,+ }),+ { status: 200 },+ );+ }+ tokenPolls += 1;+ if (tokenPolls === 1) {+ return new Response(JSON.stringify({ error: 'authorization_pending' }), { status: 400 });+ }+ if (tokenPolls === 2) {+ return new Response(JSON.stringify({ error: 'slow_down' }), { status: 400 });+ }+ return new Response(+ JSON.stringify({+ access_token: 'device-access',+ refresh_token: 'device-refresh',+ expires_in: 3600,+ }),+ { status: 200 },+ );+ };+ const progress: unknown[] = [];++ const result = await runGenericOAuthLogin(+ { id: 'device', name: 'Device Provider' },+ DEVICE_OAUTH,+ { onProgress: (event) => progress.push(event) },+ );++ expect(result).toEqual({ ok: true });+ expect(progress).toEqual([+ {+ phase: 'device-code',+ verificationUrl: 'https://auth.acme.example/device?user_code=ABCD-EFGH',+ userCode: 'ABCD-EFGH',+ expiresAt: nowMs + 10 * 60_000,+ },+ ]);+ expect(waits).toEqual([1_000, 1_000, 6_000]);+ expect(openedUrls).toEqual([]);+ expect(new URLSearchParams(fetchCalls[0]?.body).get('client_id')).toBe('device-client-1');+ expect(new URLSearchParams(fetchCalls[1]?.body).get('grant_type')).toBe(+ 'urn:ietf:params:oauth:grant-type:device_code',+ );+ const persisted = storage.map.get('device')!;+ expect(JSON.parse(persisted).access_token).toBe('device-access');+ expect(persisted).not.toContain('secret-device-code');+ expect(persisted).not.toContain('ABCD-EFGH');+ });++ it('Device Grant:持续 pending 时按注入时钟到期,不会无限轮询', async () => {+ let tokenPolls = 0;+ fetchResponder = (url) => {+ if (url === DEVICE_OAUTH.deviceAuthorizationUrl) {+ return new Response(+ JSON.stringify({+ device_code: 'secret-device-code',+ user_code: 'ABCD-EFGH',+ verification_uri: 'https://auth.acme.example/device',+ expires_in: 2,+ interval: 1,+ }),+ { status: 200 },+ );+ }+ tokenPolls += 1;+ return new Response(JSON.stringify({ error: 'authorization_pending' }), { status: 400 });+ };++ const result = await runGenericOAuthLogin(+ { id: 'device', name: 'Device Provider' },+ DEVICE_OAUTH,+ { onProgress: () => undefined },+ );++ expect(result).toEqual({ ok: false, reason: 'device_code_expired' });+ expect(tokenPolls).toBe(2);+ expect(nowMs).toBe(1_002_000);+ expect(storage.map.has('device')).toBe(false);+ });++ it('Device Grant:标准 client_id/scope 不会被扩展参数覆盖', async () => {+ fetchResponder = () => new Response('{}', { status: 200 });+ const result = await runGenericOAuthLogin(+ { id: 'device', name: 'Device Provider' },+ {+ ...DEVICE_OAUTH,+ extraDeviceParams: {+ client_id: 'wrong-client',+ scope: 'wrong-scope',+ audience: 'models',+ },+ },+ );++ expect(result).toEqual({+ ok: false,+ reason: 'invalid_device_authorization_response',+ });+ const body = new URLSearchParams(fetchCalls[0]?.body);+ expect(body.getAll('client_id')).toEqual(['device-client-1']);+ expect(body.getAll('scope')).toEqual(['openid offline_access']);+ expect(body.get('audience')).toBe('models');+ });++ it('Authorization Code:标准 PKCE 参数不会被扩展参数或端点 query 覆盖', async () => {+ configureGenericOAuth({+ openExternal: async (authUrl) => {+ openedUrls.push(authUrl);+ cancelGenericOAuthLogin('acme');+ },+ });+ const result = await runGenericOAuthLogin(+ { id: 'acme', name: 'Acme' },+ {+ ...OAUTH,+ authorizeUrl: `${OAUTH.authorizeUrl}?client_id=endpoint-client`,+ extraAuthParams: {+ client_id: 'wrong-client',+ scope: 'wrong-scope',+ audience: 'models',+ },+ },+ );++ expect(result).toEqual({ ok: false, reason: 'login_cancelled' });+ const authUrl = new URL(openedUrls[0]!);+ expect(authUrl.searchParams.getAll('client_id')).toEqual(['client-1']);+ expect(authUrl.searchParams.getAll('scope')).toEqual(['openid offline_access']);+ expect(authUrl.searchParams.get('audience')).toBe('models');+ });++ it('Device Grant:进度回调后取消,不再轮询或写入凭证', async () => {+ fetchResponder = () =>+ new Response(+ JSON.stringify({+ device_code: 'secret-device-code',+ user_code: 'ABCD-EFGH',+ verification_uri: 'https://auth.acme.example/device',+ expires_in: 600,+ }),+ { status: 200 },+ );++ const result = await runGenericOAuthLogin(+ { id: 'device', name: 'Device Provider' },+ DEVICE_OAUTH,+ { onProgress: () => cancelGenericOAuthLogin('device') },+ );++ expect(result).toEqual({ ok: false, reason: 'login_cancelled' });+ expect(fetchCalls).toHaveLength(1);+ expect(storage.map.has('device')).toBe(false);+ });++ it('Device Grant:拒绝非 https 验证页响应', async () => {+ fetchResponder = () =>+ new Response(+ JSON.stringify({+ device_code: 'secret-device-code',+ user_code: 'ABCD-EFGH',+ verification_uri: 'http://auth.acme.example/device',+ expires_in: 600,+ }),+ { status: 200 },+ );++ const result = await runGenericOAuthLogin(+ { id: 'device', name: 'Device Provider' },+ DEVICE_OAUTH,+ );+ expect(result).toEqual({+ ok: false,+ reason: 'invalid_device_authorization_response',+ });+ });});describe('discoverGenericOAuthModels', () => {@@ -244,7 +450,7 @@ describe('discoverGenericOAuthModels', () => {fetchResponder = () => new Response(JSON.stringify({ data: [{ id: 'm' }] }), { status: 200 });await discoverGenericOAuthModels('acme', OAUTH, 'https://derived.example/v1/models');expect(fetchCalls[0]?.url).toBe('https://derived.example/v1/models');- const { modelsDiscoveryUrl: _omit, ...noDiscovery } = OAUTH;+ const noDiscovery = { ...OAUTH, modelsDiscoveryUrl: undefined };expect(await discoverGenericOAuthModels('acme', noDiscovery)).toBeNull();expect(fetchCalls).toHaveLength(1); // 第二次没发请求});diff --git a/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.tsindex 94a3786899..690f94b1ae 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.ts@@ -87,12 +87,18 @@ describe('buildProbeRequest', () => {baseUrl: 'https://api.deepseek.com/anthropic/',modelId: 'deepseek-chat',apiKey: 'sk-test',- headers: { 'x-custom': '1' },+ headers: {+ 'x-custom': '1',+ Authorization: 'Bearer stale',+ 'X-API-Key': 'stale',+ },});expect(url).toBe('https://api.deepseek.com/anthropic/v1/messages');const headers = init.headers as Record<string, string>;expect(headers['x-api-key']).toBe('sk-test');expect(headers['authorization']).toBe('Bearer sk-test');+ expect(headers.Authorization).toBeUndefined();+ expect(headers['X-API-Key']).toBeUndefined();expect(headers['anthropic-version']).toBe('2023-06-01');expect(headers['x-custom']).toBe('1');const body = JSON.parse(String(init.body)) as { model: string; max_tokens: number };@@ -155,6 +161,38 @@ describe('buildProbeRequest', () => {expect(body.tool_choice).toBeUndefined();});+ it('uses an exact request path instead of appending the protocol default', () => {+ const { url } = buildProbeRequest({+ agent: 'codex',+ baseUrl: 'https://gateway.example/api',+ modelId: 'custom-model',+ wireProtocol: 'openai-chat',+ requestPath: '/tenant/acme/infer?stream=1',+ });+ expect(url).toBe('https://gateway.example/api/tenant/acme/infer?stream=1');+ });++ it('preserves the base query when applying an exact request path', () => {+ const { url } = buildProbeRequest({+ agent: 'codex',+ baseUrl: 'https://gateway.example/api?tenant=alpha',+ modelId: 'custom-model',+ requestPath: '/infer?stream=1&mode=fast',+ });+ expect(url).toBe(+ 'https://gateway.example/api/infer?tenant=alpha&stream=1&mode=fast',+ );+ });++ it('rejects base URL credentials when applying an exact request path', () => {+ expect(() => buildProbeRequest({+ agent: 'codex',+ baseUrl: 'https://user:[email protected]/api',+ modelId: 'custom-model',+ requestPath: '/infer',+ })).toThrow('invalid provider base URL');+ });+it('无 key 时不注入鉴权头(端点可能靠自定义 headers 鉴权)', () => {const { init } = buildProbeRequest({agent: 'claude-code',@@ -253,7 +291,11 @@ describe('resolveSavedProbeSpec / testProviderConnection(saved)', () => {'claude-code': {baseUrl: 'https://relay.example/anthropic',models: [{ id: 'glm-5.2', name: 'GLM' }],- headers: { 'x-tenant': 't1' },+ headers: {+ 'x-tenant': 't1',+ Authorization: 'Bearer stale',+ 'X-API-Key': 'stale',+ },},},};@@ -270,6 +312,23 @@ describe('resolveSavedProbeSpec / testProviderConnection(saved)', () => {});});+ it('safeStorage 尚无 key 时保留 legacy header-only 凭证', () => {+ setCustomProviders([buildUserProvider(config)]);+ setDiagnosticsKeyReader(() => null);++ const spec = resolveSavedProbeSpec('my-relay', 'claude-code');+ expect(spec.apiKey).toBeNull();+ expect(spec.headers).toEqual({+ 'x-tenant': 't1',+ Authorization: 'Bearer stale',+ 'X-API-Key': 'stale',+ });++ const headers = buildProbeRequest(spec).init.headers as Record<string, string>;+ expect(headers.Authorization).toBe('Bearer stale');+ expect(headers['X-API-Key']).toBe('stale');+ });+it('api-key-header + openai-chat 供应商:saved 探测带上 wireProtocol → 打 /chat/completions', async () => {const chatConfig = {id: 'ds-chat',@@ -297,6 +356,25 @@ describe('resolveSavedProbeSpec / testProviderConnection(saved)', () => {expect(seenUrl).toBe('https://api.deepseek.com/chat/completions');});+ it('saved 探测沿用自定义供应商的精确请求路径', async () => {+ setCustomProviders([+ buildUserProvider({+ id: 'exact-path',+ name: 'Exact Path',+ runtimes: {+ codex: {+ baseUrl: 'https://gateway.example/api',+ requestPath: '/tenant/acme/infer',+ models: [{ id: 'm', name: 'M' }],+ },+ },+ }),+ ]);+ setDiagnosticsKeyReader(() => 'sk-exact');+ expect(resolveSavedProbeSpec('exact-path', 'codex').requestPath)+ .toBe('/tenant/acme/infer');+ });+it('不存在 / 非 user 供应商 / 无该 runtime → 抛错(handler 映射 INVALID_PARAMS)', () => {setCustomProviders([buildUserProvider(config)]);expect(() => resolveSavedProbeSpec('nope', 'claude-code')).toThrow(/not found/);@@ -349,4 +427,29 @@ describe('resolveSavedProbeSpec / testProviderConnection(saved)', () => {expect(headers['authorization']).toBe('Bearer at-77');expect(headers['x-api-key']).toBeUndefined();});++ it('none 供应商:saved 探测不读取旧 key,并剥掉配置里残留的鉴权头', () => {+ setCustomProviders([+ buildUserProvider({+ ...config,+ id: 'local-proxy',+ auth: { method: 'none' },+ runtimes: {+ 'claude-code': {+ ...config.runtimes['claude-code'],+ headers: {+ ...config.runtimes['claude-code'].headers,+ Authorization: 'Bearer must-not-leak',+ 'X-API-Key': 'must-not-leak',+ },+ },+ },+ }),+ ]);+ setDiagnosticsKeyReader(() => 'stale-safe-storage-key');++ const spec = resolveSavedProbeSpec('local-proxy', 'claude-code');+ expect(spec.apiKey).toBeNull();+ expect(spec.headers).toEqual({ 'x-tenant': 't1' });+ });});diff --git a/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.tsindex 024ee07ad9..aa58513f7e 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts@@ -42,10 +42,19 @@ describe('buildModelsFetchRequest', () => {});it('cc wire sends anthropic-version + x-api-key + Bearer; codex wire sends Bearer only', () => {- const cc = buildModelsFetchRequest(spec()).init.headers as Record<string, string>;+ const cc = buildModelsFetchRequest(spec({+ headers: {+ Authorization: 'Bearer stale',+ 'X-API-Key': 'stale',+ 'x-extra': '1',+ },+ })).init.headers as Record<string, string>;expect(cc['anthropic-version']).toBe('2023-06-01');expect(cc['x-api-key']).toBe('sk-test');expect(cc['authorization']).toBe('Bearer sk-test');+ expect(cc.Authorization).toBeUndefined();+ expect(cc['X-API-Key']).toBeUndefined();+ expect(cc['x-extra']).toBe('1');const codex = buildModelsFetchRequest(spec({ agent: 'codex' })).init.headers as Record<string, string>;expect(codex['anthropic-version']).toBeUndefined();diff --git a/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.tsindex 6db311c3c2..6aa9b5b674 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts@@ -11,6 +11,7 @@ vi.mock('../../appCapabilities.js', () => ({import { BUNDLED_CATALOG, buildUserProvider, type AgentKind, type RoutingDescriptor } from '@cindy/model-providers';import {+ buildLocalHandlerHeaders,buildRouteDecision,resolveSessionRouteDecision,inferProviderIdForModel,@@ -43,6 +44,12 @@ function descriptor(providerId: string, agent: AgentKind) {}const KEY = 'sk-test-gateway-key';+const CODEX_ACCOUNT_HEADER_DELETE = [+ 'chatgpt-account-id',+ 'openai-beta',+ 'originator',+ 'session_id',+];afterEach(() => {mockGetAppCapabilities.mockReturnValue({ canUseCindyGateway: true });@@ -285,13 +292,206 @@ describe('api-key-header (自定义供应商 buildRouteDecision)', () => {expect(buildRouteDecision(routing(), KEY, 'codex', 'sk-custom')).toEqual({headerOverride: { authorization: 'Bearer sk-custom' },upstreamOverride: 'https://api.myprovider.com/v1',+ headerDelete: CODEX_ACCOUNT_HEADER_DELETE,});});- it('叠加用户自定义 headers;无 key 时仍路由到 baseUrl(让上游决定鉴权)', () => {+ it('叠加用户自定义 headers;无 key 时用哑值覆盖 CLI 凭证', () => {expect(buildRouteDecision(routing({ 'X-Org': 'acme' }), KEY, 'codex', null)).toEqual({- headerOverride: { 'X-Org': 'acme' },+ headerOverride: {+ 'X-Org': 'acme',+ authorization: 'Bearer cindy-missing-custom-provider-api-key',+ },upstreamOverride: 'https://api.myprovider.com/v1',+ headerDelete: CODEX_ACCOUNT_HEADER_DELETE,+ });+ });++ it('无 safeStorage key 时保留旧版 header-only 凭证', () => {+ expect(+ buildRouteDecision(+ routing({ Authorization: 'Bearer legacy', 'X-Tenant': 'tenant-a' }),+ KEY,+ 'codex',+ null,+ ),+ ).toEqual({+ headerOverride: { authorization: 'Bearer legacy', 'X-Tenant': 'tenant-a' },+ upstreamOverride: 'https://api.myprovider.com/v1',+ headerDelete: CODEX_ACCOUNT_HEADER_DELETE,+ });+ });++ it('legacy 只含 x-api-key 时仍覆盖 Codex Authorization', () => {+ expect(+ buildRouteDecision(+ routing({ 'X-API-Key': 'legacy-key' }),+ KEY,+ 'codex',+ null,+ ),+ ).toEqual({+ headerOverride: {+ 'x-api-key': 'legacy-key',+ authorization: 'Bearer cindy-missing-custom-provider-api-key',+ },+ upstreamOverride: 'https://api.myprovider.com/v1',+ headerDelete: CODEX_ACCOUNT_HEADER_DELETE,+ });+ });++ it('legacy 只含 Authorization 时仍覆盖 Claude x-api-key', () => {+ expect(+ buildRouteDecision(+ routing({ Authorization: 'Bearer legacy' }),+ KEY,+ 'claude-code',+ null,+ ),+ ).toEqual({+ headerOverride: {+ authorization: 'Bearer legacy',+ 'x-api-key': 'cindy-missing-custom-provider-api-key',+ },+ upstreamOverride: 'https://api.myprovider.com/v1',+ });+ });++ it('safeStorage key 始终覆盖复制配置里残留的鉴权头', () => {+ expect(+ buildRouteDecision(+ routing({+ Authorization: 'Bearer stale',+ 'X-API-Key': 'stale',+ 'X-Tenant': 'tenant-a',+ }),+ KEY,+ 'codex',+ 'sk-current',+ ),+ ).toEqual({+ headerOverride: {+ 'X-Tenant': 'tenant-a',+ authorization: 'Bearer sk-current',+ },+ upstreamOverride: 'https://api.myprovider.com/v1',+ headerDelete: CODEX_ACCOUNT_HEADER_DELETE,+ });+ });++ it('缺少 safeStorage 与 legacy key 时用哑值覆盖 CLI 凭证并删除 Codex 账号头', () => {+ expect(+ buildRouteDecision(+ routing({ 'X-Tenant': 'tenant-a' }),+ KEY,+ 'codex',+ null,+ ),+ ).toEqual({+ headerOverride: {+ 'X-Tenant': 'tenant-a',+ authorization: 'Bearer cindy-missing-custom-provider-api-key',+ },+ upstreamOverride: 'https://api.myprovider.com/v1',+ headerDelete: CODEX_ACCOUNT_HEADER_DELETE,+ });+ });++ it('本地 Chat bridge 在缺 key 时保留 legacy 凭证,否则注入哑值', () => {+ const baseRoute = {+ providerId: 'legacy',+ providerSource: 'user' as const,+ routing: routing({ 'X-Tenant': 'tenant-a' }),+ apiKey: null,+ oauthToken: null,+ };+ expect(buildLocalHandlerHeaders(baseRoute, 'codex')).toMatchObject({+ headers: {+ 'X-Tenant': 'tenant-a',+ authorization: 'Bearer cindy-missing-custom-provider-api-key',+ },+ });+ expect(+ buildLocalHandlerHeaders({+ ...baseRoute,+ routing: routing({+ Authorization: 'Bearer legacy',+ 'X-Tenant': 'tenant-a',+ }),+ }, 'codex'),+ ).toMatchObject({+ headers: {+ authorization: 'Bearer legacy',+ 'X-Tenant': 'tenant-a',+ },+ });+ });+});++describe('none (无鉴权自定义代理 buildRouteDecision)', () => {+ const routing: RoutingDescriptor = {+ upstream: 'http://127.0.0.1:4000/v1',+ authStrategy: 'none',+ headerOverride: { 'X-Proxy-Tenant': 'local' },+ };++ it('cc 固定路由本机代理并删除 Claude CLI 自带的认证头', () => {+ expect(buildRouteDecision(routing, KEY, 'claude-code', null)).toEqual({+ upstreamOverride: 'http://127.0.0.1:4000/v1',+ headerOverride: { 'X-Proxy-Tenant': 'local' },+ headerDelete: ['authorization', 'x-api-key'],+ });+ });++ it('codex 额外删除 ChatGPT 账号元数据,避免订阅身份泄漏', () => {+ expect(buildRouteDecision(routing, KEY, 'codex', null)).toEqual({+ upstreamOverride: 'http://127.0.0.1:4000/v1',+ headerOverride: { 'X-Proxy-Tenant': 'local' },+ headerDelete: [+ 'authorization',+ 'x-api-key',+ 'chatgpt-account-id',+ 'openai-beta',+ 'originator',+ 'session_id',+ ],+ });+ });++ it('无鉴权透明路由不保留自定义 headers 里的凭证', () => {+ expect(+ buildRouteDecision({+ ...routing,+ headerOverride: {+ Authorization: 'Bearer must-not-leak',+ 'X-API-Key': 'must-not-leak',+ 'X-Proxy-Tenant': 'local',+ },+ }, KEY, 'codex', null),+ ).toMatchObject({+ headerOverride: { 'X-Proxy-Tenant': 'local' },+ });+ });++ it('本地 Chat 桥也剥掉复制配置里残留的鉴权与账号头', () => {+ expect(+ buildLocalHandlerHeaders({+ providerId: 'local',+ providerSource: 'user',+ routing: {+ ...routing,+ headerOverride: {+ Authorization: 'Bearer must-not-leak',+ 'X-API-Key': 'must-not-leak',+ 'ChatGPT-Account-ID': 'acct',+ 'X-Proxy-Tenant': 'local',+ },+ },+ apiKey: null,+ oauthToken: null,+ }, 'codex'),+ ).toMatchObject({+ headers: { 'X-Proxy-Tenant': 'local' },});});});@@ -324,6 +524,37 @@ describe('resolveSessionRouteDecision — 自定义供应商(resolve 时注入 kexpect(resolveSessionRouteDecision('s-user', 'codex', KEY)).toEqual({headerOverride: { authorization: 'Bearer sk-or-123' },upstreamOverride: 'https://openrouter.ai/api/v1',+ headerDelete: CODEX_ACCOUNT_HEADER_DELETE,+ });+ });++ it('精确请求路径只覆盖带 model 的推理请求,不改写无 body 的控制面请求', () => {+ setCustomProviders([+ buildUserProvider({+ id: 'exact-path',+ name: 'Exact Path',+ runtimes: {+ codex: {+ baseUrl: 'https://gateway.example/api',+ requestPath: '/tenant/acme/infer?stream=1',+ models: [{ id: 'custom-model', name: 'Custom Model' }],+ },+ },+ }),+ ]);+ setCustomProviderKeyReader(() => 'sk-exact');+ setSessionProvider('s-user', 'exact-path');++ expect(resolveSessionRouteDecision('s-user', 'codex', KEY, 'custom-model')).toEqual({+ headerOverride: { authorization: 'Bearer sk-exact' },+ upstreamOverride: 'https://gateway.example/api',+ pathOverride: '/tenant/acme/infer?stream=1',+ headerDelete: CODEX_ACCOUNT_HEADER_DELETE,+ });+ expect(resolveSessionRouteDecision('s-user', 'codex', KEY)).toEqual({+ headerOverride: { authorization: 'Bearer sk-exact' },+ upstreamOverride: 'https://gateway.example/api',+ headerDelete: CODEX_ACCOUNT_HEADER_DELETE,});});diff --git a/apps/desktop/src/main/maker-host/__tests__/providerService.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerService.test.tsindex b5eed2dc91..b018171558 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerService.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerService.test.ts@@ -46,4 +46,29 @@ describe('createProviderService', () => {const openai = (await svc.listProviders()).find((p) => p.id === 'openai')!;expect(openai.connected).toBe(true);});++ it('treats catalog no-auth providers as connected without credentials', async () => {+ const noAuthProvider = {+ ...BUNDLED_CATALOG.providers[0],+ id: 'local-no-auth',+ name: 'Local no-auth',+ auth: { method: 'none' as const },+ };+ const svc = createProviderService({+ getCatalog: () => ({+ version: 'no-auth-test',+ providers: [...BUNDLED_CATALOG.providers, noAuthProvider],+ }),+ connection: {+ xd: () => false,+ anthropic: () => false,+ openai: () => false,+ xai: () => false,+ },+ });++ expect(+ (await svc.listProviders()).find((provider) => provider.id === noAuthProvider.id)?.connected,+ ).toBe(true);+ });});diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.tsindex 8325ebe046..b888ac3271 100644--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts@@ -201,6 +201,14 @@ const CHAT_BRIDGE_DEFAULT_CAPABILITIES: ChatBridgeCapabilities = {forceAutoToolChoice: true,};+function isGoogleGeminiChatUpstream(upstream: string): boolean {+ try {+ return new URL(upstream).hostname === 'generativelanguage.googleapis.com';+ } catch {+ return false;+ }+}+/*** Chat bridge 上游只收 host 明确构造的 header。绝不把 Codex/ChatGPT 请求 header* 原样透传,防止账号 id、OpenAI OAuth bearer 或内部 session 元数据泄漏给第三方。@@ -218,6 +226,19 @@ function createChatBridgeDecision(// (与 observer 的 user-only 语义一致)。const providerId = route.providerId;const providerName = getActiveCatalog().providers.find((p) => p.id === providerId)?.name ?? providerId;+ const capabilities: ChatBridgeCapabilities = isGoogleGeminiChatUpstream(+ route.routing.upstream,+ )+ ? {+ ...CHAT_BRIDGE_DEFAULT_CAPABILITIES,+ // Gemini 的 OpenAI 兼容层原生理解 reasoning_effort 和具名 tool choice;同时不需要+ // DeepSeek/Kimi 的 reasoning_content 占位。工具回放则必须带 Google thought signature。+ reasoningField: 'reasoning_effort',+ toolCallReasoningPlaceholder: false,+ forceAutoToolChoice: false,+ googleThoughtSignaturePlaceholder: true,+ }+ : CHAT_BRIDGE_DEFAULT_CAPABILITIES;const onUpstreamError = route.providerSource === 'user'? ({ status, body }: { status: number; body: string }): void => {reportProviderUpstreamError({ agent: 'codex', providerId, providerName, status, bodyText: body });@@ -225,11 +246,12 @@ function createChatBridgeDecision(: undefined;const handler = createResponsesChatHandler({upstreamBase: route.routing.upstream,+ ...(route.routing.requestPath ? { chatCompletionsPath: route.routing.requestPath } : {}),buildHeaders: async () => headers,rewriteModel: (model: string) => stripPrefix && model.startsWith(stripPrefix)? model.slice(stripPrefix.length): model,- capabilities: CHAT_BRIDGE_DEFAULT_CAPABILITIES,+ capabilities,...(onUpstreamError ? { onUpstreamError } : {}),}, { logger: log });return {diff --git a/apps/desktop/src/main/maker-host/custom-provider-store.ts b/apps/desktop/src/main/maker-host/custom-provider-store.tsindex 64ebef3f5d..04060f7562 100644--- a/apps/desktop/src/main/maker-host/custom-provider-store.ts+++ b/apps/desktop/src/main/maker-host/custom-provider-store.ts@@ -20,6 +20,10 @@ import type {CustomProviderRuntimeConfig,OAuthProviderDescriptor,} from '@cindy/model-providers';+import {+ findReservedOAuthExtraParam,+ isProviderRequestPath,+} from '@cindy/model-providers';import { getDbClient } from '../localDb/client/current.js';import { customProviders } from '../localDb/schema.js';@@ -52,9 +56,18 @@ function validateRuntime(agent: string, rt: unknown): ValidationResult {if (u.protocol !== 'http:' && u.protocol !== 'https:') {return invalid(`runtime '${agent}' baseUrl must be http(s)`);}+ if (u.username || u.password) {+ return invalid(`runtime '${agent}' baseUrl must not contain embedded credentials`);+ }} catch {return invalid(`runtime '${agent}' baseUrl is not a valid URL`);}+ if (+ r.requestPath !== undefined+ && !isProviderRequestPath(r.requestPath)+ ) {+ return invalid(`runtime '${agent}' requestPath invalid`);+ }if (!Array.isArray(r.models)) return invalid(`runtime '${agent}' models must be an array`);for (const m of r.models) {if (!m || typeof m !== 'object') return invalid(`runtime '${agent}' model must be an object`);@@ -113,34 +126,67 @@ function validateRuntime(agent: string, rt: unknown): ValidationResult {return { ok: true };}-/** 校验用户填写的 OAuth 描述符(与目录 parseCatalog 的 validateOAuthDescriptor 同规则)。 */-function validateOAuthSection(auth: unknown): ValidationResult {+/** 校验用户填写的鉴权描述符(OAuth 部分与目录校验保持同规则)。 */+function validateAuthSection(auth: unknown): ValidationResult {if (!auth || typeof auth !== 'object') return invalid('auth must be an object');const a = auth as Record<string, unknown>;- if (a.method !== 'apiKey' && a.method !== 'oauth') return invalid("auth.method must be 'apiKey' | 'oauth'");- if (a.method === 'apiKey') {- if (a.oauth !== undefined) return invalid('auth.oauth not allowed for apiKey method');+ if (a.method !== 'apiKey' && a.method !== 'oauth' && a.method !== 'none') {+ return invalid("auth.method must be 'apiKey' | 'oauth' | 'none'");+ }+ if (a.method === 'apiKey' || a.method === 'none') {+ if (a.oauth !== undefined) return invalid(`auth.oauth not allowed for ${a.method} method`);return { ok: true };}const d = a.oauth;if (!d || typeof d !== 'object') return invalid('auth.oauth required for oauth method');const o = d as Record<string, unknown>;- for (const field of ['authorizeUrl', 'tokenUrl', 'clientId', 'scopes'] as const) {+ const flow = o.flow ?? 'authorization-code';+ if (flow !== 'authorization-code' && flow !== 'device-code') {+ return invalid("auth.oauth.flow must be 'authorization-code' | 'device-code'");+ }+ if (+ flow === 'authorization-code'+ && (o.deviceAuthorizationUrl !== undefined || o.extraDeviceParams !== undefined)+ ) {+ return invalid('auth.oauth device-code fields not allowed for authorization-code');+ }+ if (+ flow === 'device-code'+ && (+ o.authorizeUrl !== undefined+ || o.extraAuthParams !== undefined+ || o.redirectPort !== undefined+ )+ ) {+ return invalid('auth.oauth authorization-code fields not allowed for device-code');+ }+ for (const field of ['tokenUrl', 'clientId', 'scopes'] as const) {if (typeof o[field] !== 'string' || (o[field] as string).trim().length === 0) {return invalid(`auth.oauth.${field} required`);}}- for (const field of ['authorizeUrl', 'tokenUrl'] as const) {+ const endpointFields =+ flow === 'device-code'+ ? (['deviceAuthorizationUrl', 'tokenUrl'] as const)+ : (['authorizeUrl', 'tokenUrl'] as const);+ for (const field of endpointFields) {+ if (typeof o[field] !== 'string' || (o[field] as string).trim().length === 0) {+ return invalid(`auth.oauth.${field} required`);+ }try {const u = new URL(o[field] as string);// OAuth 端点强制 https:回调虽在回环,但授权码/token 交换绝不能明文出网。- if (u.protocol !== 'https:') return invalid(`auth.oauth.${field} must be https`);+ if (u.protocol !== 'https:' || u.username || u.password) {+ return invalid(`auth.oauth.${field} must be https`);+ }} catch {return invalid(`auth.oauth.${field} is not a valid URL`);}}if (o.redirectPort !== undefined) {if (+ flow !== 'authorization-code'+ ||typeof o.redirectPort !== 'number'|| !Number.isInteger(o.redirectPort)|| o.redirectPort <= 0@@ -149,6 +195,41 @@ function validateOAuthSection(auth: unknown): ValidationResult {return invalid('auth.oauth.redirectPort invalid');}}+ for (const field of ['extraAuthParams', 'extraDeviceParams'] as const) {+ if (o[field] === undefined) continue;+ if (!o[field] || typeof o[field] !== 'object' || Array.isArray(o[field])) {+ return invalid(`auth.oauth.${field} invalid`);+ }+ if (+ Object.values(o[field] as Record<string, unknown>).some(+ (value) => typeof value !== 'string',+ )+ ) {+ return invalid(`auth.oauth.${field} invalid`);+ }+ const collision = findReservedOAuthExtraParam(+ o[field] as Record<string, unknown>,+ flow,+ );+ if (collision) {+ return invalid(`auth.oauth.${field} cannot override '${collision}'`);+ }+ }+ if (o.modelsDiscoveryUrl !== undefined) {+ try {+ const url = new URL(String(o.modelsDiscoveryUrl));+ if (+ typeof o.modelsDiscoveryUrl !== 'string'+ || url.protocol !== 'https:'+ || url.username+ || url.password+ ) {+ return invalid('auth.oauth.modelsDiscoveryUrl must be https');+ }+ } catch {+ return invalid('auth.oauth.modelsDiscoveryUrl is not a valid URL');+ }+ }return { ok: true };}@@ -166,7 +247,7 @@ export function validateCustomProviderConfig(config: unknown): ValidationResultif (c.name.length > MAX_NAME_LEN) return invalid(`name too long (max ${MAX_NAME_LEN})`);if (c.auth !== undefined) {- const a = validateOAuthSection(c.auth);+ const a = validateAuthSection(c.auth);if (!a.ok) return a;}@@ -203,6 +284,7 @@ function normalizeRuntime(rt: CustomProviderRuntimeConfig): CustomProviderRuntimrt.headers && Object.keys(rt.headers).length > 0 ? { ...rt.headers } : undefined;const out: CustomProviderRuntimeConfig = { baseUrl: rt.baseUrl.trim(), models };if (rt.wireProtocol) out.wireProtocol = rt.wireProtocol;+ if (rt.requestPath && rt.requestPath.trim()) out.requestPath = rt.requestPath.trim();if (headers) out.headers = headers;if (rt.modelsUrl && rt.modelsUrl.trim()) out.modelsUrl = rt.modelsUrl.trim();return out;@@ -216,21 +298,38 @@ function normalizeConfig(config: CustomProviderConfig): CustomProviderConfig {if (rt) runtimes[agent] = normalizeRuntime(rt);}const out: CustomProviderConfig = { id: config.id, name: config.name.trim(), runtimes };- // auth 规整:apiKey(默认形态)不落 auth 字段;oauth 落 trim 过的描述符。+ // auth 规整:apiKey(默认形态)不落 auth 字段;none / oauth 显式落盘。if (config.auth?.method === 'oauth' && config.auth.oauth) {const d = config.auth.oauth;- const oauth: OAuthProviderDescriptor = {- authorizeUrl: d.authorizeUrl.trim(),- tokenUrl: d.tokenUrl.trim(),- clientId: d.clientId.trim(),- scopes: d.scopes.trim(),- };- if (d.redirectPort !== undefined) oauth.redirectPort = d.redirectPort;- if (d.extraAuthParams && Object.keys(d.extraAuthParams).length > 0) {- oauth.extraAuthParams = { ...d.extraAuthParams };+ let oauth: OAuthProviderDescriptor;+ if (d.flow === 'device-code') {+ oauth = {+ flow: 'device-code',+ deviceAuthorizationUrl: d.deviceAuthorizationUrl.trim(),+ tokenUrl: d.tokenUrl.trim(),+ clientId: d.clientId.trim(),+ scopes: d.scopes.trim(),+ };+ if (d.extraDeviceParams && Object.keys(d.extraDeviceParams).length > 0) {+ oauth.extraDeviceParams = { ...d.extraDeviceParams };+ }+ } else {+ oauth = {+ ...(d.flow === 'authorization-code' ? { flow: 'authorization-code' as const } : {}),+ authorizeUrl: d.authorizeUrl.trim(),+ tokenUrl: d.tokenUrl.trim(),+ clientId: d.clientId.trim(),+ scopes: d.scopes.trim(),+ };+ if (d.redirectPort !== undefined) oauth.redirectPort = d.redirectPort;+ if (d.extraAuthParams && Object.keys(d.extraAuthParams).length > 0) {+ oauth.extraAuthParams = { ...d.extraAuthParams };+ }}if (d.modelsDiscoveryUrl) oauth.modelsDiscoveryUrl = d.modelsDiscoveryUrl.trim();out.auth = { method: 'oauth', oauth };+ } else if (config.auth?.method === 'none') {+ out.auth = { method: 'none' };}return out;}@@ -268,10 +367,11 @@ function parseAuth(raw: string | null): CustomProviderConfig['auth'] {} catch {return undefined;}- const r = validateOAuthSection(v);+ const r = validateAuthSection(v);if (!r.ok) return undefined;- const a = v as { method: 'apiKey' | 'oauth'; oauth?: OAuthProviderDescriptor };- return a.method === 'oauth' ? a : undefined;+ const a = v as CustomProviderConfig['auth'];+ if (a?.method === 'oauth' || a?.method === 'none') return a;+ return undefined;}/** 安全解析 runtimes JSON(坏数据兜底为 {},逐字段防御)。 */@@ -315,6 +415,9 @@ function parseRuntimes(raw: string): Partial<Record<AgentKind, CustomProviderRun) {entry.wireProtocol = r.wireProtocol;}+ if (isProviderRequestPath(r.requestPath)) {+ entry.requestPath = r.requestPath;+ }if (r.headers && typeof r.headers === 'object' && !Array.isArray(r.headers)) {entry.headers = r.headers as Record<string, string>;}diff --git a/apps/desktop/src/main/maker-host/generic-oauth.ts b/apps/desktop/src/main/maker-host/generic-oauth.tsindex 92a27d1520..44bacad2ac 100644--- a/apps/desktop/src/main/maker-host/generic-oauth.ts+++ b/apps/desktop/src/main/maker-host/generic-oauth.ts@@ -4,7 +4,7 @@* 把 grok-oauth-login.ts 的五件同构事泛化成 per-provider 实例:* ① PKCE 授权页拉起(回环回调端口来自描述符,缺省随机高位端口);* ② 回调捕获(state 校验);- * ③ form-encoded token 交换(PKCE challenge 二次回发,兼容严格校验的端点);+ * ③ form-encoded token 交换(按 RFC 7636 回发 PKCE verifier);* ④ 凭证 blob 存 safeStorage `provider_oauth_<id>`(IO 注入,见 providerSecretStore* 的 genericOAuthSecretIo)+ 内存缓存(路由热路径同步读,规则 10);* ⑤ 临期单飞刷新(per-provider mutex 链 + 15s 超时 + 登出/重登竞态复核)。@@ -57,6 +57,22 @@ interface GenericOAuthIo {/** 拉起系统浏览器(生产 = electron shell.openExternal)。 */openExternal: (url: string) => Promise<void>;now: () => number;+ sleep: (ms: number, signal: AbortSignal) => Promise<void>;+}++function sleepWithAbort(ms: number, signal: AbortSignal): Promise<void> {+ if (signal.aborted) return Promise.reject(new Error('login_cancelled'));+ return new Promise<void>((resolve, reject) => {+ const timer = setTimeout(() => {+ signal.removeEventListener('abort', onAbort);+ resolve();+ }, ms);+ const onAbort = () => {+ clearTimeout(timer);+ reject(new Error('login_cancelled'));+ };+ signal.addEventListener('abort', onAbort, { once: true });+ });}let io: GenericOAuthIo = {@@ -66,6 +82,7 @@ let io: GenericOAuthIo = {throw new Error('generic-oauth openExternal not configured');},now: Date.now,+ sleep: sleepWithAbort,};/** host 启动期 / 测试注入依赖(部分覆盖)。 */@@ -428,95 +445,242 @@ export interface GenericOAuthLoginResult {reason?: string;}+export interface GenericOAuthDeviceCodeProgress {+ phase: 'device-code';+ verificationUrl: string;+ userCode: string;+ expiresAt: number;+}++export interface GenericOAuthLoginOptions {+ onProgress?: (progress: GenericOAuthDeviceCodeProgress) => void;+}+// 同一时刻每个 provider 只允许一个登录流。-const activeLogins = new Map<string, { listener: CallbackListener; abort: AbortController }>();+const activeLogins = new Map<+ string,+ { abort: AbortController; close: () => void }+>();/** 取消某供应商进行中的登录。 */export function cancelGenericOAuthLogin(providerId: string): void {const cur = activeLogins.get(providerId);if (!cur) return;cur.abort.abort();- cur.listener.close();+ cur.close();activeLogins.delete(providerId);}-/**- * 跑一次描述符驱动的 OAuth 浏览器登录。成功后凭证 blob 写 safeStorage(provider_oauth_<id>)。- */-export async function runGenericOAuthLogin(- provider: { id: string; name: string },- oauth: OAuthProviderDescriptor,-): Promise<GenericOAuthLoginResult> {- cancelGenericOAuthLogin(provider.id);+function safeVerificationUrl(value: unknown): string | null {+ if (typeof value !== 'string' || value.length === 0) return null;+ try {+ const url = new URL(value);+ if (url.protocol !== 'https:' || url.username || url.password) return null;+ return url.toString();+ } catch {+ return null;+ }+}- const verifier = genVerifier();- const challenge = genChallenge(verifier);- const state = genState();- const listener = new CallbackListener(provider.name);- const abort = new AbortController();- activeLogins.set(provider.id, { listener, abort });+function positiveNumber(value: unknown): number | null {+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : null;+}- let timer: ReturnType<typeof setTimeout> | null = null;+async function readJsonObject(response: Response): Promise<Record<string, unknown> | null> {try {- await listener.start(oauth.redirectPort);- if (abort.signal.aborted) throw new Error('login_cancelled');- const redirectUri = `http://127.0.0.1:${listener.port}/callback`;-- const authUrl = new URL(oauth.authorizeUrl);- authUrl.searchParams.append('response_type', 'code');- authUrl.searchParams.append('client_id', oauth.clientId);- authUrl.searchParams.append('redirect_uri', redirectUri);- authUrl.searchParams.append('scope', oauth.scopes);- authUrl.searchParams.append('code_challenge', challenge);- authUrl.searchParams.append('code_challenge_method', 'S256');- authUrl.searchParams.append('state', state);- for (const [k, v] of Object.entries(oauth.extraAuthParams ?? {})) {- authUrl.searchParams.append(k, v);- }+ const value = (await response.json()) as unknown;+ return value && typeof value === 'object' && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : null;+ } catch {+ return null;+ }+}- // 先注册 code 等待再开浏览器(已授权的浏览器可能在 openExternal 返回前就完成重定向,同 grok)。- const codePromise = new Promise<string>((resolve, reject) => {- if (abort.signal.aborted) {- reject(new Error('login_cancelled'));- return;- }- timer = setTimeout(() => reject(new Error('timeout')), LOGIN_TIMEOUT_MS);- abort.signal.addEventListener('abort', () => reject(new Error('login_cancelled')), {- once: true,- });- listener.waitForCode(state).then(resolve, reject);+async function runDeviceCodeGrant(+ providerId: string,+ oauth: Extract<OAuthProviderDescriptor, { flow: 'device-code' }>,+ abort: AbortController,+ options?: GenericOAuthLoginOptions,+): Promise<TokenResponse> {+ const requestBody = new URLSearchParams(oauth.extraDeviceParams ?? {});+ // 标准字段永远以描述符为准;即使未来有未经过目录校验的调用方也不能被 extras 覆盖。+ requestBody.set('client_id', oauth.clientId);+ requestBody.set('scope', oauth.scopes);+ const authorizationResponse = await io.fetchImpl(oauth.deviceAuthorizationUrl, {+ method: 'POST',+ headers: { 'content-type': 'application/x-www-form-urlencoded' },+ body: requestBody.toString(),+ signal: AbortSignal.any([abort.signal, AbortSignal.timeout(TOKEN_EXCHANGE_TIMEOUT_MS)]),+ });+ const authorization = await readJsonObject(authorizationResponse);+ if (!authorizationResponse.ok) {+ throw new Error(`device_authorization_failed_${authorizationResponse.status}`);+ }++ const deviceCode =+ typeof authorization?.device_code === 'string' ? authorization.device_code : '';+ const userCode = typeof authorization?.user_code === 'string' ? authorization.user_code : '';+ const verificationUrl =+ safeVerificationUrl(authorization?.verification_uri_complete)+ ?? safeVerificationUrl(authorization?.verification_uri)+ ?? safeVerificationUrl(authorization?.verification_url);+ const expiresInSeconds = positiveNumber(authorization?.expires_in);+ if (!deviceCode || !userCode || !verificationUrl || !expiresInSeconds) {+ throw new Error('invalid_device_authorization_response');+ }++ const expiresInMs = expiresInSeconds * 1000;+ if (!Number.isFinite(expiresInMs)) {+ throw new Error('invalid_device_authorization_response');+ }+ // Device Authorization Grant 的有效期由 IdP 的 expires_in 决定;不能用授权码登录的+ // 五分钟回调超时截断,否则合法的 10–15 分钟设备码会在服务端仍有效时被本地提前判过期。+ const expiresAt = io.now() + expiresInMs;+ try {+ options?.onProgress?.({+ phase: 'device-code',+ verificationUrl,+ userCode,+ expiresAt,});- codePromise.catch(() => {- /* handled at await site */+ } catch (err) {+ log.warn('generic oauth device-code progress callback failed', {+ providerId,+ err: err instanceof Error ? err.message : String(err),});+ }- log.info('opening browser for generic oauth', { providerId: provider.id, port: listener.port });- await io.openExternal(authUrl.toString());-- const code = await codePromise;+ let intervalMs = Math.min(+ Math.max((positiveNumber(authorization?.interval) ?? 5) * 1000, 1_000),+ 60_000,+ );+ while (io.now() < expiresAt) {+ await io.sleep(Math.min(intervalMs, Math.max(0, expiresAt - io.now())), abort.signal);+ if (abort.signal.aborted) throw new Error('login_cancelled');- // form-encoded、严格按 RFC 7636 §4.5:token 端点只回发 code_verifier。- // (code_challenge/method 属 /authorize 参数,带到 token 端点会被严格校验的 IdP- // 拒为 invalid_request;需要非标参数的供应商走 bespoke 实现,不进通用 Runner。)- // 超时与用户取消双保险:授权页等待的 LOGIN_TIMEOUT_MS 管不到这一步。- const res = await io.fetchImpl(oauth.tokenUrl, {+ const response = await io.fetchImpl(oauth.tokenUrl, {method: 'POST',headers: { 'content-type': 'application/x-www-form-urlencoded' },body: new URLSearchParams({- grant_type: 'authorization_code',+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',+ device_code: deviceCode,client_id: oauth.clientId,- code,- redirect_uri: redirectUri,- code_verifier: verifier,}).toString(),signal: AbortSignal.any([abort.signal, AbortSignal.timeout(TOKEN_EXCHANGE_TIMEOUT_MS)]),});- if (!res.ok) {- const body = await res.text().catch(() => '');- throw new Error(`Token exchange failed (${res.status}): ${body.slice(0, 200)}`);+ const payload = await readJsonObject(response);+ if (+ response.ok+ && typeof payload?.access_token === 'string'+ && payload.access_token.length > 0+ ) {+ return payload as unknown as TokenResponse;+ }++ const error = typeof payload?.error === 'string' ? payload.error : '';+ if (error === 'authorization_pending') continue;+ if (error === 'slow_down') {+ intervalMs = Math.min(intervalMs + 5_000, 60_000);+ continue;+ }+ if (error === 'access_denied') throw new Error('device_access_denied');+ if (error === 'expired_token') throw new Error('device_code_expired');+ throw new Error(+ error+ ? `device_token_error_${error}`+ : `device_token_exchange_failed_${response.status}`,+ );+ }+ throw new Error('device_code_expired');+}++/**+ * 跑一次描述符驱动的 OAuth 登录。支持浏览器回环 PKCE 与 Device Authorization Grant;+ * 成功后凭证 blob 写 safeStorage(provider_oauth_<id>)。+ */+export async function runGenericOAuthLogin(+ provider: { id: string; name: string },+ oauth: OAuthProviderDescriptor,+ options?: GenericOAuthLoginOptions,+): Promise<GenericOAuthLoginResult> {+ cancelGenericOAuthLogin(provider.id);++ const listener =+ oauth.flow === 'device-code' ? null : new CallbackListener(provider.name);+ const abort = new AbortController();+ activeLogins.set(provider.id, {+ abort,+ close: () => listener?.close(),+ });++ let timer: ReturnType<typeof setTimeout> | null = null;+ try {+ let tok: TokenResponse;+ if (oauth.flow === 'device-code') {+ tok = await runDeviceCodeGrant(provider.id, oauth, abort, options);+ } else {+ const verifier = genVerifier();+ const challenge = genChallenge(verifier);+ const state = genState();+ await listener!.start(oauth.redirectPort);+ if (abort.signal.aborted) throw new Error('login_cancelled');+ const redirectUri = `http://127.0.0.1:${listener!.port}/callback`;++ const authUrl = new URL(oauth.authorizeUrl);+ for (const [k, v] of Object.entries(oauth.extraAuthParams ?? {})) {+ authUrl.searchParams.append(k, v);+ }+ authUrl.searchParams.set('response_type', 'code');+ authUrl.searchParams.set('client_id', oauth.clientId);+ authUrl.searchParams.set('redirect_uri', redirectUri);+ authUrl.searchParams.set('scope', oauth.scopes);+ authUrl.searchParams.set('code_challenge', challenge);+ authUrl.searchParams.set('code_challenge_method', 'S256');+ authUrl.searchParams.set('state', state);++ // 先注册 code 等待再开浏览器(已授权的浏览器可能在 openExternal 返回前就完成重定向)。+ const codePromise = new Promise<string>((resolve, reject) => {+ if (abort.signal.aborted) {+ reject(new Error('login_cancelled'));+ return;+ }+ timer = setTimeout(() => reject(new Error('timeout')), LOGIN_TIMEOUT_MS);+ abort.signal.addEventListener('abort', () => reject(new Error('login_cancelled')), {+ once: true,+ });+ listener!.waitForCode(state).then(resolve, reject);+ });+ codePromise.catch(() => {+ /* handled at await site */+ });++ log.info('opening browser for generic oauth', {+ providerId: provider.id,+ port: listener!.port,+ });+ await io.openExternal(authUrl.toString());+ const code = await codePromise;++ const response = await io.fetchImpl(oauth.tokenUrl, {+ method: 'POST',+ headers: { 'content-type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ grant_type: 'authorization_code',+ client_id: oauth.clientId,+ code,+ redirect_uri: redirectUri,+ code_verifier: verifier,+ }).toString(),+ signal: AbortSignal.any([abort.signal, AbortSignal.timeout(TOKEN_EXCHANGE_TIMEOUT_MS)]),+ });+ if (!response.ok) {+ const body = await response.text().catch(() => '');+ throw new Error(`Token exchange failed (${response.status}): ${body.slice(0, 200)}`);+ }+ tok = (await response.json()) as TokenResponse;+ if (!tok.access_token) throw new Error('token 响应缺 access_token');}- const tok = (await res.json()) as TokenResponse;- if (!tok.access_token) throw new Error('token 响应缺 access_token');// 落盘前最后检查:已取消的登录绝不写凭证(同 grok)。if (abort.signal.aborted) throw new Error('login_cancelled');@@ -526,18 +690,18 @@ export async function runGenericOAuthLogin(blobCache.set(provider.id, null);throw new Error('凭证写入本机安全存储失败,请检查系统钥匙串/加密服务后重试');}- listener.succeed(provider.name);+ listener?.succeed(provider.name);log.info('generic oauth login success', { providerId: provider.id, scope: tok.scope });return { ok: true };} catch (err) {const msg = err instanceof Error ? err.message : String(err);- listener.fail(msg);+ listener?.fail(msg);log.warn('generic oauth login failed', { providerId: provider.id, error: msg });return { ok: false, reason: abort.signal.aborted ? 'login_cancelled' : msg };} finally {if (timer) clearTimeout(timer);- listener.close();- if (activeLogins.get(provider.id)?.listener === listener) activeLogins.delete(provider.id);+ listener?.close();+ if (activeLogins.get(provider.id)?.abort === abort) activeLogins.delete(provider.id);}}diff --git a/apps/desktop/src/main/maker-host/provider-diagnostics.ts b/apps/desktop/src/main/maker-host/provider-diagnostics.tsindex b83c2545ac..9474eccf78 100644--- a/apps/desktop/src/main/maker-host/provider-diagnostics.ts+++ b/apps/desktop/src/main/maker-host/provider-diagnostics.ts@@ -14,7 +14,11 @@* provider-route.setCustomProviderKeyReader,host 在 register 时接通)。*/-import type { AgentKind, ProviderWireProtocol } from '@cindy/model-providers';+import {+ appendProviderRequestPath,+ type AgentKind,+ type ProviderWireProtocol,+} from '@cindy/model-providers';import {classifyProviderError,@@ -35,6 +39,8 @@ export interface ProviderProbeSpec {modelId: string;/** 缺省按 agent 保持历史行为。 */wireProtocol?: ProviderWireProtocol;+ /** 非标准推理端点的精确相对路径。 */+ requestPath?: string;/** 用户 API key;缺省 = 不注入鉴权头(端点可能靠自定义 headers 鉴权)。 */apiKey?: string | null;/** 附加请求头(自定义供应商的 headers 配置)。 */@@ -67,16 +73,22 @@ export function setDiagnosticsKeyReader(reader: KeyReader): void {keyReader = reader;}-/** 拼 URL:baseUrl 去尾斜杠 + path。 */-function joinUrl(baseUrl: string, path: string): string {- return baseUrl.replace(/\/+$/, '') + path;+function withoutCredentialHeaders(+ headers: Record<string, string> | undefined,+): Record<string, string> {+ return Object.fromEntries(+ Object.entries(headers ?? {}).filter(([name]) => {+ const normalized = name.toLowerCase();+ return normalized !== 'authorization' && normalized !== 'x-api-key';+ }),+ );}/** 构造探测请求(纯函数,单测直断言)。header 组合与 provider-route 的 api-key-header 分支对齐。 */export function buildProbeRequest(spec: ProviderProbeSpec): { url: string; init: RequestInit } {const headers: Record<string, string> = {'content-type': 'application/json',- ...(spec.headers ?? {}),+ ...(spec.apiKey ? withoutCredentialHeaders(spec.headers) : (spec.headers ?? {})),};if (spec.agent === 'claude-code') {// Anthropic Messages wire。anthropic-version 为兼容端点普遍要求的必带头。@@ -86,7 +98,7 @@ export function buildProbeRequest(spec: ProviderProbeSpec): { url: string; init:headers['authorization'] = `Bearer ${spec.apiKey}`;}return {- url: joinUrl(spec.baseUrl, '/v1/messages'),+ url: appendProviderRequestPath(spec.baseUrl, spec.requestPath ?? '/v1/messages'),init: {method: 'POST',headers,@@ -106,7 +118,7 @@ export function buildProbeRequest(spec: ProviderProbeSpec): { url: string; init:// (“Thinking mode does not support this tool_choice”),会把可达的端点误报成失败。// 工具调用能力交给真实会话验证(Codex 用 tool_choice:'auto',不强制)。return {- url: joinUrl(spec.baseUrl, '/chat/completions'),+ url: appendProviderRequestPath(spec.baseUrl, spec.requestPath ?? '/chat/completions'),init: {method: 'POST',headers,@@ -121,7 +133,7 @@ export function buildProbeRequest(spec: ProviderProbeSpec): { url: string; init:};}return {- url: joinUrl(spec.baseUrl, '/responses'),+ url: appendProviderRequestPath(spec.baseUrl, spec.requestPath ?? '/responses'),init: {method: 'POST',headers,@@ -305,13 +317,26 @@ export function resolveSavedProbeSpec(providerId: string, agent: AgentKind): ProbaseUrl: routing.upstream,modelId: model.id,wireProtocol: routing.wireProtocol,+ requestPath: routing.requestPath,apiKey: null,headers: {- ...(routing.headerOverride ?? {}),+ ...withoutCredentialHeaders(routing.headerOverride),...(oauthToken ? { authorization: `Bearer ${oauthToken}` } : {}),},};}+ if (routing.authStrategy === 'none') {+ return {+ agent,+ baseUrl: routing.upstream,+ modelId: model.id,+ wireProtocol: routing.wireProtocol,+ requestPath: routing.requestPath,+ apiKey: null,+ headers: withoutCredentialHeaders(routing.headerOverride),+ };+ }+ const apiKey = keyReader(providerId, agent);return {agent,baseUrl: routing.upstream,@@ -320,8 +345,13 @@ export function resolveSavedProbeSpec(providerId: string, agent: AgentKind): Pro// 必须带上 wireProtocol,否则 buildProbeRequest 回落到原生 /responses,对 Chat-only 上游// 误报连接失败(真实会话走 resolveSessionRoute 不受影响,探测结论会与真实会话相反)。wireProtocol: routing.wireProtocol,- apiKey: keyReader(providerId, agent),- headers: routing.headerOverride,+ requestPath: routing.requestPath,+ apiKey,+ // 与真实会话路由保持 legacy 兼容:safeStorage 已有 key 时清掉旧凭证头,由 apiKey+ // 重新注入;尚未迁移的 header-only 配置则原样保留,否则“测试连接”会无凭证误报失败。+ headers: apiKey+ ? withoutCredentialHeaders(routing.headerOverride)+ : { ...(routing.headerOverride ?? {}) },};}diff --git a/apps/desktop/src/main/maker-host/provider-model-fetch.ts b/apps/desktop/src/main/maker-host/provider-model-fetch.tsindex 90a60c560d..99bb709766 100644--- a/apps/desktop/src/main/maker-host/provider-model-fetch.ts+++ b/apps/desktop/src/main/maker-host/provider-model-fetch.ts@@ -58,9 +58,22 @@ function sameOrigin(a: string, b: string): boolean {}}+function withoutCredentialHeaders(+ headers: Record<string, string> | undefined,+): Record<string, string> {+ return Object.fromEntries(+ Object.entries(headers ?? {}).filter(([name]) => {+ const normalized = name.toLowerCase();+ return normalized !== 'authorization' && normalized !== 'x-api-key';+ }),+ );+}+/** 构造列模型请求(纯函数,单测直断言)。鉴权头组合与 buildProbeRequest 同口径。 */export function buildModelsFetchRequest(spec: ProviderModelsFetchSpec): { url: string; init: RequestInit } {- const headers: Record<string, string> = { ...(spec.headers ?? {}) };+ const headers: Record<string, string> = spec.apiKey+ ? withoutCredentialHeaders(spec.headers)+ : { ...(spec.headers ?? {}) };if (spec.agent === 'claude-code') {// Anthropic wire 的所有端点(含 GET /v1/models)都要求 anthropic-version,缺失直接 400。headers['anthropic-version'] = headers['anthropic-version'] ?? '2023-06-01';diff --git a/apps/desktop/src/main/maker-host/provider-route.ts b/apps/desktop/src/main/maker-host/provider-route.tsindex 5b73e9fcff..837d1ead34 100644--- a/apps/desktop/src/main/maker-host/provider-route.ts+++ b/apps/desktop/src/main/maker-host/provider-route.ts@@ -82,6 +82,35 @@ const MISSING_PROVIDER_OAUTH_TOKEN = 'xdt-missing-provider-oauth-token';* 在代码层兜底(非 ChatGPT spawn 下这些头不存在,删除为 no-op,无副作用)。*/const CODEX_ACCOUNT_HEADERS = ['chatgpt-account-id', 'openai-beta', 'originator', 'session_id'];+/** 无鉴权上游永远不能收到 agent 子进程自带的订阅凭证。 */+const CLIENT_AUTH_HEADERS = ['authorization', 'x-api-key'];+/** 缺少自定义供应商 key 时覆盖 CLI 凭证的哑值:目标上游应 401,但绝不收到订阅 token。 */+const MISSING_CUSTOM_PROVIDER_API_KEY = 'cindy-missing-custom-provider-api-key';++function withoutClientAuthHeaders(+ headers: Record<string, string> | undefined,+): Record<string, string> {+ const blocked = new Set(CLIENT_AUTH_HEADERS);+ return Object.fromEntries(+ Object.entries(headers ?? {}).filter(([name]) => !blocked.has(name.toLowerCase())),+ );+}++function normalizeLegacyClientAuthHeaders(+ headers: Record<string, string> | undefined,+): Record<string, string> {+ const normalized: Record<string, string> = {};+ const clientAuthHeaders = new Set(CLIENT_AUTH_HEADERS);+ for (const [name, value] of Object.entries(headers ?? {})) {+ const lower = name.toLowerCase();+ normalized[clientAuthHeaders.has(lower) ? lower : name] = value;+ }+ return normalized;+}++function hasHeader(headers: Record<string, string> | undefined, expectedName: string): boolean {+ return Object.keys(headers ?? {}).some((name) => name.toLowerCase() === expectedName);+}/*** 据路由描述符 + 当前网关 key + agent 生成 proxy 路由决策。@@ -102,13 +131,31 @@ export function buildRouteDecision(oauthToken?: string | null,): RoutingDecision | null {switch (routing.authStrategy) {+ case 'none': {+ // 本机 / 自托管无鉴权代理:仍固定路由到所选 upstream,但显式剥掉子进程自带的+ // Claude.ai / ChatGPT 凭证与账号元数据。宁可让代理按匿名请求拒绝,也不能泄漏订阅令牌。+ const headerDelete = new Set([+ ...(routing.headerDelete ?? []),+ ...CLIENT_AUTH_HEADERS,+ ...(agent === 'codex' ? CODEX_ACCOUNT_HEADERS : []),+ ]);+ const headerOverride = withoutClientAuthHeaders(routing.headerOverride);+ return {+ upstreamOverride: routing.upstream,+ ...(Object.keys(headerOverride).length > 0+ ? { headerOverride }+ : {}),+ headerDelete: [...headerDelete],+ };+ }+case 'oauth-token': {// 描述符驱动的通用 OAuth 供应商:上游改到供应商自家端点,鉴权头换成 Runner 持有的// access_token。无 token(未登录/已失效)**也不回落 null**——会话是显式选了这家的,// 回落会让请求带着子进程自带凭证流向默认网关/别家上游(模型跑错上游 + 凭证泄漏);// 与 provider-oauth-header 同口径:置哑 token 仍发往本供应商,宁可上游 401。const headerOverride: Record<string, string> = {- ...(routing.headerOverride ?? {}),+ ...withoutClientAuthHeaders(routing.headerOverride),authorization: `Bearer ${oauthToken || MISSING_PROVIDER_OAUTH_TOKEN}`,};const decision: RoutingDecision = { headerOverride };@@ -130,7 +177,7 @@ export function buildRouteDecision(// 直连供应商自家上游,但子进程 bearer 不属于它(例如 Codex 的 OpenAI OAuth 不能打 xAI)。// 缺 token 时也覆盖成哑 token,宁可让目标上游 401,也不能把原 bearer 泄漏到别家。const headerOverride: Record<string, string> = {- ...(routing.headerOverride ?? {}),+ ...withoutClientAuthHeaders(routing.headerOverride),authorization: `Bearer ${oauthToken || MISSING_PROVIDER_OAUTH_TOKEN}`,};const decision: RoutingDecision = {@@ -157,7 +204,15 @@ export function buildRouteDecision(case 'api-key-header': {// 自定义供应商:上游改到 baseUrl,用用户自己的 api key 覆盖鉴权头,叠加用户自定义 headers。// key 来自 resolve 时注入的 apiKey(不在 catalog 里)。- const headerOverride: Record<string, string> = { ...(routing.headerOverride ?? {}) };+ // 新版凭证由 safeStorage 注入;旧版曾把 API key 直接存进 headerOverride。没有迁移到+ // safeStorage 的 key 时保留旧头,避免升级后所有 legacy 自定义供应商静默掉鉴权。+ // 一旦存在安全存储 key,仍先剥掉旧头再覆盖,防旧凭证与新凭证并存。+ const hasLegacyAuthorization = hasHeader(routing.headerOverride, 'authorization');+ const hasLegacyApiKey = hasHeader(routing.headerOverride, 'x-api-key');+ const hasLegacyCredential = hasLegacyAuthorization || hasLegacyApiKey;+ const headerOverride = apiKey || !hasLegacyCredential+ ? withoutClientAuthHeaders(routing.headerOverride)+ : normalizeLegacyClientAuthHeaders(routing.headerOverride);if (apiKey) {if (agent === 'claude-code') {// cc 子进程在 oauth-spawn 下会带订阅的 `authorization: Bearer <Claude token>`——必须连它一起@@ -169,11 +224,23 @@ export function buildRouteDecision(} else {headerOverride['authorization'] = `Bearer ${apiKey}`;}+ } else {+ // 未配置 key 时,每一种 agent 原生鉴权头都必须有 legacy 值或哑值覆盖。只保留+ // x-api-key 会让 Codex Authorization 穿透;只保留 Authorization 也会让 Claude+ // x-api-key 穿透。+ if (!hasLegacyAuthorization) {+ headerOverride.authorization = `Bearer ${MISSING_CUSTOM_PROVIDER_API_KEY}`;+ }+ if (agent === 'claude-code' && !hasLegacyApiKey) {+ headerOverride['x-api-key'] = MISSING_CUSTOM_PROVIDER_API_KEY;+ }}const decision: RoutingDecision = {};if (Object.keys(headerOverride).length > 0) decision.headerOverride = headerOverride;if (routing.upstream) decision.upstreamOverride = routing.upstream;- if (routing.headerDelete?.length) decision.headerDelete = routing.headerDelete;+ const headerDelete = new Set(routing.headerDelete ?? []);+ if (agent === 'codex') for (const name of CODEX_ACCOUNT_HEADERS) headerDelete.add(name);+ if (headerDelete.size > 0) decision.headerDelete = [...headerDelete];// 自定义供应商必有 upstream → 实际总返回 decision;全空时 passthrough。return decision.headerOverride || decision.upstreamOverride || decision.headerDelete? decision@@ -311,11 +378,30 @@ export function buildLocalHandlerHeaders(route: ResolvedSessionRoute, agent: Ageheaders: Record<string, string>;headerDelete: string[];} {- const headers: Record<string, string> = { ...(route.routing.headerOverride ?? {}) };+ const hostManagedAuth =+ route.routing.authStrategy === 'none'+ || route.routing.authStrategy === 'api-key-header'+ || route.routing.authStrategy === 'oauth-token'+ || route.routing.authStrategy === 'provider-oauth-header';+ const headers: Record<string, string> = hostManagedAuth+ ? withoutClientAuthHeaders(route.routing.headerOverride)+ : { ...(route.routing.headerOverride ?? {}) };const headerDelete = new Set(route.routing.headerDelete ?? []);switch (route.routing.authStrategy) {+ case 'none':+ for (const name of CLIENT_AUTH_HEADERS) headerDelete.add(name);+ break;case 'api-key-header':- if (route.apiKey) headers.authorization = `Bearer ${route.apiKey}`;+ {+ const decision = buildRouteDecision(+ route.routing,+ null,+ agent,+ route.apiKey,+ );+ Object.assign(headers, decision?.headerOverride ?? {});+ for (const name of decision?.headerDelete ?? []) headerDelete.add(name);+ }break;case 'oauth-token':case 'provider-oauth-header':@@ -326,6 +412,10 @@ export function buildLocalHandlerHeaders(route: ResolvedSessionRoute, agent: Agebreak;}if (agent === 'codex') for (const name of CODEX_ACCOUNT_HEADERS) headerDelete.add(name);+ const normalizedDelete = new Set([...headerDelete].map((name) => name.toLowerCase()));+ for (const name of Object.keys(headers)) {+ if (normalizedDelete.has(name.toLowerCase())) delete headers[name];+ }return { headers, headerDelete: [...headerDelete] };}export function resolveSessionRouteDecision(@@ -343,17 +433,23 @@ export function resolveSessionRouteDecision(if (!routingServesWireModel(routing, wireModel)) return null;// 自定义供应商:resolve 时按 provider_key_<id>_<agent> 读出该 runtime 的 API key 注入鉴权头(不在 catalog)。const apiKey = provider?.source === 'user' ? customProviderKeyReader(providerId, agent) : null;+ const withRequestPath = (decision: RoutingDecision | null): RoutingDecision | null =>+ decision && wireModel && routing.requestPath+ ? { ...decision, pathOverride: routing.requestPath }+ : decision;// 通用 OAuth 供应商(oauth-token):从 generic-oauth 内存缓存**同步**读 access_token// (临期刷新在后台单飞,不阻塞路由热路径,规则 10)。if (routing.authStrategy === 'oauth-token') {- return buildRouteDecision(routing, gatewayKey, agent, apiKey, oauthTokenReader(providerId));+ return withRequestPath(+ buildRouteDecision(routing, gatewayKey, agent, apiKey, oauthTokenReader(providerId)),+ );}if (routing.authStrategy !== 'provider-oauth-header') {- return buildRouteDecision(routing, gatewayKey, agent, apiKey);+ return withRequestPath(buildRouteDecision(routing, gatewayKey, agent, apiKey));}return Promise.resolve(providerOAuthTokenReader(providerId, agent))- .then((token) => buildRouteDecision(routing, gatewayKey, agent, apiKey, token))- .catch(() => buildRouteDecision(routing, gatewayKey, agent, apiKey, null));+ .then((token) => withRequestPath(buildRouteDecision(routing, gatewayKey, agent, apiKey, token)))+ .catch(() => withRequestPath(buildRouteDecision(routing, gatewayKey, agent, apiKey, null)));}function providersForModel(modelId: string, agent: AgentKind) {@@ -392,9 +488,13 @@ export function resolveImplicitProviderOAuthRouteDecision(const routing = provider?.routing[agent];if (!provider || !routing || routing.authStrategy !== 'provider-oauth-header') return null;const apiKey = provider.source === 'user' ? customProviderKeyReader(provider.id, agent) : null;+ const withRequestPath = (decision: RoutingDecision | null): RoutingDecision | null =>+ decision && routing.requestPath+ ? { ...decision, pathOverride: routing.requestPath }+ : decision;return Promise.resolve(providerOAuthTokenReader(provider.id, agent))- .then((token) => buildRouteDecision(routing, gatewayKey, agent, apiKey, token))- .catch(() => buildRouteDecision(routing, gatewayKey, agent, apiKey, null));+ .then((token) => withRequestPath(buildRouteDecision(routing, gatewayKey, agent, apiKey, token)))+ .catch(() => withRequestPath(buildRouteDecision(routing, gatewayKey, agent, apiKey, null)));}/**diff --git a/apps/desktop/src/main/maker-host/provider-service.ts b/apps/desktop/src/main/maker-host/provider-service.tsindex 6e209d1a2c..37ab21d422 100644--- a/apps/desktop/src/main/maker-host/provider-service.ts+++ b/apps/desktop/src/main/maker-host/provider-service.ts@@ -60,9 +60,14 @@ export function createProviderService(deps: ProviderServiceDeps): ProviderServic// 自定义(user)供应商:存在于目录即视为「已连接」——用「编辑 / 删除」替代「连接 / 断开」,// 没有独立鉴权握手(密钥缺失则请求失败,但 UI 连接态为已配置)。for (const p of catalog.providers) {+ // 无鉴权供应商无需任何登录或密钥:只要目录声明有效,就可立即参与模型选择。+ // 该规则与 source 无关,覆盖远端目录下发的 built-in/self-hosted 条目。+ if (p.auth.method === 'none') {+ connected[p.id] = true;+ }// 通用 OAuth 供应商(带 auth.oauth 描述符,内置目录下发或用户自建皆同):// 连接态 = 本机是否有凭证 blob(登录过才算连接)。- if (p.auth.method === 'oauth' && p.auth.oauth && !(p.id in connected)) {+ else if (p.auth.method === 'oauth' && p.auth.oauth && !(p.id in connected)) {connected[p.id] = deps.genericOAuthConnected?.(p.id) ?? false;}// API key 形态的自定义(user)供应商:存在于目录即视为「已连接」——用「编辑 / 删除」diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.tsindex b7f6c614ef..2703232a89 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts@@ -4,6 +4,7 @@ import { describe, expect, it, vi } from 'vitest';import {buildNoProviderMessage,createOrcaWorkerCreationService,+ providerRouteRequiresExplicitSelection,type OrcaWorkerCreationDeps,type OrcaWorkerProviderRoutingContext,type OrcaWorkerProviderSnapshot,@@ -16,6 +17,22 @@ import { isActiveWorkerStatus } from '../../../shared/orca-worker-status';const UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;const WORKER_SESSION_ID = '123e4567-e89b-42d3-a456-426614174000';+describe('providerRouteRequiresExplicitSelection', () => {+ it.each(['api-key-header', 'oauth-token', 'none'] as const)(+ 'keeps %s routes pinned to the selected provider',+ (strategy) => {+ expect(providerRouteRequiresExplicitSelection(strategy)).toBe(true);+ },+ );++ it.each(['oauth-passthrough', 'provider-oauth-header', 'gateway-key', undefined] as const)(+ 'does not force an explicit route for %s',+ (strategy) => {+ expect(providerRouteRequiresExplicitSelection(strategy)).toBe(false);+ },+ );+});+function providerRoutingContext(availability: Record<AgentKind, OrcaWorkerProviderSnapshot[]>,): OrcaWorkerProviderRoutingContext {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.tsindex b850eb7703..d0e7d35439 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts@@ -211,12 +211,26 @@ describe('provider:test-connection handler', () => {const result = await harness.invoke(MAKER_INVOKE.PROVIDER_TEST_CONNECTION, {kind: 'adhoc',- spec: { agent: 'claude-code', baseUrl: 'https://x.example', modelId: 'm', apiKey: 'k' },+ spec: {+ agent: 'claude-code',+ baseUrl: 'https://x.example',+ modelId: 'm',+ requestPath: '/tenant/acme/infer?stream=1',+ apiKey: 'k',+ },});expect(result).toMatchObject({ ok: false, code: 'AUTH_INVALID', status: 401 });expect(testConnection).toHaveBeenCalledWith({kind: 'adhoc',- spec: { agent: 'claude-code', baseUrl: 'https://x.example', modelId: 'm', apiKey: 'k', headers: undefined },+ spec: {+ agent: 'claude-code',+ baseUrl: 'https://x.example',+ modelId: 'm',+ wireProtocol: undefined,+ requestPath: '/tenant/acme/infer?stream=1',+ apiKey: 'k',+ headers: undefined,+ },});});@@ -229,6 +243,15 @@ describe('provider:test-connection handler', () => {{ kind: 'adhoc', spec: { agent: 'gemini', baseUrl: 'https://x.example', modelId: 'm' } },{ kind: 'adhoc', spec: { agent: 'codex', baseUrl: 'ftp://x', modelId: 'm' } },{ kind: 'adhoc', spec: { agent: 'codex', baseUrl: 'https://x.example', modelId: '' } },+ {+ kind: 'adhoc',+ spec: {+ agent: 'codex',+ baseUrl: 'https://x.example',+ modelId: 'm',+ requestPath: '/unescaped path',+ },+ },{ kind: 'saved', providerId: '', agent: 'codex' },];for (const input of bad) {diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex 9f3c775d68..024638133d 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -645,6 +645,8 @@ export const MAKER_PUSH = {* 模型选择器 live 刷新)。无 payload;收到即重拉 listProviders。*/PROVIDER_CHANGED: 'maker:provider:changed',+ /** 通用 OAuth Device Grant 的短期验证码进度(仅 renderer 展示,不落盘/不进日志)。 */+ PROVIDER_OAUTH_PROGRESS: 'maker:provider:oauth:progress',/*** 自定义 MCP 服务器增删改后广播(renderer 设置页 McpServersSection refetch)。* 无 payload;收到即重拉 listCustomMcpServers。diff --git a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.tsindex a681733036..8e323742c9 100644--- a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts+++ b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts@@ -1,4 +1,5 @@import type { AgentKind } from '@cindy/maker-core';+import type { AuthStrategy } from '@cindy/model-providers';import { isCredentialModeSwitchBusyError } from '../maker-host/codex-credential-switch.js';import type { DispatchWorkerTaskResult, OrcaWorkerEffort, OrcaWorkerStatus } from './orcaTeamService.js';@@ -61,6 +62,15 @@ export interface OrcaWorkerProviderSnapshot {requiresExplicitRoute?: boolean;}+/** 自带凭证或明确无鉴权的第三方路由都不能回落到 worker/lead 的默认上游。 */+export function providerRouteRequiresExplicitSelection(+ authStrategy: AuthStrategy | undefined,+): boolean {+ return authStrategy === 'api-key-header'+ || authStrategy === 'oauth-token'+ || authStrategy === 'none';+}+/** 同一次 provider registry 快照派生出的可用性与默认模型路由,避免两次读取产生竞态。 */export interface OrcaWorkerProviderRoutingContext {availability: Record<AgentKind, OrcaWorkerProviderSnapshot[]>;diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.tsindex 7d67f60932..5aa8cb169f 100644--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts@@ -14,7 +14,13 @@* handler body 可脱 Electron 用 IpcHarness + 内存 db 直接 invoke 单测(规则 14)。*/-import type { AgentKind, CustomProviderConfig, ProviderPreset, ProviderView } from '@cindy/model-providers';+import {+ isProviderRequestPath,+ type AgentKind,+ type CustomProviderConfig,+ type ProviderPreset,+ type ProviderView,+} from '@cindy/model-providers';import type { LocalCliDetection } from '../../shared/localCliDetect.js';@@ -104,6 +110,7 @@ function parseTestInput(input: unknown): ProviderTestInput | null {: ['openai-responses', 'openai-chat'];if (typeof spec.wireProtocol !== 'string' || !allowed.includes(spec.wireProtocol)) return null;}+ if (spec.requestPath !== undefined && !isProviderRequestPath(spec.requestPath)) return null;return {kind: 'adhoc',spec: {@@ -111,6 +118,7 @@ function parseTestInput(input: unknown): ProviderTestInput | null {baseUrl: spec.baseUrl,modelId: spec.modelId,wireProtocol: spec.wireProtocol as ProviderProbeSpec['wireProtocol'],+ requestPath: spec.requestPath as string | undefined,apiKey: (spec.apiKey as string | null | undefined) ?? null,headers: spec.headers as Record<string, string> | undefined,},diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 2f0fc4ea0d..5aac0faee9 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -333,7 +333,11 @@ import { getAgentIslandService } from '../agent-island/service.js';import { createOrcaLifecycleService, ORCA_WORKER_READY_MESSAGE } from './orcaLifecycleService.js';import { throwOrcaServiceFailure } from './orcaServiceFailure.js';import { createOrcaTeamService, findFocusTargetWorker, type ListWorkerQueuedMessagesResult, type OrcaTeamService, type OrcaWorkerEffort, type WorkerQueuedMessageControlResult } from './orcaTeamService.js';-import { createOrcaWorkerCreationService, normalizeOrcaWorkerLabel } from './orcaWorkerCreationService.js';+import {+ createOrcaWorkerCreationService,+ normalizeOrcaWorkerLabel,+ providerRouteRequiresExplicitSelection,+} from './orcaWorkerCreationService.js';import { registerOrcaWorkerControlHandlers } from './orcaWorkerControlHandlers.js';import {clearOrcaMcpHydrated,@@ -3421,7 +3425,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptionsconst provider = getActiveCatalog().providers.find((p) => p.id === providerId);const oauth = provider?.auth.oauth;if (!provider || !oauth) throw new Error(`provider '${providerId}' has no oauth descriptor`);- const result = await runGenericOAuthLogin({ id: provider.id, name: provider.name }, oauth);+ const result = await runGenericOAuthLogin(+ { id: provider.id, name: provider.name },+ oauth,+ {+ onProgress: (progress) =>+ broadcastToAllWindows(MAKER_PUSH.PROVIDER_OAUTH_PROGRESS, {+ providerId,+ ...progress,+ }),+ },+ );if (result.ok) {// 授权成功后按 agent 自动发现模型(与内置订阅体验统一,用户不必手填模型):// 发现端点 = 描述符显式声明 ?? 由该 runtime 的 baseUrl 推导(…/v1/models)。@@ -5536,8 +5550,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions{ efforts: model.efforts, defaultEffort: model.defaultEffort },]),),- requiresExplicitRoute: provider.routing['claude-code']?.authStrategy === 'api-key-header'- || provider.routing['claude-code']?.authStrategy === 'oauth-token',+ requiresExplicitRoute: providerRouteRequiresExplicitSelection(+ provider.routing['claude-code']?.authStrategy,+ ),})),codex: connectedProvidersForAgent(views, 'codex').map((provider) => ({id: provider.id,@@ -5552,8 +5567,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions{ efforts: model.efforts, defaultEffort: model.defaultEffort },]),),- requiresExplicitRoute: provider.routing.codex?.authStrategy === 'api-key-header'- || provider.routing.codex?.authStrategy === 'oauth-token',+ requiresExplicitRoute: providerRouteRequiresExplicitSelection(+ provider.routing.codex?.authStrategy,+ ),})),},resolveDefaultProviderIdForModel: (agent, model) => (diff --git a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.tsindex 1f20624c6c..67d211fa7f 100644--- a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts+++ b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts@@ -270,6 +270,178 @@ describe('utility one-shot candidates', () => {});});+ it('uses Chat Completions for an explicitly selected openai-chat provider', async () => {+ activeCatalog.mockReturnValue({+ providers: [{+ id: 'chat-only',+ name: 'Chat Only',+ source: 'user',+ agents: ['codex'],+ auth: { method: 'apiKey' },+ routing: {+ codex: {+ upstream: 'https://chat.example/v1',+ wireProtocol: 'openai-chat',+ authStrategy: 'api-key-header',+ },+ },+ models: {+ codex: [{ id: 'chat-model', name: 'Chat Model', contextWindow: 100_000 }],+ },+ }],+ } as never);+ readCustomKey.mockReturnValue('chat-secret');+ fetchMock.mockResolvedValueOnce({+ ok: true,+ text: async () => JSON.stringify({+ choices: [{ message: { content: 'chat result' } }],+ }),+ } as never);++ const result = await requestUtilityText(makerMock(false), 'generate', {+ providerId: 'chat-only',+ agentKind: 'codex',+ model: 'chat-model',+ });++ expect(result).toMatchObject({+ ok: true,+ text: 'chat result',+ transport: 'litellm-chat-completions',+ });+ expect(fetchMock).toHaveBeenCalledWith(+ 'https://chat.example/v1/chat/completions',+ expect.anything(),+ );+ expect(JSON.parse(String(vi.mocked(fetchMock).mock.calls[0]?.[1]?.body))).toMatchObject({+ model: 'chat-model',+ messages: [{ role: 'user', content: 'generate' }],+ });+ });++ it('uses an explicitly configured custom-provider request path', async () => {+ activeCatalog.mockReturnValue({+ providers: [{+ id: 'exact-path',+ name: 'Exact Path',+ source: 'user',+ agents: ['codex'],+ auth: { method: 'none' },+ routing: {+ codex: {+ upstream: 'http://127.0.0.1:4000',+ requestPath: '/tenant/acme/infer?stream=1',+ authStrategy: 'none',+ },+ },+ models: {+ codex: [{ id: 'local-model', name: 'Local Model', contextWindow: 100_000 }],+ },+ }],+ } as never);+ fetchMock.mockResolvedValueOnce({+ ok: true,+ text: async () => 'data: {"type":"response.output_text.delta","delta":"ok"}\ndata: [DONE]\n',+ } as never);+ const result = await requestUtilityText(makerMock(false), 'generate', {+ providerId: 'exact-path',+ agentKind: 'codex',+ model: 'local-model',+ });++ expect(result).toMatchObject({ ok: true, providerId: 'exact-path' });+ expect(fetchMock).toHaveBeenCalledWith(+ 'http://127.0.0.1:4000/tenant/acme/infer?stream=1',+ expect.objectContaining({+ headers: expect.not.objectContaining({+ Authorization: expect.anything(),+ 'x-api-key': expect.anything(),+ }),+ }),+ );+ });++ it('rejects base URL userinfo when applying an exact provider request path', async () => {+ activeCatalog.mockReturnValue({+ providers: [{+ id: 'exact-path-query',+ name: 'Exact Path Query',+ source: 'user',+ agents: ['codex'],+ auth: { method: 'none' },+ routing: {+ codex: {+ upstream: 'https://user:[email protected]/api?tenant=alpha',+ requestPath: '/infer?stream=1&mode=fast',+ authStrategy: 'none',+ },+ },+ models: {+ codex: [{ id: 'local-model', name: 'Local Model', contextWindow: 100_000 }],+ },+ }],+ } as never);++ const result = await requestUtilityText(makerMock(false), 'generate', {+ providerId: 'exact-path-query',+ agentKind: 'codex',+ model: 'local-model',+ });++ expect(result).toMatchObject({+ ok: false,+ attempts: [expect.objectContaining({ providerId: 'exact-path-query', reason: 'request_failed' })],+ });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('uses a legacy header-only custom-provider credential when safeStorage is empty', async () => {+ activeCatalog.mockReturnValue({+ providers: [{+ id: 'legacy-header',+ name: 'Legacy Header',+ source: 'user',+ agents: ['codex'],+ auth: { method: 'apiKey' },+ routing: {+ codex: {+ upstream: 'https://custom.example/v1',+ authStrategy: 'api-key-header',+ headerOverride: {+ Authorization: 'Bearer legacy-secret',+ 'X-Tenant': 'tenant-a',+ },+ },+ },+ models: {+ codex: [{ id: 'legacy-mini', name: 'Legacy Mini', contextWindow: 100_000 }],+ },+ }],+ } as never);+ fetchMock.mockResolvedValueOnce({+ ok: true,+ text: async () =>+ 'data: {"type":"response.output_text.delta","delta":"ok"}\ndata: [DONE]\n',+ } as never);++ const result = await requestUtilityText(makerMock(false), 'generate', {+ providerId: 'legacy-header',+ agentKind: 'codex',+ model: 'legacy-mini',+ });++ expect(result).toMatchObject({ ok: true, providerId: 'legacy-header' });+ expect(fetchMock).toHaveBeenCalledWith(+ 'https://custom.example/v1/responses',+ expect.objectContaining({+ headers: expect.objectContaining({+ Authorization: 'Bearer legacy-secret',+ 'X-Tenant': 'tenant-a',+ }),+ }),+ );+ });+it('does not fall back to XD after an explicitly selected custom provider returns 401', async () => {activeCatalog.mockReturnValue({providers: [{@@ -315,6 +487,12 @@ describe('utility one-shot candidates', () => {'claude-code': {upstream: 'https://custom.example/api',authStrategy: 'api-key-header',+ headerOverride: {+ authorization: 'Bearer stale-lowercase',+ Authorization: 'Bearer stale-uppercase',+ 'X-API-Key': 'stale-key',+ 'x-tenant': 'tenant-a',+ },},},models: {@@ -337,6 +515,10 @@ describe('utility one-shot candidates', () => {const init = fetchMock.mock.calls[0]?.[1] as { headers: Record<string, string> };expect(init.headers['anthropic-version']).toBe('2023-06-01');expect(init.headers['x-api-key']).toBe('custom-secret');+ expect(init.headers.Authorization).toBe('Bearer custom-secret');+ expect(init.headers.authorization).toBeUndefined();+ expect(init.headers['X-API-Key']).toBeUndefined();+ expect(init.headers['x-tenant']).toBe('tenant-a');});it('uses a generic OAuth token for a custom Claude provider without sending x-api-key', async () => {diff --git a/apps/desktop/src/main/utility-model/oneShotCandidates.ts b/apps/desktop/src/main/utility-model/oneShotCandidates.tsindex dbb4077a5f..527979c098 100644--- a/apps/desktop/src/main/utility-model/oneShotCandidates.ts+++ b/apps/desktop/src/main/utility-model/oneShotCandidates.ts@@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto';import { fetch as undiciFetch } from 'undici';import { toSdkModelString, type AgentKind, type Maker } from '@cindy/maker-core';+import { appendProviderRequestPath } from '@cindy/model-providers';import { createLogger } from '../logger.js';import { readClaudeApiKey } from '../maker-host/auth-adapters.js';@@ -215,9 +216,11 @@ async function requestExplicitProviderText(// here: that legacy field may belong to another runtime (for example Codex),// which would silently turn a Claude request into a Codex request.const model = requestedModel || configuredModels[0]?.id || '';- const transport: UtilityModelTransport = agentKind === 'codex'- ? 'codex-responses'- : 'litellm-chat-completions';+ const selectedRouting = agentKind ? provider?.routing[agentKind] : undefined;+ const transport: UtilityModelTransport =+ agentKind === 'codex' && selectedRouting?.wireProtocol !== 'openai-chat'+ ? 'codex-responses'+ : 'litellm-chat-completions';if (!provider || !agentKind || !provider.agents.includes(agentKind)) {return {@@ -271,14 +274,18 @@ async function requestExplicitProviderText(}const routing = provider.routing[agentKind];- if (routing?.authStrategy !== 'api-key-header' && routing?.authStrategy !== 'oauth-token') {+ if (+ routing?.authStrategy !== 'api-key-header'+ && routing?.authStrategy !== 'oauth-token'+ && routing?.authStrategy !== 'none'+ ) {return {ok: false,reason: 'no_candidate',attempts: [{ providerId: provider.id, model, transport, status: 'skipped', reason: 'not_authenticated' }],};}- const authStrategy: 'api-key-header' | 'oauth-token' = routing.authStrategy;+ const authStrategy: 'api-key-header' | 'oauth-token' | 'none' = routing.authStrategy;if (!routing?.upstream) {return {ok: false,@@ -287,10 +294,23 @@ async function requestExplicitProviderText(};}const isOAuth = authStrategy === 'oauth-token';+ const noAuth = authStrategy === 'none';const credential = isOAuth? readCachedGenericOAuthAccessToken(provider.id, provider.auth.oauth)- : readCustomProviderKey(provider.id, agentKind);- if (!credential) {+ : noAuth+ ? null+ : readCustomProviderKey(provider.id, agentKind);+ const hasLegacyHeaderCredential = (+ authStrategy === 'api-key-header'+ && Object.entries(routing.headerOverride ?? {}).some(([key, value]) => {+ const normalized = key.toLowerCase();+ return (+ (normalized === 'authorization' || normalized === 'x-api-key')+ && value.trim().length > 0+ );+ })+ );+ if (!noAuth && !credential && !hasLegacyHeaderCredential) {return {ok: false,reason: 'no_candidate',@@ -320,8 +340,10 @@ async function requestExplicitProviderText(execute: (text, requestOpts) => requestCustomProviderText({agentKind,baseUrl: routing.upstream,+ requestPath: routing.requestPath,+ wireProtocol: routing.wireProtocol,headers: routing.headerOverride,- credential,+ credential: credential ?? '',authStrategy,model,prompt: text,@@ -760,9 +782,11 @@ function parseChatCompletionText(raw: string): string {async function requestCustomProviderText(input: {agentKind: AgentKind;baseUrl: string;+ requestPath?: string;+ wireProtocol?: 'anthropic-messages' | 'openai-responses' | 'openai-chat';headers?: Record<string, string>;credential: string;- authStrategy: 'api-key-header' | 'oauth-token';+ authStrategy: 'api-key-header' | 'oauth-token' | 'none';model: string;prompt: string;maxTokens?: number;@@ -772,30 +796,40 @@ async function requestCustomProviderText(input: {...(input.headers ?? {}),'Content-Type': 'application/json',};- if (input.authStrategy === 'oauth-token') {- // OAuth upstreams must not receive an API key left over from a copied- // header override; some gateways prefer it over Bearer authentication.- // Remove authorization in every casing too, otherwise a copied lowercase- // value can coexist with the canonical `Authorization` header below.+ // safeStorage 有当前凭证时覆盖历史 header;没有时仅 api-key 策略允许保留旧版+ // header-only 配置,以便用户升级后继续可用。OAuth 与 none 仍必须清掉复制进来的凭证头。+ const preserveLegacyApiKeyHeaders =+ input.authStrategy === 'api-key-header' && input.credential.length === 0;+ if (!preserveLegacyApiKeyHeaders) {for (const key of Object.keys(headers)) {const normalized = key.toLowerCase();if (normalized === 'x-api-key' || normalized === 'authorization') delete headers[key];}}- if (input.agentKind === 'codex') {+ if (input.credential) {headers.Authorization = `Bearer ${input.credential}`;- } else {- headers.Authorization = `Bearer ${input.credential}`;- if (input.authStrategy === 'api-key-header') {+ if (input.agentKind === 'claude-code' && input.authStrategy === 'api-key-header') {headers['x-api-key'] = input.credential;}+ }+ if (input.agentKind === 'claude-code') {headers['anthropic-version'] = headers['anthropic-version'] ?? '2023-06-01';}+ const wire: ProviderWire =+ input.agentKind === 'claude-code'+ ? 'anthropic-messages'+ : input.wireProtocol === 'openai-chat'+ ? 'chat-completions'+ : 'responses';return requestProviderHttpText({- wire: input.agentKind === 'codex' ? 'responses' : 'anthropic-messages',- endpoint: input.agentKind === 'codex'- ? joinProxyPath(input.baseUrl, '/responses')- : joinAnthropicMessagesPath(input.baseUrl),+ wire,+ endpoint: input.requestPath+ ? appendProviderRequestPath(input.baseUrl, input.requestPath)+ : wire === 'responses'+ ? joinProxyPath(input.baseUrl, '/responses')+ : wire === 'chat-completions'+ ? joinProxyPath(input.baseUrl, '/chat/completions')+ : joinAnthropicMessagesPath(input.baseUrl),headers,model: input.model,prompt: input.prompt,diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex b5176c5467..2e2e1297f7 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -447,6 +447,7 @@ const fanOutMakerAuthStateChanged = createIpcFanOut('maker:auth:state-changed');const fanOutMakerAuthLoginProgress = createIpcFanOut('maker:auth:login-progress');// 自定义供应商增删改广播 → 各 useProviders 实例 refetch(设置页列表 + 对话模型选择器 live 刷新)。const fanOutMakerProvidersChanged = createIpcFanOut('maker:provider:changed');+const fanOutMakerProviderOAuthProgress = createIpcFanOut('maker:provider:oauth:progress');// 自定义 MCP 服务器增删改广播 → 设置页 McpServersSection refetch。const fanOutMakerMcpChanged = createIpcFanOut('maker:mcp:changed');// 自定义供应商上游错误的结构化广播(payload = { agent, providerId, providerName, code, retryable, status })。@@ -3630,6 +3631,8 @@ contextBridge.exposeInMainWorld('electronAPI', {agent: 'claude-code' | 'codex';baseUrl: string;modelId: string;+ wireProtocol?: import('@cindy/model-providers').ProviderWireProtocol;+ requestPath?: string;apiKey?: string | null;headers?: Record<string, string>;};@@ -3715,6 +3718,7 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('maker:provider:oauth:logout', providerId),providerOAuthCancel: (providerId: string): Promise<{ ok: true }> =>ipcRenderer.invoke('maker:provider:oauth:cancel', providerId),+ onProviderOAuthProgress: fanOutMakerProviderOAuthProgress,/*** renderer → main 单向镜像「模型显示/隐藏」override 整张快照(modelVisibilityPrefs)。* 让 IM /model 在 main 侧复用同一套可见性过滤,与应用内模型列表逐模型一致。diff --git a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsxindex a8b693715d..fc0737eb10 100644--- a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx+++ b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx@@ -197,6 +197,41 @@ describe('AddProviderWizard — preset 直达', () => {);});+ it('editable preset saves the edited base URL and exact request path', async () => {+ const editablePreset = {+ id: 'local-gateway',+ name: 'Local Gateway',+ runtimes: {+ codex: {+ baseUrl: 'http://127.0.0.1:4000/v1',+ baseUrlEditable: true,+ requestPath: '/tenant/acme/infer',+ models: [{ id: 'local-model', name: 'Local model' }],+ },+ },+ };+ vi.mocked(window.electronAPI.maker.listProviderPresets)+ .mockResolvedValueOnce({ presets: [editablePreset] });+ renderWizard('local-gateway');++ const baseUrl = await screen.findByDisplayValue('http://127.0.0.1:4000/v1');+ fireEvent.change(baseUrl, { target: { value: 'http://localhost:11434/custom' } });+ fireEvent.change(screen.getByPlaceholderText('sk-…'), { target: { value: 'local-key' } });+ fireEvent.click(screen.getByText('settings.providers.wizard.next'));++ await waitFor(() => expect(screen.getByText('Local model')).not.toBeNull());+ expect(window.electronAPI.maker.fetchProviderModels).toHaveBeenCalledWith(+ expect.objectContaining({ baseUrl: 'http://localhost:11434/custom' }),+ );+ fireEvent.click(screen.getByText('settings.providers.wizard.finish'));++ await waitFor(() => expect(createCustomProvider).toHaveBeenCalledTimes(1));+ expect(vi.mocked(createCustomProvider).mock.calls[0][0].runtimes.codex).toMatchObject({+ baseUrl: 'http://localhost:11434/custom',+ requestPath: '/tenant/acme/infer',+ });+ });+it('presetId 不存在 → 回落目录第一步', async () => {renderWizard('nonexistent');diff --git a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsxindex 6dcfadcd21..013d242ebe 100644--- a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx+++ b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx@@ -57,11 +57,38 @@ interface AddProviderWizardProps {type Selection ={ kind: 'oauth'; provider: ProviderView } | { kind: 'preset'; preset: ProviderPreset };+type PresetBaseUrls = Partial<Record<AgentKind, string>>;+const AGENT_LABEL: Record<AgentKind, string> = {'claude-code': 'Claude Code',codex: 'Codex',};+function presetRuntimeBaseUrl(+ preset: ProviderPreset,+ agent: AgentKind,+ edited: PresetBaseUrls,+): string {+ const runtime = preset.runtimes[agent];+ if (!runtime) return '';+ return runtime.baseUrlEditable+ ? (edited[agent] ?? runtime.baseUrl).trim()+ : runtime.baseUrl;+}++function isValidEditablePresetBaseUrl(value: string): boolean {+ try {+ const url = new URL(value);+ return (+ (url.protocol === 'http:' || url.protocol === 'https:')+ && !url.username+ && !url.password+ );+ } catch {+ return false;+ }+}+/*** bespoke OAuth 渠道的官方 API 预设——授权步「改用 API Key 接入」的替代路径* (API 用户没有订阅,OAuth 授权对其是错误路径)。@@ -253,6 +280,7 @@ export function AddProviderWizard({// 预设表单态const [name, setName] = useState('');const [apiKey, setApiKey] = useState('');+ const [presetBaseUrls, setPresetBaseUrls] = useState<PresetBaseUrls>({});const [saving, setSaving] = useState(false);const [loggingIn, setLoggingIn] = useState(false);// Step 3 拉取态@@ -327,6 +355,12 @@ export function AddProviderWizard({setSel({ kind: 'preset', preset });setName(presetDisplayName(preset, i18n.language));setApiKey('');+ setPresetBaseUrls(+ Object.fromEntries(+ (Object.keys(preset.runtimes) as AgentKind[])+ .map((agent) => [agent, preset.runtimes[agent]?.baseUrl ?? '']),+ ) as PresetBaseUrls,+ );setStep(2);},[i18n.language],@@ -434,6 +468,12 @@ export function AddProviderWizard({const startFetch = useCallback(async () => {if (!sel || sel.kind !== 'preset') return;const preset = sel.preset;+ const editableBaseUrlsValid = (Object.keys(preset.runtimes) as AgentKind[]).every((agent) => {+ const rt = preset.runtimes[agent];+ return !rt?.baseUrlEditable+ || isValidEditablePresetBaseUrl(presetRuntimeBaseUrl(preset, agent, presetBaseUrls));+ });+ if (!editableBaseUrlsValid) return;// 预设推荐模型先入清单(预勾);归属 = 预设里列出该模型的全部 runtime。const initial = new Map<string,@@ -463,7 +503,7 @@ export function AddProviderWizard({try {const r = await window.electronAPI.maker.fetchProviderModels({agent,- baseUrl: rt.baseUrl,+ baseUrl: presetRuntimeBaseUrl(preset, agent, presetBaseUrls),modelsUrl: rt.modelsUrl ?? null,apiKey: apiKey.trim() || null,...(rt.headers ? { headers: rt.headers } : {}),@@ -494,7 +534,7 @@ export function AddProviderWizard({});// 全部端点都失败才算失败(单端失败仍可按另一端 + 预设推荐完成)。setFetchState({ status: 'done', failed: !results.some((r) => r.ok) });- }, [sel, apiKey]);+ }, [sel, apiKey, presetBaseUrls]);// ── 完成创建(预设)────────────────────────────────────────────────────const handleFinish = useCallback(async () => {@@ -535,8 +575,9 @@ export function AddProviderWizard({});if (agentModels.length === 0) continue;runtimes[agent] = {- baseUrl: rt.baseUrl,+ baseUrl: presetRuntimeBaseUrl(preset, agent, presetBaseUrls),...(rt.wireProtocol ? { wireProtocol: rt.wireProtocol } : {}),+ ...(rt.requestPath ? { requestPath: rt.requestPath } : {}),models: agentModels,...(rt.headers ? { headers: rt.headers } : {}),...(rt.modelsUrl ? { modelsUrl: rt.modelsUrl } : {}),@@ -563,7 +604,7 @@ export function AddProviderWizard({} finally {setSaving(false);}- }, [sel, picks, name, apiKey, providers, onDone, t, i18n.language]);+ }, [sel, picks, name, apiKey, presetBaseUrls, providers, onDone, t, i18n.language]);// ── 步骤指示(OAuth 路径只有 2 步)─────────────────────────────────────const totalSteps = sel?.kind === 'preset' ? 3 : 2;@@ -576,6 +617,15 @@ export function AddProviderWizard({// 预设单 runtime 时的「仅支持 X」说明(数据驱动的静态灰,见文件头注释)。const presetAgents =sel?.kind === 'preset' ? (Object.keys(sel.preset.runtimes) as AgentKind[]) : [];+ const presetBaseUrlsValid =+ sel?.kind !== 'preset'+ || presetAgents.every((agent) => {+ const rt = sel.preset.runtimes[agent];+ return !rt?.baseUrlEditable+ || isValidEditablePresetBaseUrl(+ presetRuntimeBaseUrl(sel.preset, agent, presetBaseUrls),+ );+ });const presetSingleAgentNote =sel?.kind === 'preset' && presetAgents.length === 1? t('settings.providers.wizard.onlyAgentNote', { agent: AGENT_LABEL[presetAgents[0]] })@@ -872,12 +922,43 @@ export function AddProviderWizard({}}/></div>- {/* baseUrl 由预设携带,只读展示(要改走保存后的编辑表单)。+ {/* 官方渠道 URL 只读;本机/自托管预设可在创建时改 host/port。codex + openai-chat 上游标注「Cindy 桥接」,让用户明确该通道是协议转换而非原生。 */}- <div className="flex flex-col gap-1">+ <div className="flex flex-col gap-2">{presetAgents.map((agent) => {const rt = sel.preset.runtimes[agent];const bridged = agent === 'codex' && rt?.wireProtocol === 'openai-chat';+ if (rt?.baseUrlEditable) {+ const value = presetBaseUrls[agent] ?? rt.baseUrl;+ const valid = isValidEditablePresetBaseUrl(value.trim());+ return (+ <label key={agent} className="flex flex-col gap-1.5">+ <span className="text-12 font-medium" style={{ color: 'var(--text-secondary)' }}>+ {t('settings.providers.custom.fields.baseUrl')} · {AGENT_LABEL[agent]}+ </span>+ <input+ type="url"+ value={value}+ onChange={(event) => setPresetBaseUrls((prev) => ({+ ...prev,+ [agent]: event.target.value,+ }))}+ aria-invalid={!valid}+ className="h-9 rounded-full border px-4 font-mono text-12 outline-none focus:ring-2 focus:ring-[var(--focus-ring)]"+ style={{+ borderColor: valid ? 'var(--border-default)' : 'var(--status-error)',+ backgroundColor: 'var(--surface-elevated)',+ color: 'var(--settings-section-title)',+ }}+ />+ {bridged && (+ <span className="text-11" style={{ color: 'var(--text-tertiary)' }}>+ {t('settings.providers.wizard.bridgedNote')}+ </span>+ )}+ </label>+ );+ }return (<spankey={agent}@@ -1041,10 +1122,12 @@ export function AddProviderWizard({<buttontype="button"onClick={() => void startFetch()}- disabled={apiKey.trim().length === 0}+ disabled={apiKey.trim().length === 0 || !presetBaseUrlsValid}className={cn('flex h-9 items-center justify-center rounded-full px-5 text-13 font-medium transition-opacity',- apiKey.trim().length === 0 ? 'cursor-not-allowed opacity-50' : 'hover:opacity-90',+ apiKey.trim().length === 0 || !presetBaseUrlsValid+ ? 'cursor-not-allowed opacity-50'+ : 'hover:opacity-90',)}style={{ backgroundColor: 'var(--accent-cta-bg)', color: 'var(--surface-on-card)' }}>diff --git a/apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx b/apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsxnew file mode 100644index 0000000000..a3fabbaee3--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx@@ -0,0 +1,104 @@+import { Copy, ExternalLink } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { toast } from '@/lib/toast';+import type { ProviderOAuthDeviceCode } from '@/hooks/useProviderOAuthDeviceCode';++export function OAuthDeviceCodeCard({+ deviceCode,+}: {+ deviceCode?: ProviderOAuthDeviceCode | null;+}) {+ const { t } = useTranslation();+ const verificationHost = (() => {+ if (!deviceCode) return '';+ try {+ return new URL(deviceCode.verificationUrl).hostname;+ } catch {+ return '';+ }+ })();++ return (+ <div+ aria-live="polite"+ className="flex flex-col gap-3 rounded-xl border p-3"+ style={{+ backgroundColor: 'var(--surface-card-ivory)',+ borderColor: 'var(--border-default)',+ }}+ >+ {deviceCode ? (+ <>+ <span className="text-12" style={{ color: 'var(--text-secondary)' }}>+ {t('settings.providers.wizard.deviceCodePrompt')}+ </span>+ <code+ className="select-all text-20 font-semibold tracking-[0.16em]"+ style={{ color: 'var(--text-primary)' }}+ >+ {deviceCode.userCode}+ </code>+ <div className="flex flex-wrap items-center gap-2">+ <button+ type="button"+ onClick={() => {+ void Promise.resolve()+ .then(() => navigator.clipboard.writeText(deviceCode.userCode))+ .then(() =>+ toast.success(t('settings.providers.wizard.deviceCodeCopied')),+ )+ .catch(() =>+ toast.error(t('settings.providers.wizard.deviceCodeCopyFailed')),+ );+ }}+ className="flex h-8 items-center gap-1.5 rounded-full border px-3 text-12 font-medium transition-colors hover:bg-[var(--surface-hover)]"+ style={{+ borderColor: 'var(--settings-btn-secondary-border)',+ color: 'var(--settings-btn-secondary-text)',+ }}+ >+ <Copy size={13} />+ {t('settings.providers.wizard.copyDeviceCode')}+ </button>+ <button+ type="button"+ onClick={() => {+ void window.electronAPI+ .openExternal(deviceCode.verificationUrl)+ .then((result) => {+ if (!result.success) {+ toast.error(t('settings.providers.wizard.verificationPageOpenFailed'));+ }+ })+ .catch(() =>+ toast.error(t('settings.providers.wizard.verificationPageOpenFailed')),+ );+ }}+ className="flex h-8 items-center gap-1.5 rounded-full border px-3 text-12 font-medium transition-colors hover:bg-[var(--surface-hover)]"+ style={{+ borderColor: 'var(--settings-btn-secondary-border)',+ color: 'var(--settings-btn-secondary-text)',+ }}+ >+ <ExternalLink size={13} />+ {t('settings.providers.wizard.openVerificationPage')}+ {verificationHost && (+ <span className="font-normal" style={{ color: 'var(--text-tertiary)' }}>+ · {verificationHost}+ </span>+ )}+ </button>+ </div>+ <span className="text-11" style={{ color: 'var(--text-tertiary)' }}>+ {t('settings.providers.wizard.deviceCodeWaiting')}+ </span>+ </>+ ) : (+ <span className="text-12" style={{ color: 'var(--text-secondary)' }}>+ {t('settings.providers.wizard.preparingDeviceCode')}+ </span>+ )}+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsxindex c25ac9fcf1..df2ec94e87 100644--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx@@ -29,11 +29,12 @@ import { useApiKey } from '@/hooks/useApiKey';import { useModelAccessStatus } from '@/hooks/useModelAccessStatus';import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';import { useSignInToCindy } from '@/hooks/useSignInToCindy';+import { useProviderOAuthDeviceCode } from '@/hooks/useProviderOAuthDeviceCode';import { toast } from '@/lib/toast';import {appendDiscoveredCustomProviderModels,- customProviderModelConfigFromCatalogModel,deleteCustomProvider,+ providerViewToCustomProviderConfig,readCustomProviderKey,updateCustomProvider,} from '@/lib/customProviders';@@ -44,6 +45,7 @@ import {} from '@/lib/providerSubtitle';import { CustomProviderDialog } from './CustomProviderDialog';import { AddProviderWizard, type WizardEntry } from './AddProviderWizard';+import { OAuthDeviceCodeCard } from './OAuthDeviceCodeCard';import { buildUnionRows, UnifiedModelList } from './UnifiedModelList';import { AnthropicMark } from '@/components/icons/AnthropicMark';import { OpenAIMark } from '@/components/icons/OpenAIMark';@@ -555,9 +557,15 @@ function GenericOAuthHeader({const [busy, setBusy] = useState(false);const [loggingIn, setLoggingIn] = useState(false);const connected = provider.connected;+ const deviceFlow = provider.auth.oauth?.flow === 'device-code';+ const { deviceCode, clearDeviceCode, beginOwnedLogin } = useProviderOAuthDeviceCode(+ deviceFlow ? provider.id : null,+ );const handleLogin = useCallback(async () => {+ clearDeviceCode();setLoggingIn(true);+ const finishOwnedLogin = beginOwnedLogin();try {const r = await window.electronAPI.maker.providerOAuthLogin(provider.id);if (r.ok) {@@ -573,9 +581,10 @@ function GenericOAuthHeader({} catch {toast.error(t('settings.providers.genericOAuth.toast.loginFailed', { name: provider.name }));} finally {+ finishOwnedLogin();setLoggingIn(false);}- }, [onChanged, provider.id, provider.name, t]);+ }, [beginOwnedLogin, clearDeviceCode, onChanged, provider.id, provider.name, t]);const handleLogout = useCallback(async () => {const confirmed = await confirm({@@ -611,11 +620,18 @@ function GenericOAuthHeader({) : (<PillButtonlabel={- loggingIn ? t('settings.providers.button.cancel') : t('settings.providers.button.authorize')+ loggingIn+ ? t('settings.providers.button.cancel')+ : t(+ deviceFlow+ ? 'settings.providers.wizard.authorizeWithDeviceCode'+ : 'settings.providers.button.authorize',+ )}onClick={() => {if (loggingIn) {void window.electronAPI.maker.providerOAuthCancel(provider.id);+ clearDeviceCode();setLoggingIn(false);} else {void handleLogin();@@ -623,6 +639,8 @@ function GenericOAuthHeader({}}/>);+ const detail =+ loggingIn && deviceFlow ? <OAuthDeviceCodeCard deviceCode={deviceCode} /> : undefined;return (<DetailHeader@@ -631,6 +649,7 @@ function GenericOAuthHeader({subtitle={t('settings.providers.genericOAuth.subtitle')}trailing={trailing}provider={provider}+ detail={detail}/>);}@@ -817,32 +836,6 @@ function XdGatewayHeader({// 自定义供应商详情头 —— 编辑 / 删除;OAuth 形态另有授权/登出。// ----------------------------------------------------------------------------/** ProviderView → 编辑表单用的 CustomProviderConfig(per-runtime,不含密钥)。 */-function providerViewToConfig(p: ProviderView): CustomProviderConfig {- const runtimes: CustomProviderConfig['runtimes'] = {};- for (const agent of p.agents) {- const routing = p.routing[agent];- const models = p.models[agent] ?? [];- runtimes[agent] = {- baseUrl: routing?.upstream ?? '',- ...(routing?.wireProtocol ? { wireProtocol: routing.wireProtocol } : {}),- models: models.map(customProviderModelConfigFromCatalogModel),- ...(routing?.headerOverride && Object.keys(routing.headerOverride).length > 0- ? { headers: { ...routing.headerOverride } }- : {}),- ...(routing?.modelsUrl ? { modelsUrl: routing.modelsUrl } : {}),- };- }- return {- id: p.id,- name: p.name,- ...(p.auth.method === 'oauth' && p.auth.oauth- ? { auth: { method: 'oauth' as const, oauth: p.auth.oauth } }- : {}),- runtimes,- };-}-function CustomProviderHeader({provider,onEdit,@@ -855,6 +848,10 @@ function CustomProviderHeader({const { t } = useTranslation();const [loggingIn, setLoggingIn] = useState(false);const isOAuth = provider.auth.method === 'oauth' && !!provider.auth.oauth;+ const deviceFlow = provider.auth.oauth?.flow === 'device-code';+ const { deviceCode, clearDeviceCode, beginOwnedLogin } = useProviderOAuthDeviceCode(+ deviceFlow ? provider.id : null,+ );const handleOAuthClick = useCallback(async () => {if (provider.connected) {try {@@ -871,10 +868,13 @@ function CustomProviderHeader({}if (loggingIn) {void window.electronAPI.maker.providerOAuthCancel(provider.id);+ clearDeviceCode();setLoggingIn(false);return;}+ clearDeviceCode();setLoggingIn(true);+ const finishOwnedLogin = beginOwnedLogin();try {const r = await window.electronAPI.maker.providerOAuthLogin(provider.id);if (r.ok)@@ -887,9 +887,10 @@ function CustomProviderHeader({} catch {toast.error(t('settings.providers.genericOAuth.toast.loginFailed', { name: provider.name }));} finally {+ finishOwnedLogin();setLoggingIn(false);}- }, [loggingIn, provider.connected, provider.id, provider.name, t]);+ }, [beginOwnedLogin, clearDeviceCode, loggingIn, provider.connected, provider.id, provider.name, t]);const trailing = (<div className="flex shrink-0 items-center gap-1">@@ -900,7 +901,11 @@ function CustomProviderHeader({? t('settings.providers.button.disconnect'): loggingIn? t('settings.providers.button.cancel')- : t('settings.providers.button.authorize')+ : t(+ deviceFlow+ ? 'settings.providers.wizard.authorizeWithDeviceCode'+ : 'settings.providers.button.authorize',+ )}onClick={() => void handleOAuthClick()}/>@@ -925,6 +930,9 @@ function CustomProviderHeader({trailing={trailing}provider={provider}badge={<CustomTag label={t('settings.providers.custom.tag')} />}+ detail={+ loggingIn && deviceFlow ? <OAuthDeviceCodeCard deviceCode={deviceCode} /> : undefined+ }/>);}@@ -1251,7 +1259,7 @@ export function ProvidersSection() {async (p: ProviderView) => {setRefreshingModels(true);try {- const config = providerViewToConfig(p);+ const config = providerViewToCustomProviderConfig(p);let added = 0;let anyOk = false;for (const agent of p.agents) {@@ -1301,7 +1309,7 @@ export function ProvidersSection() {return (<CustomProviderHeaderprovider={p}- onEdit={() => setDialog({ mode: 'edit', config: providerViewToConfig(p) })}+ onEdit={() => setDialog({ mode: 'edit', config: providerViewToCustomProviderConfig(p) })}onDelete={() => void handleDelete(p)}/>);diff --git a/apps/desktop/src/renderer/hooks/__tests__/useProviderOAuthDeviceCode.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useProviderOAuthDeviceCode.test.tsnew file mode 100644index 0000000000..c7ed0cb850--- /dev/null+++ b/apps/desktop/src/renderer/hooks/__tests__/useProviderOAuthDeviceCode.test.ts@@ -0,0 +1,95 @@+// @vitest-environment jsdom++import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useProviderOAuthDeviceCode } from '../useProviderOAuthDeviceCode';++describe('useProviderOAuthDeviceCode', () => {+ const unsubscribe = vi.fn();+ const cancel = vi.fn(async () => ({ ok: true as const }));+ let listener: ((progress: {+ providerId: string;+ phase: 'device-code';+ verificationUrl: string;+ userCode: string;+ expiresAt?: number;+ }) => void) | null = null;++ beforeEach(() => {+ unsubscribe.mockReset();+ cancel.mockReset();+ cancel.mockResolvedValue({ ok: true });+ listener = null;+ Object.assign(window, {+ electronAPI: {+ maker: {+ providerOAuthCancel: cancel,+ onProviderOAuthProgress: vi.fn((next) => {+ listener = next;+ return unsubscribe;+ }),+ },+ },+ });+ });++ it('keeps only matching progress in memory', () => {+ const { result } = renderHook(() => useProviderOAuthDeviceCode('provider-a'));++ act(() => {+ listener?.({+ providerId: 'provider-b',+ phase: 'device-code',+ verificationUrl: 'https://example.com/b',+ userCode: 'BBBB',+ });+ listener?.({+ providerId: 'provider-a',+ phase: 'device-code',+ verificationUrl: 'https://example.com/a',+ userCode: 'AAAA',+ expiresAt: 123,+ });+ });++ expect(result.current.deviceCode).toEqual({+ verificationUrl: 'https://example.com/a',+ userCode: 'AAAA',+ expiresAt: 123,+ });+ });++ it('unsubscribes without cancelling a login observed from another view', () => {+ const { rerender, unmount } = renderHook(+ ({ providerId }) => useProviderOAuthDeviceCode(providerId),+ { initialProps: { providerId: 'provider-a' as string | null } },+ );++ rerender({ providerId: 'provider-b' });+ expect(unsubscribe).toHaveBeenCalledTimes(1);+ expect(cancel).not.toHaveBeenCalled();++ unmount();+ expect(unsubscribe).toHaveBeenCalledTimes(2);+ expect(cancel).not.toHaveBeenCalled();+ });++ it('cancels only a login started by this hook when its provider is switched', () => {+ const { result, rerender, unmount } = renderHook(+ ({ providerId }) => useProviderOAuthDeviceCode(providerId),+ { initialProps: { providerId: 'provider-a' as string | null } },+ );++ result.current.beginOwnedLogin();+ rerender({ providerId: 'provider-b' });+ expect(cancel).toHaveBeenCalledOnce();+ expect(cancel).toHaveBeenCalledWith('provider-a');++ result.current.beginOwnedLogin();+ const finish = result.current.beginOwnedLogin();+ finish();+ unmount();+ expect(cancel).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/renderer/hooks/useProviderOAuthDeviceCode.ts b/apps/desktop/src/renderer/hooks/useProviderOAuthDeviceCode.tsnew file mode 100644index 0000000000..139df28823--- /dev/null+++ b/apps/desktop/src/renderer/hooks/useProviderOAuthDeviceCode.ts@@ -0,0 +1,47 @@+import { useCallback, useEffect, useRef, useState } from 'react';++export interface ProviderOAuthDeviceCode {+ verificationUrl: string;+ userCode: string;+ expiresAt?: number;+}++/**+ * 订阅某个通用 OAuth 供应商的 Device Grant 短期代码。+ * 代码只在组件内存中保留;切换供应商、取消或卸载都会清空。+ */+export function useProviderOAuthDeviceCode(providerId: string | null) {+ const [deviceCode, setDeviceCode] = useState<ProviderOAuthDeviceCode | null>(null);+ const ownedLoginRef = useRef<{ providerId: string; token: symbol } | null>(null);++ useEffect(() => {+ setDeviceCode(null);+ if (!providerId) return undefined;+ const unsubscribe = window.electronAPI.maker.onProviderOAuthProgress((progress) => {+ if (progress.providerId !== providerId || progress.phase !== 'device-code') return;+ setDeviceCode({+ verificationUrl: progress.verificationUrl,+ userCode: progress.userCode,+ expiresAt: progress.expiresAt,+ });+ });+ return () => {+ unsubscribe();+ if (ownedLoginRef.current?.providerId === providerId) {+ ownedLoginRef.current = null;+ void window.electronAPI.maker.providerOAuthCancel(providerId).catch(() => undefined);+ }+ };+ }, [providerId]);++ const beginOwnedLogin = useCallback(() => {+ if (!providerId) return () => undefined;+ const owned = { providerId, token: Symbol(providerId) };+ ownedLoginRef.current = owned;+ return () => {+ if (ownedLoginRef.current === owned) ownedLoginRef.current = null;+ };+ }, [providerId]);+ const clearDeviceCode = useCallback(() => setDeviceCode(null), []);+ return { deviceCode, clearDeviceCode, beginOwnedLogin };+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 44eb3b149d..e437c219ac 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1357,6 +1357,15 @@"customMeta": "Connect any OpenAI / Anthropic compatible source","pickHint": "The sign-in method is defined by each provider; OAuth endpoints and base URLs come from presets — nothing to fill in by hand.","oauthDesc": "Authorize your subscription in the browser — no API key needed",+ "authorizeWithDeviceCode": "Use device code",+ "preparingDeviceCode": "Preparing a device code…",+ "deviceCodePrompt": "Enter this one-time device code on the verification page:",+ "deviceCodeWaiting": "Keep this window open while you complete authorization.",+ "copyDeviceCode": "Copy code",+ "openVerificationPage": "Open verification page",+ "deviceCodeCopied": "Device code copied",+ "deviceCodeCopyFailed": "Couldn't copy the device code",+ "verificationPageOpenFailed": "Couldn't open the verification page","authorizedToast": "Connected {{name}}","authorizeFailed": "Failed to authorize {{name}}. Please try again","nameLabel": "Display name",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 11d8be3a56..e956a3079e 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1356,6 +1356,15 @@"customMeta": "OpenAI / Anthropic 互換の任意のモデルソースを接続","pickHint": "認証方式はプロバイダーの定義で決まります。OAuth エンドポイントとベース URL はプリセットに含まれ、手入力は不要です。","oauthDesc": "ブラウザでサブスクリプション認証を完了します。API キーは不要です",+ "authorizeWithDeviceCode": "デバイスコードを使用",+ "preparingDeviceCode": "デバイスコードを準備しています…",+ "deviceCodePrompt": "認証ページで、次のワンタイムデバイスコードを入力してください:",+ "deviceCodeWaiting": "認証が完了するまで、このウィンドウを開いたままにしてください。",+ "copyDeviceCode": "コードをコピー",+ "openVerificationPage": "認証ページを開く",+ "deviceCodeCopied": "デバイスコードをコピーしました",+ "deviceCodeCopyFailed": "デバイスコードをコピーできませんでした",+ "verificationPageOpenFailed": "認証ページを開けませんでした","authorizedToast": "「{{name}}」に接続しました","authorizeFailed": "「{{name}}」の認証に失敗しました。もう一度お試しください","nameLabel": "表示名",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 6f65dd9aad..02903573b7 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1356,6 +1356,15 @@"customMeta": "OpenAI / Anthropic 호환 모델 소스를 연결","pickHint": "인증 방식은 제공자 정의에 따라 결정됩니다. OAuth 엔드포인트와 기본 URL은 프리셋에 포함되어 직접 입력할 필요가 없습니다.","oauthDesc": "브라우저에서 구독 인증을 완료합니다. API 키가 필요 없습니다",+ "authorizeWithDeviceCode": "기기 코드 사용",+ "preparingDeviceCode": "기기 코드를 준비하는 중…",+ "deviceCodePrompt": "인증 페이지에 다음 일회용 기기 코드를 입력하세요:",+ "deviceCodeWaiting": "인증이 완료될 때까지 이 창을 열어 두세요.",+ "copyDeviceCode": "코드 복사",+ "openVerificationPage": "인증 페이지 열기",+ "deviceCodeCopied": "기기 코드가 복사되었습니다",+ "deviceCodeCopyFailed": "기기 코드를 복사하지 못했습니다",+ "verificationPageOpenFailed": "인증 페이지를 열지 못했습니다","authorizedToast": "{{name}}에 연결되었습니다","authorizeFailed": "{{name}} 인증에 실패했습니다. 다시 시도해 주세요","nameLabel": "표시 이름",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 2b567878ca..92c9ff0c91 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1356,6 +1356,15 @@"customMeta": "接入任意 OpenAI / Anthropic 兼容的模型来源","pickHint": "鉴权方式由供应商定义决定;OAuth 端点与基础 URL 由预设携带,无需手填。","oauthDesc": "通过浏览器完成订阅授权,无需 API Key",+ "authorizeWithDeviceCode": "使用设备码",+ "preparingDeviceCode": "正在生成设备码…",+ "deviceCodePrompt": "请在验证页面输入以下一次性设备码:",+ "deviceCodeWaiting": "完成授权前请保持此窗口开启。",+ "copyDeviceCode": "复制设备码",+ "openVerificationPage": "打开验证页面",+ "deviceCodeCopied": "设备码已复制",+ "deviceCodeCopyFailed": "设备码复制失败",+ "verificationPageOpenFailed": "无法打开验证页面","authorizedToast": "已连接「{{name}}」","authorizeFailed": "「{{name}}」授权失败,请重试","nameLabel": "显示名称",diff --git a/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts b/apps/desktop/src/renderer/lib/__tests__/customProviders.test.tsindex 7e4b603704..df0a98a35a 100644--- a/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts@@ -3,8 +3,10 @@ import { describe, expect, it } from 'vitest';import {appendDiscoveredCustomProviderModels,customProviderModelConfigFromCatalogModel,+ providerViewToCustomProviderConfig,replaceCustomProviderModelId,} from '../customProviders';+import type { ProviderView } from '@cindy/model-providers';describe('replaceCustomProviderModelId', () => {it('drops hidden metadata when the model id changes', () => {@@ -66,6 +68,53 @@ describe('customProviderModelConfigFromCatalogModel', () => {});});+describe('providerViewToCustomProviderConfig', () => {+ it('preserves no-auth and exact request-path fields through the edit round trip', () => {+ const provider = {+ id: 'local-chat',+ name: 'Local Chat',+ source: 'user',+ agents: ['codex'],+ auth: { method: 'none' },+ access: { kind: 'api' },+ routing: {+ codex: {+ upstream: 'http://127.0.0.1:4000/v1',+ authStrategy: 'none',+ wireProtocol: 'openai-chat',+ requestPath: '/tenant/acme/infer?stream=1',+ modelsUrl: 'http://127.0.0.1:4000/v1/models',+ },+ },+ models: {+ codex: [{+ id: 'local-model',+ name: 'Local Model',+ contextWindow: 200_000,+ efforts: [],+ defaultEffort: null,+ }],+ },+ connected: true,+ } satisfies ProviderView;++ expect(providerViewToCustomProviderConfig(provider)).toEqual({+ id: 'local-chat',+ name: 'Local Chat',+ auth: { method: 'none' },+ runtimes: {+ codex: {+ baseUrl: 'http://127.0.0.1:4000/v1',+ requestPath: '/tenant/acme/infer?stream=1',+ wireProtocol: 'openai-chat',+ modelsUrl: 'http://127.0.0.1:4000/v1/models',+ models: [{ id: 'local-model', name: 'Local Model' }],+ },+ },+ });+ });+});+describe('appendDiscoveredCustomProviderModels', () => {it('only appends unknown models and defaults them to hidden', () => {const result = appendDiscoveredCustomProviderModels(diff --git a/apps/desktop/src/renderer/lib/customProviders.ts b/apps/desktop/src/renderer/lib/customProviders.tsindex d30d11627e..6e5deb4db2 100644--- a/apps/desktop/src/renderer/lib/customProviders.ts+++ b/apps/desktop/src/renderer/lib/customProviders.ts@@ -17,6 +17,7 @@ import type {AgentKind,CatalogModel,CustomProviderConfig,+ ProviderView,ProviderRuntimeModelConfig,} from '@cindy/model-providers';@@ -54,6 +55,35 @@ export function customProviderModelConfigFromCatalogModel(};}+/** ProviderView → 编辑表单配置;必须无损保留所有非密钥路由/鉴权字段。 */+export function providerViewToCustomProviderConfig(p: ProviderView): CustomProviderConfig {+ const runtimes: CustomProviderConfig['runtimes'] = {};+ for (const agent of p.agents) {+ const routing = p.routing[agent];+ const models = p.models[agent] ?? [];+ runtimes[agent] = {+ baseUrl: routing?.upstream ?? '',+ ...(routing?.requestPath ? { requestPath: routing.requestPath } : {}),+ ...(routing?.wireProtocol ? { wireProtocol: routing.wireProtocol } : {}),+ models: models.map(customProviderModelConfigFromCatalogModel),+ ...(routing?.headerOverride && Object.keys(routing.headerOverride).length > 0+ ? { headers: { ...routing.headerOverride } }+ : {}),+ ...(routing?.modelsUrl ? { modelsUrl: routing.modelsUrl } : {}),+ };+ }+ return {+ id: p.id,+ name: p.name,+ ...(p.auth.method === 'oauth' && p.auth.oauth+ ? { auth: { method: 'oauth' as const, oauth: p.auth.oauth } }+ : p.auth.method === 'none'+ ? { auth: { method: 'none' as const } }+ : {}),+ runtimes,+ };+}+/** 刷新时只追加接口新发现的模型,并让新增模型默认隐藏。 */export function appendDiscoveredCustomProviderModels(existing: readonly ProviderRuntimeModelConfig[],diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex d8b53c9989..5958a8b214 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -3488,6 +3488,7 @@ interface ElectronAPI {baseUrl: string;modelId: string;wireProtocol?: import('@cindy/model-providers').ProviderWireProtocol;+ requestPath?: string;apiKey?: string | null;headers?: Record<string, string>;};@@ -3542,6 +3543,15 @@ interface ElectronAPI {providerOAuthLogin: (providerId: string) => Promise<{ ok: boolean; reason?: string }>;providerOAuthLogout: (providerId: string) => Promise<{ ok: true }>;providerOAuthCancel: (providerId: string) => Promise<{ ok: true }>;+ onProviderOAuthProgress: (+ cb: (progress: {+ providerId: string;+ phase: 'device-code';+ verificationUrl: string;+ userCode: string;+ expiresAt: number;+ }) => void,+ ) => () => void;/** 自定义供应商上游错误订阅(返回 off);code 走 providerError.* i18n。 */onProviderUpstreamError: (cb: (event: {diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.mdindex 761f6fcc07..2d6ec0f1c2 100644--- a/i18n/GLOSSARY.md+++ b/i18n/GLOSSARY.md@@ -120,7 +120,14 @@## 待讨论术语-(暂无——所有已登记术语都已裁决)+这些术语现状不一致但**尚未拍板**,guard 只告警不阻断。裁决后把 `i18n/glossary.json` 里对应条目的 `status` 改为 `decided`、补上 `translations`。++**注意别指望 `--update-baseline` 帮你收尾。** `proposed` 存在的理由正是「已知有存量不一致」,改成 `decided` 的那一刻这些告警会变成阻断违规;而 `--update-baseline` 只删不加,遇到 baseline 里没有的指纹会直接拒绝。所以裁决时只有两条路:要么把命中逐条读语境改掉,要么先人工把已 review 过的指纹写进 `i18n/glossary-baseline.json` 冻结存量,之后再用 `--update-baseline` 做修剪。++### Device Code++OAuth 2.0 Device Authorization Grant 中由用户在另一设备验证页输入的一次性代码。当前先采用各语言直译,作为待产品裁决术语登记,避免后续界面出现“设备代码/配对码/认证码”等多套说法。+## 怎么加一条术语1. 在 `i18n/glossary.json` 的 `terms` 里加条目,`note` 必填——写清楚**为什么**这么定,diff --git a/i18n/glossary.json b/i18n/glossary.jsonindex 36f8a5eccd..02b4d53107 100644--- a/i18n/glossary.json+++ b/i18n/glossary.json@@ -12,6 +12,17 @@"desktop:settings.help.qnaFeedbackBodyTemplate"],"terms": [+ {+ "id": "device-code",+ "status": "proposed",+ "en": "Device Code",+ "translations": {+ "zh-CN": "设备码",+ "ja": "デバイスコード",+ "ko": "기기 코드"+ },+ "note": "OAuth 2.0 Device Authorization Grant 中由用户在另一设备验证页输入的一次性代码。当前先采用各语言直译,作为待产品裁决术语登记,避免后续界面出现“设备代码/配对码/认证码”等多套说法。"+ },{"id": "agent","status": "decided",diff --git a/packages/anthropic-compat-proxy/src/server.test.ts b/packages/anthropic-compat-proxy/src/server.test.tsindex 1b481b0013..a376a03a14 100644--- a/packages/anthropic-compat-proxy/src/server.test.ts+++ b/packages/anthropic-compat-proxy/src/server.test.ts@@ -607,6 +607,92 @@ describe('anthropic-compat-proxy routingTransform', () => {expect(custom.bodies).toHaveLength(1);});+ it('forwards to an exact same-origin path override instead of appending the client path', async () => {+ const custom = await startFakeUpstream((_i, _b, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end('{}');+ });+ upstreamClose = custom.close;++ proxy = await createAnthropicCompatProxy({+ upstream: `${custom.url}/base`,+ transformRequest: [],+ routingTransform: () => ({ pathOverride: '/tenant/acme/infer?stream=1' }),+ });++ await post(proxy.url, { model: 'custom-model' });+ expect(custom.paths).toEqual(['/base/tenant/acme/infer?stream=1']);+ });++ it('accepts a root override when the upstream base already names the endpoint', async () => {+ const custom = await startFakeUpstream((_i, _b, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end('{}');+ });+ upstreamClose = custom.close;++ proxy = await createAnthropicCompatProxy({+ upstream: `${custom.url}/inference-endpoint`,+ transformRequest: [],+ routingTransform: () => ({ pathOverride: '/' }),+ });++ await post(proxy.url, { model: 'custom-model' });+ expect(custom.paths).toEqual(['/inference-endpoint/']);+ });++ it('preserves the upstream base query when applying a path override', async () => {+ const custom = await startFakeUpstream((_i, _b, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end('{}');+ });+ upstreamClose = custom.close;++ proxy = await createAnthropicCompatProxy({+ upstream: `${custom.url}/base?tenant=acme`,+ transformRequest: [],+ routingTransform: () => ({ pathOverride: '/infer?stream=1' }),+ });++ await post(proxy.url, { model: 'custom-model' });+ expect(custom.paths).toEqual(['/base/infer?tenant=acme&stream=1']);+ });++ it.each([+ '//evil.example/infer',+ '/infer#fragment',+ '/infer\r\nx-injected: yes',+ '/my path',+ '/infer\tmode',+ '/infer\u0000mode',+ '/infer\u007fmode',+ '/infer\u0085mode',+ '/café',+ '/infer%2',+ '/%ZZ',+ '/模型',+ '/v1\\messages',+ ])('rejects an unsafe path override before contacting the upstream: %j', async (pathOverride) => {+ const custom = await startFakeUpstream((_i, _b, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end('{}');+ });+ upstreamClose = custom.close;++ proxy = await createAnthropicCompatProxy({+ upstream: `${custom.url}/base`,+ transformRequest: [],+ routingTransform: () => ({ pathOverride }),+ });++ const result = await post(proxy.url, { model: 'custom-model' });+ expect(result.status).toBe(502);+ expect(JSON.parse(result.text)).toEqual({+ error: { type: 'proxy_error', message: 'selected request path invalid' },+ });+ expect(custom.paths).toHaveLength(0);+ });+it('runs a local handler without resolving an unavailable default upstream', async () => {proxy = await createAnthropicCompatProxy({upstream: () => '',@@ -932,8 +1018,9 @@ describe('anthropic-compat-proxy routingTransform', () => {let observedEnd = false;let transformedReqId: number | null = null;let observedCtx: { reqId: number; url: string; status: number; upstreamBase: string } | null = null;+ const upstreamWithQuery = `${upstream.url}/tenant/acme?region=us`;proxy = await createAnthropicCompatProxy({- upstream: upstream.url,+ upstream: upstreamWithQuery,transformRequest: [(_body, ctx) => {transformedReqId = ctx.reqId;return null;@@ -961,7 +1048,7 @@ describe('anthropic-compat-proxy routingTransform', () => {reqId: transformedReqId,url: '/v1/responses',status: 200,- upstreamBase: upstream.url,+ upstreamBase: upstreamWithQuery,});expect(chunks.join('')).toBe(r.text);expect(observedEnd).toBe(true);diff --git a/packages/anthropic-compat-proxy/src/server.ts b/packages/anthropic-compat-proxy/src/server.tsindex 7986db134e..c22c4ac60d 100644--- a/packages/anthropic-compat-proxy/src/server.ts+++ b/packages/anthropic-compat-proxy/src/server.ts@@ -103,6 +103,7 @@ interface UpstreamTarget {port: number;protocol: 'http:' | 'https:';basePath: string; // 上游路径前缀(例 "" 或 "/v1")+ baseQuery: string; // 不含前导 '?'}/**@@ -125,6 +126,7 @@ function parseUpstream(upstream: string): UpstreamTarget {port: u.port ? Number(u.port) : (u.protocol === 'https:' ? 443 : 80),protocol: u.protocol,basePath: u.pathname.replace(/\/+$/, ''), // 去末尾斜杠,防止后面拼出双斜杠+ baseQuery: u.search.slice(1),};}@@ -138,7 +140,8 @@ function formatUpstreamBase(t: UpstreamTarget): string {return (`${t.protocol}//${t.hostname}` +(t.port === defaultPort ? '' : `:${t.port}`) +- t.basePath+ t.basePath ++ (t.baseQuery ? `?${t.baseQuery}` : ''));}@@ -251,6 +254,21 @@ function respondRoutingFailure(res.destroy(err instanceof Error ? err : new Error(String(err)));}+/** 路由层是最后的信任边界;任何调用方给出的路径覆盖都必须保持同源且不可注入 header。 */+function isSafePathOverride(value: unknown): value is string {+ return (+ typeof value === 'string'+ && value.length >= 1+ && value.length <= 2_048+ && value.startsWith('/')+ && !value.startsWith('//')+ && !value.includes('#')+ && !value.includes('\\')+ && !/[^\u0021-\u007e]/.test(value)+ && !/%(?![0-9A-Fa-f]{2})/.test(value)+ );+}+function isPromiseLike<T>(value: unknown): value is PromiseLike<T> {return typeof value === 'object' && value !== null && typeof (value as { then?: unknown }).then === 'function';}@@ -604,6 +622,8 @@ function forward(clientModel = '',// 请求处理层解析好的出站代理;undefined = 直连(与扩展前字节级一致)。outboundProxy?: ResolvedOutboundProxy,+ // 精确推理路径覆盖;省略时沿用客户端原始 path。+ pathOverride?: string,): void {// 客户端已断开(典型:400 缓冲期间断开后走到透明重试)——'close' 已经发过,// 下面挂的中断传播 listener 永远不会触发,直接不发起上游请求。@@ -622,7 +642,14 @@ function forward(}}const reqFn = actualTarget.protocol === 'https:' ? httpsRequest : httpRequest;- const upstreamPath = `${actualTarget.basePath}${path.startsWith('/') ? path : '/' + path}`;+ const routedPath = pathOverride ?? path;+ const queryIndex = routedPath.indexOf('?');+ const routedPathname = queryIndex === -1 ? routedPath : routedPath.slice(0, queryIndex);+ const routedQuery = queryIndex === -1 ? '' : routedPath.slice(queryIndex + 1);+ const upstreamPathname =+ `${actualTarget.basePath}${routedPathname.startsWith('/') ? routedPathname : '/' + routedPathname}`;+ const upstreamQuery = [actualTarget.baseQuery, routedQuery].filter(Boolean).join('&');+ const upstreamPath = upstreamQuery ? `${upstreamPathname}?${upstreamQuery}` : upstreamPathname;// http.request 会把 options 原样透传给 agent.createConnection → net.connect,// 所以 socket 级 connect 选项运行时有效;但 @types/node 的 RequestOptions 没收录@@ -758,6 +785,7 @@ function forward(responseObserver,clientModel,outboundProxy,+ pathOverride,);return;}@@ -992,7 +1020,20 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<ProverrideTarget?: UpstreamTarget;headerOverride?: Record<string, string>;headerDelete?: readonly string[];+ pathOverride?: string;} | null => {+ const pathOverride = decision?.pathOverride;+ if (pathOverride !== undefined && !isSafePathOverride(pathOverride)) {+ respondRoutingFailure(+ res,+ logger,+ reqId,+ 502,+ 'selected request path invalid',+ new Error('routingTransform returned an unsafe pathOverride'),+ );+ return null;+ }let overrideTarget: UpstreamTarget | undefined;try {overrideTarget = decision?.upstreamOverride@@ -1014,6 +1055,7 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<ProverrideTarget,headerOverride: decision?.headerOverride,headerDelete: decision?.headerDelete,+ pathOverride,};};@@ -1137,6 +1179,7 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Propts.responseObserver,'',await resolveOutboundForTarget(route.target, reqId),+ route.pathOverride,);return;}@@ -1269,6 +1312,7 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Propts.responseObserver,extractBodyModel(rawBody),await resolveOutboundForTarget(route.target, reqId),+ route.pathOverride,);});diff --git a/packages/anthropic-compat-proxy/src/types.ts b/packages/anthropic-compat-proxy/src/types.tsindex 54e3134986..5cfb8f4b11 100644--- a/packages/anthropic-compat-proxy/src/types.ts+++ b/packages/anthropic-compat-proxy/src/types.ts@@ -77,6 +77,11 @@ export type LocalRequestHandler = (args: {export interface RoutingDecision {/** 覆盖本次请求的上游 URL(完整 `http(s)://host[:port][/basePath]`);省略 = 用默认 `opts.upstream`。 */upstreamOverride?: string;+ /**+ * 覆盖本次请求追加到上游 base path 后的路径;必须是以单个 `/` 开头的同源路径。+ * 典型用于兼容端点不是标准 `/responses` / `/v1/messages` 的供应商。+ */+ pathOverride?: string;/** 合并进 outbound headers 的字段(覆盖语义,小写 key);典型用于换 `authorization`。 */headerOverride?: Record<string, string>;/**@@ -88,7 +93,7 @@ export interface RoutingDecision {*/headerDelete?: string[];/**- * 本地 handler(见 LocalRequestHandler)。与上面三个转发字段**互斥**:设了 handler 时其余+ * 本地 handler(见 LocalRequestHandler)。与上面四个转发字段**互斥**:设了 handler 时其余* 字段忽略、不发生任何上游转发。省略 = 转发语义,与本字段引入前字节级一致。*/localHandler?: LocalRequestHandler;diff --git a/packages/model-providers/src/__tests__/catalog.test.ts b/packages/model-providers/src/__tests__/catalog.test.tsindex 0c85bcbbf6..79687f6023 100644--- a/packages/model-providers/src/__tests__/catalog.test.ts+++ b/packages/model-providers/src/__tests__/catalog.test.ts@@ -408,3 +408,74 @@ describe('vendor grouping metadata (xai 静态清单)', () => {}});});++describe('provider OAuth and upstream URL validation', () => {+ const oauthCatalog = (): Catalog => ({+ version: '1',+ providers: [{+ id: 'oauth-provider',+ name: 'OAuth Provider',+ source: 'builtin',+ agents: ['codex'],+ auth: {+ method: 'oauth',+ oauth: {+ flow: 'authorization-code',+ authorizeUrl: 'https://auth.example/authorize',+ tokenUrl: 'https://auth.example/token',+ clientId: 'client',+ scopes: 'openid',+ },+ },+ routing: {+ codex: {+ upstream: 'https://api.example/v1',+ authStrategy: 'oauth-token',+ },+ },+ models: { codex: [model('m1')] },+ }],+ });++ it('rejects fields from the other OAuth flow', () => {+ const authorizationCode = oauthCatalog();+ Object.assign(authorizationCode.providers[0]!.auth.oauth!, {+ deviceAuthorizationUrl: 'https://auth.example/device',+ });+ expect(() => parseCatalog(authorizationCode)).toThrow(/device-code fields/);++ const deviceCode = oauthCatalog();+ deviceCode.providers[0]!.auth.oauth = {+ flow: 'device-code',+ deviceAuthorizationUrl: 'https://auth.example/device',+ tokenUrl: 'https://auth.example/token',+ clientId: 'client',+ scopes: 'openid',+ authorizeUrl: 'https://auth.example/authorize',+ } as never;+ expect(() => parseCatalog(deviceCode)).toThrow(/authorization-code fields/);+ });++ it('rejects reserved OAuth extra params case-insensitively', () => {+ const catalog = oauthCatalog();+ catalog.providers[0]!.auth.oauth!.extraAuthParams = {+ Client_Id: 'shadow-client',+ };+ expect(() => parseCatalog(catalog)).toThrow(/cannot override 'Client_Id'/);+ });++ it('rejects an OAuth descriptor on a non-OAuth auth method', () => {+ const catalog = oauthCatalog();+ catalog.providers[0]!.auth = {+ method: 'none',+ oauth: catalog.providers[0]!.auth.oauth,+ } as never;+ expect(() => parseCatalog(catalog)).toThrow(/auth\.oauth not allowed for none method/);+ });++ it('rejects an upstream URL with embedded credentials', () => {+ const catalog = oauthCatalog();+ catalog.providers[0]!.routing.codex!.upstream = 'https://user:[email protected]/v1';+ expect(() => parseCatalog(catalog)).toThrow(/upstream invalid/);+ });+});diff --git a/packages/model-providers/src/__tests__/presets.test.ts b/packages/model-providers/src/__tests__/presets.test.tsindex 53338ede26..6a0fa865dc 100644--- a/packages/model-providers/src/__tests__/presets.test.ts+++ b/packages/model-providers/src/__tests__/presets.test.ts@@ -221,6 +221,28 @@ describe('parseCatalog oauth 描述符校验', () => {).toThrow(/redirectPort/);});+ it('扩展参数不能覆盖 OAuth 标准字段', () => {+ expect(() =>+ parseCatalog(catalogWithAuth({+ method: 'oauth',+ oauth: { ...oauth, extraAuthParams: { state: 'fixed-state' } },+ })),+ ).toThrow(/cannot override 'state'/);+ expect(() =>+ parseCatalog(catalogWithAuth({+ method: 'oauth',+ oauth: {+ flow: 'device-code',+ deviceAuthorizationUrl: 'https://auth.acme.example/device',+ tokenUrl: oauth.tokenUrl,+ clientId: oauth.clientId,+ scopes: oauth.scopes,+ extraDeviceParams: { client_id: 'other-client' },+ },+ })),+ ).toThrow(/cannot override 'client_id'/);+ });+it('不带描述符的 oauth 供应商(bespoke 现状)不受影响', () => {expect(() => parseCatalog(catalogWithAuth({ method: 'oauth' }))).not.toThrow();});diff --git a/packages/model-providers/src/__tests__/provider-url.test.ts b/packages/model-providers/src/__tests__/provider-url.test.tsnew file mode 100644index 0000000000..f3da202fdb--- /dev/null+++ b/packages/model-providers/src/__tests__/provider-url.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest';++import { appendProviderRequestPath, isProviderRequestPath } from '../provider-url.js';++describe('isProviderRequestPath', () => {+ it('accepts an encoded same-origin path with query parameters', () => {+ expect(isProviderRequestPath('/tenant/acme/my%20path?stream=1')).toBe(true);+ });++ it('accepts the root path for providers whose base URL already names the inference endpoint', () => {+ expect(isProviderRequestPath('/')).toBe(true);+ expect(appendProviderRequestPath('https://custom.example/infer', '/'))+ .toBe('https://custom.example/infer/');+ });++ it.each([+ '//evil.example/infer',+ '/infer#fragment',+ '/my path',+ '/infer\tmode',+ '/infer\u0000mode',+ '/infer\u007fmode',+ '/infer\u0085mode',+ '/café',+ '/foo%2',+ '/%ZZ',+ '/./infer',+ '/../infer',+ '/%2e/infer',+ '/%2E%2e/infer',+ '/.%2e/infer',+ '/%2e./infer',+ '/模型',+ '/v1\\messages',+ 'responses',+ ])('rejects an unsafe or unescaped request path: %j', (requestPath) => {+ expect(isProviderRequestPath(requestPath)).toBe(false);+ });++ it('does not treat dot-like query values as path segments', () => {+ expect(isProviderRequestPath('/infer?next=../other')).toBe(true);+ expect(isProviderRequestPath('/infer?next=%2e%2e')).toBe(true);+ });+});++describe('appendProviderRequestPath', () => {+ it('preserves the base query and appends the request-path query', () => {+ expect(+ appendProviderRequestPath(+ 'https://custom.example/api?tenant=alpha',+ '/infer?stream=1&mode=fast',+ ),+ ).toBe(+ 'https://custom.example/api/infer?tenant=alpha&stream=1&mode=fast',+ );+ });++ it('rejects base URLs with embedded credentials', () => {+ expect(() =>+ appendProviderRequestPath('https://user:[email protected]/api', '/infer'),+ ).toThrow('invalid provider base URL');+ });++ it('rejects invalid paths before URL construction', () => {+ expect(() => appendProviderRequestPath('https://custom.example', '/my path'))+ .toThrow('invalid provider request path');+ });+});diff --git a/packages/model-providers/src/__tests__/user-provider.test.ts b/packages/model-providers/src/__tests__/user-provider.test.tsindex 3b1da634ae..533686a476 100644--- a/packages/model-providers/src/__tests__/user-provider.test.ts+++ b/packages/model-providers/src/__tests__/user-provider.test.ts@@ -63,6 +63,19 @@ describe('buildUserProvider (per-runtime)', () => {});});+ it('preserves a non-standard inference request path in routing', () => {+ const p = buildUserProvider({+ ...codexOnly,+ runtimes: {+ codex: {+ ...codexOnly.runtimes.codex!,+ requestPath: '/tenant/acme/v2/infer?stream=1',+ },+ },+ });+ expect(p.routing.codex?.requestPath).toBe('/tenant/acme/v2/infer?stream=1');+ });+it('maps models per runtime with conservative default metadata', () => {const p = buildUserProvider(codexOnly);const models = p.models.codex ?? [];@@ -148,6 +161,23 @@ describe('buildUserProvider (per-runtime)', () => {expect(p.routing.codex?.authStrategy).toBe('oauth-token');});+ it('maps an explicit no-auth proxy without falling back to API-key routing', () => {+ const p = buildUserProvider({+ ...codexOnly,+ id: 'litellm-proxy',+ auth: { method: 'none' },+ runtimes: {+ codex: {+ baseUrl: 'http://127.0.0.1:4000/v1',+ models: [{ id: 'local-model', name: 'Local model' }],+ },+ },+ });+ expect(p.auth).toEqual({ method: 'none' });+ expect(p.access).toEqual({ kind: 'api' });+ expect(p.routing.codex?.authStrategy).toBe('none');+ });+it('supports two runtimes with independent baseUrl + models, stable agent order', () => {const p = buildUserProvider({id: 'vendor',diff --git a/packages/model-providers/src/catalog.ts b/packages/model-providers/src/catalog.tsindex a4b30f0f40..3b470db374 100644--- a/packages/model-providers/src/catalog.ts+++ b/packages/model-providers/src/catalog.ts@@ -12,6 +12,8 @@*/import type { Catalog, Provider, CatalogModel, AgentKind, Effort, ProviderPreset } from './types.js';+import { findReservedOAuthExtraParam } from './provider-oauth.js';+import { isProviderRequestPath } from './provider-url.js';export { BUNDLED_CATALOG, BUILTIN_PROVIDERS } from './builtin.js';@@ -74,22 +76,88 @@ function validateModel(m: CatalogModel, providerId: string): void {function validateOAuthDescriptor(p: Provider): void {const d = p.auth?.oauth;if (d === undefined) return;- assert(d && typeof d === 'object', `provider '${p.id}' auth.oauth must be an object`);- for (const field of ['authorizeUrl', 'tokenUrl', 'clientId', 'scopes'] as const) {- assert(typeof d[field] === 'string' && d[field].length > 0, `provider '${p.id}' auth.oauth.${field} missing`);+ assert(d && typeof d === 'object' && !Array.isArray(d), `provider '${p.id}' auth.oauth must be an object`);+ const raw = d as unknown as Record<string, unknown>;+ const flow = raw.flow ?? 'authorization-code';+ assert(+ flow === 'authorization-code' || flow === 'device-code',+ `provider '${p.id}' auth.oauth.flow invalid`,+ );+ for (const field of ['tokenUrl', 'clientId', 'scopes'] as const) {+ assert(typeof raw[field] === 'string' && raw[field].length > 0, `provider '${p.id}' auth.oauth.${field} missing`);}- for (const field of ['authorizeUrl', 'tokenUrl'] as const) {- assert(d[field].startsWith('https://'), `provider '${p.id}' auth.oauth.${field} must be https`);+ const requireHttpsUrl = (field: string): void => {+ const value = raw[field];+ let valid = false;+ if (typeof value === 'string') {+ try {+ const url = new URL(value);+ valid = url.protocol === 'https:' && !url.username && !url.password;+ } catch {+ valid = false;+ }+ }+ assert(valid, `provider '${p.id}' auth.oauth.${field} must be https`);+ };+ requireHttpsUrl('tokenUrl');+ if (flow === 'authorization-code') {+ requireHttpsUrl('authorizeUrl');+ assert(+ raw.deviceAuthorizationUrl === undefined && raw.extraDeviceParams === undefined,+ `provider '${p.id}' auth.oauth device-code fields not allowed for authorization-code`,+ );+ } else {+ requireHttpsUrl('deviceAuthorizationUrl');+ assert(+ raw.authorizeUrl === undefined+ && raw.extraAuthParams === undefined+ && raw.redirectPort === undefined,+ `provider '${p.id}' auth.oauth authorization-code fields not allowed for device-code`,+ );}- if (d.redirectPort !== undefined) {+ if (raw.redirectPort !== undefined) {assert(- typeof d.redirectPort === 'number' && Number.isInteger(d.redirectPort) && d.redirectPort > 0 && d.redirectPort < 65536,+ flow === 'authorization-code'+ && typeof raw.redirectPort === 'number'+ && Number.isInteger(raw.redirectPort)+ && raw.redirectPort > 0+ && raw.redirectPort < 65536,`provider '${p.id}' auth.oauth.redirectPort invalid`,);}- if (d.modelsDiscoveryUrl !== undefined) {+ const validateParams = (field: 'extraAuthParams' | 'extraDeviceParams'): void => {+ if (raw[field] === undefined) return;+ assert(+ raw[field] && typeof raw[field] === 'object' && !Array.isArray(raw[field]),+ `provider '${p.id}' auth.oauth.${field} invalid`,+ );+ assert(+ Object.values(raw[field] as Record<string, unknown>).every((value) => typeof value === 'string'),+ `provider '${p.id}' auth.oauth.${field} invalid`,+ );+ const collision = findReservedOAuthExtraParam(+ raw[field] as Record<string, unknown>,+ flow,+ );assert(- typeof d.modelsDiscoveryUrl === 'string' && d.modelsDiscoveryUrl.startsWith('https://'),+ collision === null,+ `provider '${p.id}' auth.oauth.${field} cannot override '${String(collision)}'`,+ );+ };+ if (flow === 'authorization-code') validateParams('extraAuthParams');+ else validateParams('extraDeviceParams');+ if (raw.modelsDiscoveryUrl !== undefined) {+ let valid = false;+ if (typeof raw.modelsDiscoveryUrl === 'string') {+ try {+ const url = new URL(raw.modelsDiscoveryUrl);+ valid = url.protocol === 'https:' && !url.username && !url.password;+ } catch {+ valid = false;+ }+ }+ assert(+ valid,`provider '${p.id}' auth.oauth.modelsDiscoveryUrl must be https`,);}@@ -102,6 +170,20 @@ function validateProvider(p: Provider): void {// 必须限定 slug 字符集,防被投毒目录用 `../` 之类字符把凭证写出存储目录。assert(/^[a-zA-Z0-9_-]+$/.test(p.id), `provider.id has illegal characters: '${p.id}'`);assert(typeof p.name === 'string' && p.name.length > 0, `provider.name missing for '${p.id}'`);+ assert(+ p.auth+ && (+ p.auth.method === 'oauth'+ || p.auth.method === 'apiKey'+ || p.auth.method === 'managed'+ || p.auth.method === 'none'+ ),+ `provider.auth.method invalid for '${p.id}'`,+ );+ assert(+ p.auth.method === 'oauth' || p.auth.oauth === undefined,+ `provider '${p.id}' auth.oauth not allowed for ${p.auth.method} method`,+ );assert(Array.isArray(p.agents) && p.agents.length > 0, `provider.agents missing for '${p.id}'`);assert(p.agents.every(isAgentKind), `provider.agents has invalid kind for '${p.id}'`);assert(p.routing && typeof p.routing === 'object', `provider.routing missing for '${p.id}'`);@@ -113,6 +195,20 @@ function validateProvider(p: Provider): void {for (const agent of p.agents) {const routing = p.routing[agent];assert(routing, `provider '${p.id}' declares agent '${agent}' but no routing[${agent}]`);+ if (routing.upstream !== undefined) {+ let valid = false;+ try {+ const url = new URL(routing.upstream);+ valid = (+ (url.protocol === 'http:' || url.protocol === 'https:')+ && !url.username+ && !url.password+ );+ } catch {+ valid = false;+ }+ assert(valid, `provider '${p.id}' routing[${agent}].upstream invalid`);+ }if (routing.wireProtocol !== undefined) {assert(isWireProtocol(routing.wireProtocol),@@ -133,6 +229,12 @@ function validateProvider(p: Provider): void {);}}+ if (routing.requestPath !== undefined) {+ assert(+ isProviderRequestPath(routing.requestPath),+ `provider '${p.id}' routing[${agent}].requestPath invalid`,+ );+ }// modelPrefixes(路由服务范围)提供了就必须是命名空间前缀形态(`xai/` 这类,以 `/` 结尾)——// 结构上保证 claude-* 等裸 wire model 永远不会命中,防止把 scope 声明成误伤辅助请求的形状。if (routing.modelPrefixes !== undefined) {@@ -249,6 +351,11 @@ function isValidPreset(v: unknown): v is ProviderPreset {if (typeof p.id !== 'string' || p.id.length === 0) return false;if (typeof p.name !== 'string' || p.name.length === 0) return false;if (p.docsUrl !== undefined && typeof p.docsUrl !== 'string') return false;+ if (+ p.authMethod !== undefined+ && p.authMethod !== 'apiKey'+ && p.authMethod !== 'none'+ ) return false;if (!p.runtimes || typeof p.runtimes !== 'object' || Array.isArray(p.runtimes)) return false;const entries = Object.entries(p.runtimes as Record<string, unknown>);if (entries.length === 0) return false;@@ -275,7 +382,8 @@ function isValidPreset(v: unknown): v is ProviderPreset {if (!r.headers || typeof r.headers !== 'object' || Array.isArray(r.headers)) return false;if (Object.values(r.headers as Record<string, unknown>).some((x) => typeof x !== 'string')) return false;}- // modelsUrl 不在此淘汰整条——非法值由 sanitizePresets 剥字段(同 regionHint 容错语义)。+ if (r.baseUrlEditable !== undefined && typeof r.baseUrlEditable !== 'boolean') return false;+ // modelsUrl / requestPath 不在此淘汰整条——非法值由 sanitizePresets 剥字段。}return true;}@@ -295,17 +403,22 @@ function isHttpUrl(v: unknown): boolean {* runtime.modelsUrl 非法(非 http(s) URL)时剥掉该字段、保留预设本体——OSS 推错一个* 不可见字段不该让整条预设消失,更不该让用户保存时撞 main 侧 URL 校验无法自助修复。*/-function normalizePresetModelsUrls(p: ProviderPreset): ProviderPreset {+function normalizePresetRuntimeOptions(p: ProviderPreset): ProviderPreset {let changed = false;const runtimes: ProviderPreset['runtimes'] = {};for (const [agent, rt] of Object.entries(p.runtimes) as [AgentKind, ProviderPreset['runtimes'][AgentKind] & object][]) {- if (rt.modelsUrl !== undefined && !isHttpUrl(rt.modelsUrl)) {- const { modelsUrl: _drop, ...rest } = rt;- runtimes[agent] = rest;+ let next = rt;+ if (next.modelsUrl !== undefined && !isHttpUrl(next.modelsUrl)) {+ const { modelsUrl: _drop, ...rest } = next;+ next = rest;+ changed = true;+ }+ if (next.requestPath !== undefined && !isProviderRequestPath(next.requestPath)) {+ const { requestPath: _drop, ...rest } = next;+ next = rest;changed = true;- } else {- runtimes[agent] = rt;}+ runtimes[agent] = next;}return changed ? { ...p, runtimes } : p;}@@ -336,7 +449,7 @@ export function sanitizePresets(input: unknown): ProviderPreset[] {const { nameEn: _drop, ...rest } = preset as ProviderPreset & { nameEn: unknown };preset = rest as ProviderPreset;}- out.push(normalizePresetModelsUrls(preset));+ out.push(normalizePresetRuntimeOptions(preset));}return out;}diff --git a/packages/model-providers/src/index.ts b/packages/model-providers/src/index.tsindex 665887ddf0..6eb8e43e2f 100644--- a/packages/model-providers/src/index.ts+++ b/packages/model-providers/src/index.ts@@ -25,12 +25,16 @@ export type {ProviderRuntimeModelConfig,ProviderPreset,ProviderPresetRuntime,+ OAuthAuthorizationCodeDescriptor,+ OAuthDeviceCodeDescriptor,OAuthProviderDescriptor,} from './types.js';export { BUNDLED_CATALOG, BUILTIN_PROVIDERS, parseCatalog, presetDisplayName, sanitizePresets, sortPresetsForLocale } from './catalog.js';export { buildUserProvider, DEFAULT_CUSTOM_CONTEXT_WINDOW } from './user-provider.js';+export { appendProviderRequestPath, isProviderRequestPath } from './provider-url.js';+export { findReservedOAuthExtraParam } from './provider-oauth.js';export {CATALOG_API_PATH,diff --git a/packages/model-providers/src/provider-oauth.ts b/packages/model-providers/src/provider-oauth.tsnew file mode 100644index 0000000000..fc74d7b15e--- /dev/null+++ b/packages/model-providers/src/provider-oauth.ts@@ -0,0 +1,23 @@+import type { OAuthProviderDescriptor } from './types.js';++const RESERVED_AUTHORIZATION_CODE_PARAMS = new Set([+ 'response_type',+ 'client_id',+ 'redirect_uri',+ 'scope',+ 'code_challenge',+ 'code_challenge_method',+ 'state',+]);+const RESERVED_DEVICE_CODE_PARAMS = new Set(['client_id', 'scope']);++/** 返回 OAuth 扩展参数里首个会覆盖标准字段的 key;没有冲突时返回 null。 */+export function findReservedOAuthExtraParam(+ params: Record<string, unknown>,+ flow: NonNullable<OAuthProviderDescriptor['flow']>,+): string | null {+ const reserved = flow === 'device-code'+ ? RESERVED_DEVICE_CODE_PARAMS+ : RESERVED_AUTHORIZATION_CODE_PARAMS;+ return Object.keys(params).find((key) => reserved.has(key.toLowerCase())) ?? null;+}diff --git a/packages/model-providers/src/provider-url.ts b/packages/model-providers/src/provider-url.tsnew file mode 100644index 0000000000..8bc8c98e79--- /dev/null+++ b/packages/model-providers/src/provider-url.ts@@ -0,0 +1,56 @@+/**+ * 供应商推理路径的共享边界。+ *+ * 路径最终会原样进入 Node `http(s).request({ path })`,因此除同源约束外,还必须拒绝+ * 会被 WHATWG URL 重新编码、但透明代理仍按原字节发送的字符。仅允许可打印 ASCII;+ * 空格、控制符和非 ASCII 字符应由用户先做 percent-encoding。+ */+export function isProviderRequestPath(value: unknown): value is string {+ if (typeof value !== 'string') return false;+ const queryIndex = value.indexOf('?');+ const path = queryIndex === -1 ? value : value.slice(0, queryIndex);+ const hasDotSegment = path+ .split('/')+ .some((segment) => {+ const normalizedDots = segment.replace(/%2e/gi, '.');+ return normalizedDots === '.' || normalizedDots === '..';+ });+ return (+ value.length >= 1+ && value.length <= 2_048+ && value.startsWith('/')+ && !value.startsWith('//')+ && !value.includes('#')+ && !value.includes('\\')+ && !/[^\u0021-\u007e]/.test(value)+ && !/%(?![0-9A-Fa-f]{2})/.test(value)+ && !hasDotSegment+ );+}++/**+ * 把已验证的精确推理路径追加到 base URL,同时保留 base query。+ * requestPath 自带的 query 追加在 base query 后,fragment 一律不进入请求。+ */+export function appendProviderRequestPath(baseUrl: string, requestPath: string): string {+ if (!isProviderRequestPath(requestPath)) {+ throw new TypeError('invalid provider request path');+ }+ const url = new URL(baseUrl);+ if (+ (url.protocol !== 'http:' && url.protocol !== 'https:')+ || url.username+ || url.password+ ) {+ throw new TypeError('invalid provider base URL');+ }+ const basePath = url.pathname.replace(/\/+$/, '');+ const queryIndex = requestPath.indexOf('?');+ const exactPath = queryIndex === -1 ? requestPath : requestPath.slice(0, queryIndex);+ const exactQuery = queryIndex === -1 ? '' : requestPath.slice(queryIndex + 1);+ const baseQuery = url.search.slice(1);+ url.pathname = `${basePath}${exactPath}`;+ url.search = [baseQuery, exactQuery].filter(Boolean).join('&');+ url.hash = '';+ return url.toString();+}diff --git a/packages/model-providers/src/types.ts b/packages/model-providers/src/types.tsindex f1588509fb..1a055d99ec 100644--- a/packages/model-providers/src/types.ts+++ b/packages/model-providers/src/types.ts@@ -37,8 +37,9 @@ export type ProviderSource = 'builtin' | 'user';* - oauth : 走 OAuth 登录(Claude.ai 订阅 / Codex 订阅)* - apiKey : 用户手填 API key* - managed : 由平台托管 / 自动下发(XD 网关 key 登录后自动同步)+ * - none : 上游不要求客户端鉴权(本机 LiteLLM / Ollama 等受信代理)*/-export type AuthMethod = 'oauth' | 'apiKey' | 'managed';+export type AuthMethod = 'oauth' | 'apiKey' | 'managed' | 'none';/*** 模型额度的来源(展示 / 产品语义),与 `auth` 的连接协议刻意分开:@@ -62,32 +63,46 @@ export type ProviderAccess =* access_token 覆盖鉴权头(`Authorization: Bearer`)。与* oauth-passthrough 的区别:token 不来自 agent 二进制自带凭证,* 而来自目录 `auth.oauth` 描述符驱动的登录(见 OAuthProviderDescriptor)。+ * - none : 直连无需鉴权的受信上游;代理必须剥掉 agent 自带的鉴权与账号头,+ * 防把 Claude.ai / ChatGPT 订阅凭证泄漏给本地或自托管服务。*/export type AuthStrategy =| 'oauth-passthrough'| 'provider-oauth-header'| 'api-key-header'| 'gateway-key'- | 'oauth-token';+ | 'oauth-token'+ | 'none';/*** 授权(OAuth)供应商描述符 —— 让「接一家标准 OAuth 供应商」退化成目录数据。*- * 只承载**标准 authorization-code + PKCE** 形态的同构参数;深度定制(spawn CLI 登录、- * auth.json reconcile、JWT claim 提头等)保持 host 侧 bespoke 实现,不进描述符(规则 9:- * 确定性逻辑写代码,描述符只承载真正同构的部分)。host 的通用 OAuth Runner- * (generic-oauth)消费本描述符完成:授权页拉起 → 回环回调 → token 交换 → safeStorage- * 存储 → 单飞刷新;路由侧配合 `authStrategy: 'oauth-token'` 注入 Bearer。+ * 承载标准 authorization-code + PKCE 或 OAuth 2.0 Device Authorization Grant 的同构参数;+ * 深度定制(spawn CLI 登录、auth.json reconcile、JWT claim 提头等)保持 host 侧 bespoke+ * 实现,不进描述符(规则 9:确定性逻辑写代码,描述符只承载真正同构的部分)。host 的+ * 通用 OAuth Runner(generic-oauth)消费本描述符完成授权、safeStorage 存储与单飞刷新;+ * 路由侧配合 `authStrategy: 'oauth-token'` 注入 Bearer。*/-export interface OAuthProviderDescriptor {- /** 授权端点(authorization_endpoint)。 */- authorizeUrl: string;+interface OAuthProviderDescriptorBase {/** token 交换端点(token_endpoint,form-encoded POST)。 */tokenUrl: string;/** OAuth client id(公共客户端,PKCE 保护,无 secret)。 */clientId: string;/** 请求的 scopes(空格分隔)。 */scopes: string;+ /**+ * 动态模型发现端点(可选)。登录成功后 host 带 Bearer GET 此 URL,响应按 OpenAI+ * `GET /models` 形状(`{data:[{id}]}` 或 `{models:[...]}`)解析,additions-only+ * merge 进 active-catalog(静态条目 first-wins,发现条目只增不改删)。+ */+ modelsDiscoveryUrl?: string;+}++export interface OAuthAuthorizationCodeDescriptor extends OAuthProviderDescriptorBase {+ /** 缺省保持历史目录兼容;等价于 `authorization-code`。 */+ flow?: 'authorization-code';+ /** 授权端点(authorization_endpoint)。 */+ authorizeUrl: string;/*** 回环回调端口。多数供应商注册的 redirect_uri 是固定端口* (`http://127.0.0.1:<port>/callback`);缺省 = 随机高位端口(供应商允许通配端口时用)。@@ -95,14 +110,25 @@ export interface OAuthProviderDescriptor {redirectPort?: number;/** 追加到授权 URL 的额外 query 参数(如厂商自定义的 plan / referrer)。 */extraAuthParams?: Record<string, string>;- /**- * 动态模型发现端点(可选)。登录成功后 host 带 Bearer GET 此 URL,响应按 OpenAI- * `GET /models` 形状(`{data:[{id}]}` 或 `{models:[...]}`)解析,additions-only- * merge 进 active-catalog(静态条目 first-wins,发现条目只增不改删)。- */- modelsDiscoveryUrl?: string;+ deviceAuthorizationUrl?: never;+ extraDeviceParams?: never;}+export interface OAuthDeviceCodeDescriptor extends OAuthProviderDescriptorBase {+ flow: 'device-code';+ /** 申请 device_code / user_code 的端点(device_authorization_endpoint)。 */+ deviceAuthorizationUrl: string;+ /** 追加到设备授权 POST body 的厂商参数。 */+ extraDeviceParams?: Record<string, string>;+ authorizeUrl?: never;+ redirectPort?: never;+ extraAuthParams?: never;+}++export type OAuthProviderDescriptor =+ | OAuthAuthorizationCodeDescriptor+ | OAuthDeviceCodeDescriptor;+/*** 路由描述符(per provider × runtime)。喂给 host 侧通用路由器,决定请求的* 真实上游 + 鉴权 + model id 还原。加新供应商 = 加这份数据,不改路由器代码。@@ -115,6 +141,14 @@ export interface RoutingDescriptor {wireProtocol?: ProviderWireProtocol;/** 真实上游 base URL(direct 时是供应商自家;gateway 时是 XD 网关 base)。 */upstream: string;+ /**+ * 推理请求的精确相对路径(可选,必须以单个 `/` 开头)。+ *+ * 缺省时沿用 agent 发来的标准路径(Claude `/v1/messages`、Codex `/responses`);+ * 提供后只覆盖带 model 的推理请求,GET `/models` 等控制面请求不受影响。+ * `openai-chat` 本地桥也消费同一字段,替代缺省 `/chat/completions`。+ */+ requestPath?: string;/** 鉴权策略(见 AuthStrategy)。 */authStrategy: AuthStrategy;/** 转发上游前还原 model id(如剥掉 `codex/` 前缀)。缺省 = 原样。 */@@ -330,6 +364,8 @@ export interface ProviderPresetRuntime {wireProtocol?: ProviderWireProtocol;/** 该 runtime 的兼容端点 base URL(cc=Anthropic 兼容 / codex=OpenAI Responses 兼容)。 */baseUrl: string;+ /** 非标准推理端点的相对路径;缺省由 wire protocol 推导。 */+ requestPath?: string;/** 推荐模型清单(预填进表单,用户可增删改)。 */models: ProviderRuntimeModelConfig[];/** 可选预填请求头。 */@@ -340,6 +376,11 @@ export interface ProviderPresetRuntime {* `…/anthropic`,但列模型接口只在 `https://api.moonshot.cn/v1/models`(同一 key 可用)。*/modelsUrl?: string;+ /**+ * 允许添加向导编辑预填 base URL。仅用于本机 / 自托管网关类预设;普通官方渠道保持只读,+ * 防用户无意改坏已核验端点。+ */+ baseUrlEditable?: boolean;}/**@@ -370,6 +411,11 @@ export interface ProviderPreset {* (单端点全球服务的厂商,如 OpenRouter / DeepSeek),排序时居中。*/regionHint?: 'cn' | 'global';+ /**+ * 预设的鉴权形态。缺省 = API key;`none` 用于明确不要求客户端凭证的本机 / 自托管代理。+ * 创建后会快照进 CustomProviderConfig,不随预设后续更新。+ */+ authMethod?: 'apiKey' | 'none';/** per-runtime 预填数据(至少一个)。 */runtimes: Partial<Record<AgentKind, ProviderPresetRuntime>>;}@@ -409,6 +455,8 @@ export interface CustomProviderRuntimeConfig {wireProtocol?: ProviderWireProtocol;/** 该 runtime 的兼容上游 base URL(cc=Anthropic 端点 / codex=OpenAI 端点)。 */baseUrl: string;+ /** 非标准推理端点的相对路径;缺省由 wire protocol 推导。 */+ requestPath?: string;/** 用户模型;contextWindow 可由预设带入,缺省时由 `buildUserProvider` 补保守默认。 */models: ProviderRuntimeModelConfig[];/** 可选自定义请求头(非密钥鉴权头可放这里;API key 走 safeStorage,不放这里)。 */@@ -445,7 +493,10 @@ export interface CustomProviderConfig {* 登录(凭证存 safeStorage `provider_oauth_<id>`),路由用 `oauth-token` 策略注入* Bearer;此形态下不再使用 per-runtime API key。*/- auth?: { method: 'apiKey' | 'oauth'; oauth?: OAuthProviderDescriptor };+ auth?:+ | { method: 'apiKey'; oauth?: never }+ | { method: 'oauth'; oauth: OAuthProviderDescriptor }+ | { method: 'none'; oauth?: never };/** per-runtime 独立配置(键为 agent,只含已配置的 runtime;至少一个)。 */runtimes: Partial<Record<AgentKind, CustomProviderRuntimeConfig>>;}diff --git a/packages/model-providers/src/user-provider.ts b/packages/model-providers/src/user-provider.tsindex 6dc6731b94..0e9f1e57e9 100644--- a/packages/model-providers/src/user-provider.ts+++ b/packages/model-providers/src/user-provider.ts@@ -4,8 +4,8 @@* 设计要点:* - 产出的 `Provider` 与内置厂商(providers.json)**同形状**,进同一 active-catalog,* 下游(路由 / 选择器 / listProviders)不区分内置 / 自定义,统一消费。- * - `source: 'user'`、`auth.method: 'apiKey'`。- * - 每个用户选中的 agent 生成一份 `api-key-header` 路由(upstream = baseUrl,带用户自定义+ * - `source: 'user'`,鉴权可为 API key / OAuth / none。+ * - 每个用户选中的 agent 生成一份与鉴权形态匹配的路由(upstream = baseUrl,带用户自定义* headers);**API key 不在此注入**——它存 safeStorage,由 host 在路由 resolve 时按* `provider_key_<id>` 读出并写进鉴权头,绝不进 catalog(防经 listProviders 泄漏给 renderer)。* - 用户模型可携带预设确认的 contextWindow;缺省时补保守默认,effort 使用 runtime 默认。@@ -66,18 +66,20 @@ function defaultWireProtocol(agent: AgentKind): 'anthropic-messages' | 'openai-rreturn agent === 'claude-code' ? 'anthropic-messages' : 'openai-responses';}-/** baseUrl + 自定义 headers → 路由描述符(**不含密钥**;OAuth 形态用 oauth-token 策略)。 */+/** baseUrl + 自定义 headers → 路由描述符(**不含密钥**)。 */function toRouting(agent: AgentKind,baseUrl: string,+ requestPath: string | undefined,headers: Record<string, string> | undefined,- strategy: 'api-key-header' | 'oauth-token',+ strategy: 'api-key-header' | 'oauth-token' | 'none',modelsUrl?: string,wireProtocol?: 'anthropic-messages' | 'openai-responses' | 'openai-chat',): RoutingDescriptor {const r: RoutingDescriptor = {upstream: baseUrl,authStrategy: strategy,+ ...(requestPath ? { requestPath } : {}),...(wireProtocol && wireProtocol !== defaultWireProtocol(agent) ? { wireProtocol } : {}),};if (headers && Object.keys(headers).length > 0) r.headerOverride = { ...headers };@@ -92,8 +94,11 @@ function toRouting(* 模型 / headers);空 runtimes 产出空 Provider(不出现在任何 agent 列表,无害)。*/export function buildUserProvider(config: CustomProviderConfig): Provider {- // OAuth 形态:带完整描述符时路由走 oauth-token(Runner 持有的 Bearer),否则 API key(历史默认)。- const isOAuth = config.auth?.method === 'oauth' && config.auth.oauth !== undefined;+ // OAuth 形态路由走 Runner Bearer;none 明确走无鉴权且由 host 剥凭证;缺省保持历史 API key。+ const oauth = config.auth?.method === 'oauth' ? config.auth.oauth : undefined;+ const isOAuth = oauth !== undefined;+ const noAuth = config.auth?.method === 'none';+ const strategy = isOAuth ? 'oauth-token' : noAuth ? 'none' : 'api-key-header';const routing: Partial<Record<AgentKind, RoutingDescriptor>> = {};const models: Partial<Record<AgentKind, CatalogModel[]>> = {};const agents: AgentKind[] = [];@@ -104,8 +109,9 @@ export function buildUserProvider(config: CustomProviderConfig): Provider {routing[agent] = toRouting(agent,rt.baseUrl,+ rt.requestPath,rt.headers,- isOAuth ? 'oauth-token' : 'api-key-header',+ strategy,rt.modelsUrl,rt.wireProtocol,);@@ -116,8 +122,12 @@ export function buildUserProvider(config: CustomProviderConfig): Provider {name: config.name,source: 'user',agents,- auth: isOAuth ? { method: 'oauth', oauth: config.auth!.oauth } : { method: 'apiKey' },- // API key 的额度语义明确;通用 OAuth 可能是订阅也可能按量计费,配置尚未显式声明前不猜。+ auth: isOAuth+ ? { method: 'oauth', oauth }+ : noAuth+ ? { method: 'none' }+ : { method: 'apiKey' },+ // API key / 无鉴权代理都属于用户自备接口;通用 OAuth 可能订阅也可能按量,未声明前不猜。...(isOAuth ? {} : { access: { kind: 'api' as const } }),routing,models,diff --git a/packages/responses-chat-bridge/src/__tests__/handler.test.ts b/packages/responses-chat-bridge/src/__tests__/handler.test.tsindex c1fba43cba..ad3e2e1f11 100644--- a/packages/responses-chat-bridge/src/__tests__/handler.test.ts+++ b/packages/responses-chat-bridge/src/__tests__/handler.test.ts@@ -73,6 +73,51 @@ describe('createResponsesChatHandler', () => {expect(res.ended).toBe(true);});+ it('preserves the upstream base query when applying the chat path', async () => {+ const fetchImpl = vi.fn(async () =>+ streamResponse([+ { id: 'chat_1', choices: [{ delta: {}, finish_reason: 'stop' }] },+ ]),+ ) as typeof fetch;+ const handler = createResponsesChatHandler({+ upstreamBase: 'https://provider.example/gateway?tenant=acme',+ chatCompletionsPath: '/infer?stream=1',+ buildHeaders: async () => ({}),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({ parsedBody: { model: 'm', input: 'hi' }, res: res as never });+ expect(fetchImpl).toHaveBeenCalledWith(+ 'https://provider.example/gateway/infer?tenant=acme&stream=1',+ expect.anything(),+ );+ });++ it.each([+ ['an invalid upstream base URL', 'ftp://provider.example/v1', '/chat/completions'],+ ['an invalid chat path', 'https://provider.example/v1', '//attacker.example/chat'],+ ['a raw non-ASCII chat path', 'https://provider.example/v1', '/café'],+ ['a control character in the chat path', 'https://provider.example/v1', '/chat\u007f'],+ ['a backslash in the chat path', 'https://provider.example/v1', '/v1\\chat'],+ ['an incomplete percent escape', 'https://provider.example/v1', '/chat%2'],+ ['an invalid percent escape', 'https://provider.example/v1', '/%ZZ'],+ ])('reports %s as configuration failure before fetching', async (_case, upstreamBase, chatCompletionsPath) => {+ const fetchImpl = vi.fn() as unknown as typeof fetch;+ const buildHeaders = vi.fn(async () => ({ authorization: 'Bearer secret' }));+ const handler = createResponsesChatHandler({+ upstreamBase,+ chatCompletionsPath,+ buildHeaders,+ }, { fetchImpl });+ const res = new FakeResponse();++ await handler.handle({ parsedBody: { model: 'm', input: 'hi' }, res: res as never });++ expect(res.status).toBe(502);+ expect(res.chunks.join('')).toContain('invalid_upstream_config');+ expect(fetchImpl).not.toHaveBeenCalled();+ expect(buildHeaders).not.toHaveBeenCalled();+ });+it('accepts a final SSE data event without a trailing newline', async () => {const fetchImpl = vi.fn(async () => new Response('data: {"id":"chat_tail","choices":[{"delta":{"content":"tail"},"finish_reason":"stop"}]}',diff --git a/packages/responses-chat-bridge/src/__tests__/translate-request.test.ts b/packages/responses-chat-bridge/src/__tests__/translate-request.test.tsindex 3416fd870e..3ef920c5cd 100644--- a/packages/responses-chat-bridge/src/__tests__/translate-request.test.ts+++ b/packages/responses-chat-bridge/src/__tests__/translate-request.test.ts@@ -114,6 +114,100 @@ describe('translateResponsesRequest', () => {expect((plain.messages[0] as { reasoning_content?: string }).reasoning_content).toBeUndefined();});+ it('injects the official Gemini thought-signature fallback on only the first call in each step', () => {+ const out = translateResponsesRequest(base({+ input: [+ {+ type: 'function_call',+ call_id: 'c1',+ name: 'Read',+ arguments: '{}',+ extra_content: {+ vendor: { cache_key: 'keep-me' },+ google: { other_extension: 'keep-me-too' },+ },+ },+ { type: 'function_call', call_id: 'c2', name: 'Search', arguments: '{}' },+ { type: 'function_call_output', call_id: 'c1', output: 'ok' },+ { type: 'function_call_output', call_id: 'c2', output: 'ok' },+ ],+ }), { capabilities: { googleThoughtSignaturePlaceholder: true } });+ const assistant = out.messages[0] as {+ tool_calls?: Array<{ extra_content?: { google?: { thought_signature?: string } } }>;+ };+ expect(assistant.tool_calls?.[0]?.extra_content).toEqual({+ vendor: { cache_key: 'keep-me' },+ google: {+ other_extension: 'keep-me-too',+ thought_signature: 'skip_thought_signature_validator',+ },+ });+ expect(assistant.tool_calls?.[1]?.extra_content).toBeUndefined();++ const plain = translateResponsesRequest(base({+ input: [{ type: 'function_call', call_id: 'c1', name: 'Read', arguments: '{}' }],+ }));+ expect(+ (plain.messages[0] as { tool_calls?: Array<{ extra_content?: unknown }> })+ .tool_calls?.[0]?.extra_content,+ ).toBeUndefined();+ });++ it.each([+ '',+ ' ',+ 123,+ { malformed: true },+ ])('replaces an invalid Gemini thought signature: %j', (thoughtSignature) => {+ const out = translateResponsesRequest(base({+ input: [{+ type: 'function_call',+ call_id: 'c1',+ name: 'Read',+ arguments: '{}',+ extra_content: {+ google: { thought_signature: thoughtSignature as string },+ },+ }],+ }), { capabilities: { googleThoughtSignaturePlaceholder: true } });+ expect(+ (out.messages[0] as {+ tool_calls?: Array<{ extra_content?: { google?: { thought_signature?: string } } }>;+ }).tool_calls?.[0]?.extra_content?.google?.thought_signature,+ ).toBe('skip_thought_signature_validator');+ });++ it('drops malformed Google tool-call metadata instead of spreading it as an object', () => {+ const input = base({+ input: [{+ type: 'function_call',+ call_id: 'c1',+ name: 'Read',+ arguments: '{}',+ extra_content: {+ vendor: { cache_key: 'keep-me' },+ google: 'malformed',+ },+ }],+ });+ const plain = translateResponsesRequest(input);+ expect(+ (plain.messages[0] as { tool_calls?: Array<{ extra_content?: unknown }> })+ .tool_calls?.[0]?.extra_content,+ ).toEqual({ vendor: { cache_key: 'keep-me' } });++ const gemini = translateResponsesRequest(input, {+ capabilities: { googleThoughtSignaturePlaceholder: true },+ });+ expect(+ (gemini.messages[0] as { tool_calls?: Array<{ extra_content?: unknown }> })+ .tool_calls?.[0]?.extra_content,+ ).toEqual({+ vendor: { cache_key: 'keep-me' },+ google: { thought_signature: 'skip_thought_signature_validator' },+ });+ });+it('normalizes custom tool history and flattens text-like tool output parts', () => {const out = translateResponsesRequest(base({input: [diff --git a/packages/responses-chat-bridge/src/handler.ts b/packages/responses-chat-bridge/src/handler.tsindex a0715f432c..9ea41a5b31 100644--- a/packages/responses-chat-bridge/src/handler.ts+++ b/packages/responses-chat-bridge/src/handler.ts@@ -35,16 +35,33 @@ function writeSse(res: ServerResponse, event: unknown, sequenceNumber: number):res.write(`event: ${event.type}\ndata: ${JSON.stringify(payload)}\n\n`);}-// 去尾部斜杠。不用 /\/*$/ 正则——超长 '/' 串上会 O(n²) 回溯(CodeQL js/polynomial-redos)。-function trimTrailingSlashes(s: string): string {- let end = s.length;- while (end > 0 && s.charCodeAt(end - 1) === 0x2f) end -= 1;- return s.slice(0, end);-}-function joinUrl(base: string, path: string): string {const normalizedPath = path.startsWith('/') ? path : `/${path}`;- return `${trimTrailingSlashes(base)}${normalizedPath}`;+ if (+ normalizedPath.startsWith('//')+ || normalizedPath.includes('#')+ || normalizedPath.includes('\\')+ || /[^\u0021-\u007e]/.test(normalizedPath)+ || /%(?![0-9A-Fa-f]{2})/.test(normalizedPath)+ ) {+ throw new TypeError('invalid chat completions path');+ }+ const url = new URL(base);+ if (+ (url.protocol !== 'http:' && url.protocol !== 'https:')+ || url.username+ || url.password+ ) {+ throw new TypeError('invalid upstream base URL');+ }+ const queryIndex = normalizedPath.indexOf('?');+ const pathname = queryIndex === -1 ? normalizedPath : normalizedPath.slice(0, queryIndex);+ const pathQuery = queryIndex === -1 ? '' : normalizedPath.slice(queryIndex + 1);+ const baseQuery = url.search.slice(1);+ url.pathname = `${url.pathname.replace(/\/+$/, '')}${pathname}`;+ url.search = [baseQuery, pathQuery].filter(Boolean).join('&');+ url.hash = '';+ return url.toString();}function responsesError(status: number, code: string, message: string): Record<string, unknown> {@@ -109,6 +126,25 @@ export function createResponsesChatHandler(throw error;}+ let upstreamUrl: string;+ try {+ upstreamUrl = joinUrl(+ provider.upstreamBase,+ provider.chatCompletionsPath ?? '/chat/completions',+ );+ } catch (error) {+ log.error?.('responses-chat bridge invalid upstream configuration', {+ model: request.model,+ error: error instanceof Error ? error.message : String(error),+ });+ writeJson(+ res,+ 502,+ responsesError(502, 'invalid_upstream_config', 'provider upstream configuration is invalid'),+ );+ return;+ }+let providerHeaders: Record<string, string>;try {providerHeaders = await provider.buildHeaders();@@ -126,7 +162,7 @@ export function createResponsesChatHandler(res.once('close', abortUpstream);let upstream: Response;try {- upstream = await fetchImpl(joinUrl(provider.upstreamBase, provider.chatCompletionsPath ?? '/chat/completions'), {+ upstream = await fetchImpl(upstreamUrl, {method: 'POST',headers: {...providerHeaders,diff --git a/packages/responses-chat-bridge/src/translate-request.ts b/packages/responses-chat-bridge/src/translate-request.tsindex 196623903a..c8f492ba6b 100644--- a/packages/responses-chat-bridge/src/translate-request.ts+++ b/packages/responses-chat-bridge/src/translate-request.ts@@ -5,6 +5,7 @@ import {type ChatDeveloperRole,type ChatCompletionsRequest,type ChatMessage,+ type ChatToolCallExtraContent,type ResponsesContentPart,type ResponsesFunctionTool,type ResponsesInputItem,@@ -15,6 +16,15 @@ function isPlainObject(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null && !Array.isArray(value);}+function cloneToolCallExtraContent(value: unknown): ChatToolCallExtraContent | undefined {+ if (!isPlainObject(value)) return undefined;+ const { google, ...rest } = value;+ return {+ ...rest,+ ...(isPlainObject(google) ? { google: { ...google } } : {}),+ };+}+function stringifyToolOutput(output: unknown): string {if (typeof output === 'string') return output;if (Array.isArray(output)) {@@ -82,10 +92,14 @@ interface TranslateInputOptions {developerRole: ChatDeveloperRole;/** thinking 模型:为带 tool_calls 但缺 reasoning_content 的 assistant 消息注入占位。 */toolCallReasoningPlaceholder: boolean;+ /** Gemini 3 OpenAI 兼容层:为每步首个回放 tool call 注入官方允许的签名跳过值。 */+ googleThoughtSignaturePlaceholder: boolean;}/** cc-switch 的占位口径:kimi/DeepSeek 要求 tool_call assistant 消息带非空 reasoning_content。 */const TOOL_CALL_REASONING_PLACEHOLDER = 'tool call';+/** Google 官方文档允许在无法取得原始签名的注入式 function call 上使用的校验跳过值。 */+const GOOGLE_THOUGHT_SIGNATURE_PLACEHOLDER = 'skip_thought_signature_validator';function flushAssistant(messages: ChatMessage[],@@ -99,6 +113,22 @@ function flushAssistant(if (hasToolCalls && opts.toolCallReasoningPlaceholder && !pending.reasoning_content) {pending.reasoning_content = TOOL_CALL_REASONING_PLACEHOLDER;}+ if (hasToolCalls && opts.googleThoughtSignaturePlaceholder) {+ const firstCall = pending.tool_calls?.[0];+ const thoughtSignature = firstCall?.extra_content?.google?.thought_signature;+ if (+ firstCall+ && (typeof thoughtSignature !== 'string' || thoughtSignature.trim().length === 0)+ ) {+ firstCall.extra_content = {+ ...firstCall.extra_content,+ google: {+ ...firstCall.extra_content?.google,+ thought_signature: GOOGLE_THOUGHT_SIGNATURE_PLACEHOLDER,+ },+ };+ }+ }messages.push(pending);return null;}@@ -170,10 +200,12 @@ function translateInput(input: ResponsesRequest['input'], opts: TranslateInputOp}assistant ??= { role: 'assistant', content: null, tool_calls: [] };assistant.tool_calls ??= [];+ const extraContent = cloneToolCallExtraContent(item.extra_content);assistant.tool_calls.push({id: item.call_id,type: 'function',function: { name: item.name, arguments: item.arguments },+ ...(extraContent ? { extra_content: extraContent } : {}),});continue;}@@ -273,6 +305,7 @@ export function translateResponsesRequest(const messages = translateInput(input.input, {developerRole,toolCallReasoningPlaceholder: capabilities.toolCallReasoningPlaceholder === true,+ googleThoughtSignaturePlaceholder: capabilities.googleThoughtSignaturePlaceholder === true,});if (input.instructions) {messages.unshift({ role: developerRole, content: input.instructions });diff --git a/packages/responses-chat-bridge/src/types.ts b/packages/responses-chat-bridge/src/types.tsindex 528f030a99..459e08999e 100644--- a/packages/responses-chat-bridge/src/types.ts+++ b/packages/responses-chat-bridge/src/types.ts@@ -23,6 +23,14 @@ export type ResponsesContentPart = ResponsesInputTextPart | ResponsesInputImageP[key: string]: unknown;};+export interface ChatToolCallExtraContent {+ [key: string]: unknown;+ google?: {+ [key: string]: unknown;+ thought_signature?: string;+ };+}+export type ResponsesInputItem =| {type?: 'message';@@ -34,6 +42,7 @@ export type ResponsesInputItem =call_id: string;name: string;arguments: string;+ extra_content?: ChatToolCallExtraContent;}| {type: 'function_call_output';@@ -85,6 +94,8 @@ export interface ChatAssistantMessage {id: string;type: 'function';function: { name: string; arguments: string };+ /** OpenAI 兼容层的厂商扩展;当前仅用于 Google Gemini thought signature。 */+ extra_content?: ChatToolCallExtraContent;}>;}@@ -139,6 +150,12 @@ export interface ChatBridgeCapabilities {* 开启后把具名 / required 的 tool_choice 降级为 'auto'。*/forceAutoToolChoice?: boolean;+ /**+ * Gemini 3 在工具结果下一轮强制校验 thought signature。Responses 历史不承载 Google 的+ * `tool_calls[].extra_content`,开启后按 Google 官方兼容说明给每步首个 call 写入+ * `skip_thought_signature_validator`,避免桥接历史在首个工具调用后稳定 400。+ */+ googleThoughtSignaturePlaceholder?: boolean;}export interface ChatBridgeLogger {