Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(providers): reject credentials embedded in model discovery URLs (#3988)
elfcvf568d153c179
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 184bd4eec5..8f95bc1c69 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@@ -72,6 +72,25 @@ afterEach(() => {});describe('validateCustomProviderConfig (per-runtime)', () => {+ it.each(['user@', ':secret@', 'user:secret@', 'us%65r:s%65cret@'])(+ 'rejects credentials in modelsUrl without exposing them: %s',+ (userinfo) => {+ expect(validateCustomProviderConfig({+ ...valid,+ runtimes: {+ codex: {+ ...valid.runtimes.codex!,+ modelsUrl: `https://${userinfo}openrouter.ai/api/v1/models`,+ },+ },+ })).toEqual({+ ok: false,+ code: 'INVALID_PARAMS',+ message: "runtime 'codex' modelsUrl must not contain embedded credentials",+ });+ },+ );+it('accepts a valid single-runtime config', () => {expect(validateCustomProviderConfig(valid)).toEqual({ ok: true });});diff --git a/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.tsindex 038f84e6f0..5f742735d2 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts@@ -21,6 +21,16 @@ function fakeResponse(status: number, body: string): Response {}describe('buildModelsFetchRequest', () => {+ it.each(+ (['baseUrl', 'modelsUrl'] as const).flatMap((field) =>+ ['user@', ':secret@', 'user:secret@', 'us%65r:s%65cret@'].map((userinfo) => ({ field, userinfo })),+ ),+ )('rejects credentials in $field before building a request: $userinfo', ({ field, userinfo }) => {+ expect(() => buildModelsFetchRequest(spec({+ [field]: `https://${userinfo}api.acme.example/anthropic/v1/models`,+ }))).toThrow('model discovery requires HTTP(S) URLs without embedded credentials');+ });+it('derives {base}/v1/models for non-/vN baseUrl; appends /models when baseUrl ends with /vN', () => {expect(buildModelsFetchRequest(spec()).url).toBe('https://api.acme.example/anthropic/v1/models');expect(@@ -116,6 +126,24 @@ describe('buildModelsFetchRequest', () => {});describe('fetchProviderModels', () => {+ it.each(+ (['baseUrl', 'modelsUrl'] as const).flatMap((field) =>+ ['user@', ':secret@', 'user:secret@', 'us%65r:s%65cret@'].map((userinfo) => ({ field, userinfo })),+ ),+ )('does not dispatch a request with credentials in $field: $userinfo', async ({ field, userinfo }) => {+ const fetchImpl = vi.fn<typeof fetch>();+ const result = await fetchProviderModels(spec({+ [field]: `https://${userinfo}api.acme.example/anthropic/v1/models`,+ authMethod: 'apiKey',+ }), fetchImpl);+ expect(result).toEqual({+ ok: false,+ code: 'UNKNOWN',+ detail: 'model discovery requires HTTP(S) URLs without embedded credentials',+ });+ expect(fetchImpl).not.toHaveBeenCalled();+ });+it.each([{baseUrl: 'https://remote.example/v1',diff --git a/apps/desktop/src/main/maker-host/custom-provider-store.ts b/apps/desktop/src/main/maker-host/custom-provider-store.tsindex 23b0eda15e..54b34b36a7 100644--- a/apps/desktop/src/main/maker-host/custom-provider-store.ts+++ b/apps/desktop/src/main/maker-host/custom-provider-store.ts@@ -343,6 +343,9 @@ function validateRuntime(agent: string, rt: unknown): ValidationResult {if (u.protocol !== 'http:' && u.protocol !== 'https:') {return invalid(`runtime '${agent}' modelsUrl must be http(s)`);}+ if (u.username || u.password) {+ return invalid(`runtime '${agent}' modelsUrl must not contain embedded credentials`);+ }} catch {return invalid(`runtime '${agent}' modelsUrl is not a valid URL`);}diff --git a/apps/desktop/src/main/maker-host/provider-model-fetch.ts b/apps/desktop/src/main/maker-host/provider-model-fetch.tsindex daf7cf9a4e..4442aea9ee 100644--- a/apps/desktop/src/main/maker-host/provider-model-fetch.ts+++ b/apps/desktop/src/main/maker-host/provider-model-fetch.ts@@ -28,6 +28,7 @@ import { outboundFetch } from './outbound-fetch.js';const FETCH_TIMEOUT_MS = 10_000;/** 失败响应体最多读取的字节数(分类只看前几 KB)。 */const MAX_ERROR_BODY_BYTES = 16 * 1024;+const INVALID_DISCOVERY_URL = 'model discovery requires HTTP(S) URLs without embedded credentials';/** 一次「获取模型列表」的完整参数(表单值内存透传,不落盘)。 */export interface ProviderModelsFetchSpec {@@ -64,13 +65,17 @@ export interface ProviderModelsFetchResult {detail?: string;}-/** 两个 URL 是否同源(scheme + host + 端口)。任一解析失败视为不同源(fail-closed)。 */-function sameOrigin(a: string, b: string): boolean {+/** origin 不含 userinfo;先独立验证地址,错误中不带原始 URL 或解析器异常。 */+function parseModelsFetchUrl(value: string): URL {try {- return new URL(a).origin === new URL(b).origin;+ const url = new URL(value);+ if ((url.protocol === 'http:' || url.protocol === 'https:') && !url.username && !url.password) {+ return url;+ }} catch {- return false;+ // URL 解析器的异常可能包含凭据,只返回固定的校验说明。}+ throw new Error(INVALID_DISCOVERY_URL);}function withoutCredentialHeaders(@@ -94,6 +99,9 @@ function normalizedHeaders(headers: Record<string, string> | undefined): Record</** 构造列模型请求(纯函数,单测直断言)。鉴权头组合与 buildProbeRequest 同口径。 */export function buildModelsFetchRequest(spec: ProviderModelsFetchSpec): { url: string; init: RequestInit } {+ const baseUrl = parseModelsFetchUrl(spec.baseUrl);+ const explicit = spec.modelsUrl?.trim();+ const modelsUrl = explicit ? parseModelsFetchUrl(explicit) : null;const mustStripCredentialHeaders =!!spec.apiKey || spec.authMethod === 'none' || spec.authMethod === 'oauth';const headers: Record<string, string> = mustStripCredentialHeaders@@ -116,9 +124,8 @@ export function buildModelsFetchRequest(spec: ProviderModelsFetchSpec): { url: s}// modelsUrl 是用户不可见的隐藏字段(预设/配置快照)。只有与 baseUrl 同源才采用——// 防止用户改了 baseUrl 后,key 仍被发往快照里的旧主机 / 被降级成明文(现有预设全部同源)。- const explicit = spec.modelsUrl?.trim();return {- url: explicit && sameOrigin(explicit, spec.baseUrl) ? explicit : deriveModelsDiscoveryUrl(spec.baseUrl),+ url: explicit && modelsUrl?.origin === baseUrl.origin ? explicit : deriveModelsDiscoveryUrl(spec.baseUrl),init: { method: 'GET', headers },};}@@ -152,7 +159,13 @@ export async function fetchProviderModels(detail: 'no-auth provider model discovery requires loopback URLs',};}- const { url, init } = buildModelsFetchRequest(spec);+ let request: ReturnType<typeof buildModelsFetchRequest>;+ try {+ request = buildModelsFetchRequest(spec);+ } catch {+ return { ok: false, code: 'UNKNOWN', detail: INVALID_DISCOVERY_URL };+ }+ const { url, init } = request;let res: Response;try {res = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.tsindex 803d27a692..02655063ea 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts@@ -3233,6 +3233,23 @@ describe('provider:models-fetch handler', () => {expect(deps.fetchModels).not.toHaveBeenCalled();});+ it.each(+ (['baseUrl', 'modelsUrl'] as const).flatMap((field) =>+ ['user@', ':secret@', 'user:secret@', 'us%65r:s%65cret@'].map((userinfo) => ({ field, userinfo })),+ ),+ )('rejects credentials in model discovery $field at IPC ingress: $userinfo', async ({ field, userinfo }) => {+ const harness = new IpcHarness();+ const deps = makeDeps();+ registerProviderHandlers(harness, deps);+ await expect(harness.invoke(MAKER_INVOKE.PROVIDER_MODELS_FETCH, {+ agent: 'codex',+ authMethod: 'apiKey',+ baseUrl: 'https://x.example/v1',+ [field]: `https://${userinfo}x.example/v1/models`,+ })).rejects.toThrow(/INVALID_PARAMS/);+ expect(deps.fetchModels).not.toHaveBeenCalled();+ });+it('rejects malformed input with INVALID_PARAMS (bad agent / bad url / bad modelsUrl / bad headers)', async () => {const harness = new IpcHarness();const deps = makeDeps();diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.tsindex 7a11419d84..1b6110dc77 100644--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts@@ -463,7 +463,7 @@ function parseModelsFetchInput(input: unknown): ProviderModelsFetchSpec | null {const httpUrlOk = (v: string): boolean => {try {const u = new URL(v);- return u.protocol === 'http:' || u.protocol === 'https:';+ return (u.protocol === 'http:' || u.protocol === 'https:') && !u.username && !u.password;} catch {return false;}diff --git a/packages/model-providers/src/__tests__/presets.test.ts b/packages/model-providers/src/__tests__/presets.test.tsindex 535f3de75b..4e8c5eec68 100644--- a/packages/model-providers/src/__tests__/presets.test.ts+++ b/packages/model-providers/src/__tests__/presets.test.ts@@ -261,6 +261,52 @@ describe('sanitizePresets', () => {}});+ it.each(['user@', ':secret@', 'user:secret@', 'us%65r:s%65cret@'])(+ 'strips credential-bearing modelsUrl without dropping the preset: %s',+ (userinfo) => {+ const preset = {+ ...VALID_PRESET,+ runtimes: {+ codex: {+ baseUrl: 'https://x.example/v1',+ models: [{ id: 'm', name: 'M' }],+ modelsUrl: `https://${userinfo}x.example/v1/models`,+ },+ },+ };+ const out = sanitizePresets([preset]);+ expect(out).toHaveLength(1);+ expect(out[0]?.runtimes.codex).toEqual({+ baseUrl: 'https://x.example/v1',+ models: [{ id: 'm', name: 'M' }],+ });+ },+ );++ it.each(+ (['baseUrl', 'modelsUrl'] as const).flatMap((field) =>+ ['user@', ':secret@', 'user:secret@', 'us%65r:s%65cret@'].map((userinfo) => ({ field, userinfo })),+ ),+ )('removes only discovery sources with credentials in $field: $userinfo', ({ field, userinfo }) => {+ const source = {+ baseUrl: 'https://x.example/v1',+ modelsUrl: 'https://x.example/v1/models',+ wireProtocol: 'openai-responses',+ };+ const out = sanitizePresets([{+ ...VALID_PRESET,+ runtimes: {+ codex: {+ baseUrl: 'https://x.example/v1',+ models: [{ id: 'm', name: 'M' }],+ modelDiscovery: [source, { ...source, [field]: `https://${userinfo}x.example/v1/models` }],+ },+ },+ }]);+ expect(out).toHaveLength(1);+ expect(out[0]?.runtimes.codex?.modelDiscovery).toEqual([source]);+ });+it('modelDiscovery 只保留同源且协议合法的附加目录', () => {const source = {baseUrl: 'https://x.example/api/v1',diff --git a/packages/model-providers/src/catalog.ts b/packages/model-providers/src/catalog.tsindex f07bc495fd..ca85481aaa 100644--- a/packages/model-providers/src/catalog.ts+++ b/packages/model-providers/src/catalog.ts@@ -579,12 +579,12 @@ function isValidPreset(v: unknown): v is ProviderPreset {return true;}-/** 是否合法 http(s) URL(modelsUrl 归一化用)。 */+/** 是否为不含内嵌凭据的 http(s) URL(模型发现地址归一化用)。 */function isHttpUrl(v: unknown): boolean {if (typeof v !== 'string' || v.length === 0) return false;try {const u = new URL(v);- return u.protocol === 'https:' || u.protocol === 'http:';+ return (u.protocol === 'https:' || u.protocol === 'http:') && !u.username && !u.password;} catch {return false;}@@ -625,7 +625,7 @@ function isLegacyAnthropicPiRuntime(}/**- * runtime.modelsUrl 非法(非 http(s) URL)时剥掉该字段、保留预设本体——OSS 推错一个+ * runtime.modelsUrl 非法(非 http(s) URL 或含内嵌凭据)时剥掉该字段、保留预设本体——OSS 推错一个* 不可见字段不该让整条预设消失,更不该让用户保存时撞 main 侧 URL 校验无法自助修复。*/function normalizePresetRuntimeOptions(p: ProviderPreset): ProviderPreset {