Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugin): close guarded network races
liugaowei878a8a98dd4f
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.tsindex 02557a4639..83a73a8ed3 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts@@ -266,6 +266,36 @@ describe('networkSlot · 能力资格审', () => {expect(fetchImpl).not.toHaveBeenCalled();});+ it('Agent 在 DNS 等待期间交卷时,dispatch 前最后一次复核会阻断请求', async () => {+ let live = true;+ const guardedFetch: NetworkSlotDeps['fetchPublicImpl'] = vi.fn(+ async (_url, _init, beforeDispatch) => {+ // 模拟代理选择 / DNS 守门 await 期间外层 ghost_call 已经交卷。+ live = false;+ await beforeDispatch();+ throw new Error('unreachable');+ },+ );+ const { slot, fetchImpl } = makeSlot({+ getGhost: () => fakeGhost({ network: null }),+ inFlightCallInfo: () =>+ live+ ? { ghostId: 'web-search', sessionId: 'session-1', channel: 'session' }+ : null,+ fetchPublicImpl: guardedFetch,+ });++ const result = await slot.handleFetchRequest('web-search', {+ url: 'https://example.com/data',+ callId: 'call-agent',+ });++ expect(result).toMatchObject({ ok: false });+ if (!result.ok) expect(result.message).toContain('Agent 调用已结束');+ expect(guardedFetch).toHaveBeenCalledTimes(1);+ expect(fetchImpl).not.toHaveBeenCalled();+ });+it('Agent 访问已声明目标仍使用声明边界,不额外阻断私有服务', async () => {const { slot, fetchImpl, fetchPublicImpl } = makeSlot({getGhost: () => fakeGhost({ network: { hosts: ['127.0.0.1'], secrets: [] } }),diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 8b6c258c5c..b19f37b9c3 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -342,7 +342,6 @@ import {hasGrokOAuthLogin,} from '../maker-host/grok-oauth-login.js';import { invalidateXaiBridgeAuth } from '../maker-host/xai-auth-invalidation-host.js';-import { fetchSingleHopWithSsrFGuard } from '@cindy/browser-control-runtime/ssrf-runtime';import {isModelDisabled,isModelDisabledWithUniqueLegacyBasename,@@ -351,7 +350,7 @@ import {} from '@cindy/model-providers';import { readModelDisableOverrides } from '../maker-host/model-disable-store.js';import { readProviderOrder } from '../maker-host/provider-order-store.js';-import { outboundFetch } from '../maker-host/outbound-fetch.js';+import { guardedOutboundFetch, outboundFetch } from '../maker-host/outbound-fetch.js';import { getSharedGhCliTokenSource } from '../git-context/ghCliTokenSource.js';import { hasCodexOAuthLoginReadOnly } from '../maker-host/codex-oauth-readiness.js';import { getUtilityModelChainProfiles } from '../utility-model/UtilityModelSelection.js';@@ -4851,12 +4850,8 @@ export function getGhostNetworkSlot(): GhostNetworkSlot {// 未在 manifest / 连接白名单声明的 Agent 在途目标不能复用普通// outboundFetch:它会重新解析 hostname,留下 DNS rebinding 窗口。// 这里每跳都以复核后的 DNS 地址建立 pinned dispatcher。- fetchPublicImpl: (url, init) => fetchSingleHopWithSsrFGuard({- url,- init: init as RequestInit,- signal: init.signal,- requireHttps: true,- }),+ fetchPublicImpl: (url, init, beforeDispatch) =>+ guardedOutboundFetch(url, init as RequestInit, beforeDispatch),// 媒体模式(as:'media'):字节直落总仓 + ghost-gallery 记账(出生=该// 意识,与 cindy 槽产物同一记账口径),走统一入库助手 ingestMedia// (规则 25)。mime 白名单同一来源(blobStore),槽内归一化后再判。diff --git a/apps/desktop/src/main/cindy-brain/networkSlot.ts b/apps/desktop/src/main/cindy-brain/networkSlot.tsindex e3da273c46..9e106c0dfc 100644--- a/apps/desktop/src/main/cindy-brain/networkSlot.ts+++ b/apps/desktop/src/main/cindy-brain/networkSlot.ts@@ -109,7 +109,10 @@ export interface NetworkSlotDeps {body?: string | Uint8Array;signal: AbortSignal;redirect: 'manual';- }): Promise<{ response: Response; release: () => Promise<void> }>;+ }, beforeDispatch: () => void | Promise<void>): Promise<{+ response: Response;+ release: () => Promise<void>;+ }>;/*** 上传通道:按指纹读"该意识名下"的总仓媒体字节(生产实现内做归属查账* ghostCanRead——出生自它 / 挂它画廊 / 用户显式过户;越权与不存在统一@@ -1259,7 +1262,15 @@ export class GhostNetworkSlot {return { ok: false, message: '当前 Agent 调用已结束,未声明目标不再允许访问' };}if (hopAgentMediated) {- const guarded = await this.deps.fetchPublicImpl(currentUrl.toString(), fetchInit);+ const guarded = await this.deps.fetchPublicImpl(+ currentUrl.toString(),+ fetchInit,+ () => {+ if (!hasLiveAgentAuthorization()) {+ throw new Error('当前 Agent 调用已结束,未声明目标不再允许访问');+ }+ },+ );guardedFetchReleases.push(guarded.release);response = guarded.response;} else {diff --git a/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.ts b/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.tsindex f110c7d4c3..cb0414f104 100644--- a/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.ts@@ -53,9 +53,11 @@ vi.mock('undici', async (importOriginal) => {import {createOutboundHttpAgent,+ guardedOutboundFetch,outboundFetch,outboundUndiciFetch,resetOutboundFetchStateForTest,+ rewritePinnedProxyDispatchOptions,resolveConnectOptions,resolveOutboundDispatcher,} from '../outbound-fetch.js';@@ -291,6 +293,49 @@ describe('resolveOutboundDispatcher', () => {});describe('outboundFetch', () => {+ it('rewrites proxy dial origin to the vetted IP while preserving the original Host', () => {+ const rewritten = rewritePinnedProxyDispatchOptions(+ {+ origin: 'https://api.example.com',+ path: '/data',+ method: 'GET',+ headers: ['accept', 'application/json'],+ },+ new URL('https://api.example.com/data'),+ '2001:db8::1',+ );++ expect(rewritten.origin).toBe('https://[2001:db8::1]');+ expect(rewritten.headers).toEqual([+ 'accept',+ 'application/json',+ 'host',+ 'api.example.com',+ ]);+ });++ it.each([+ 'http://127.0.0.1:7890',+ 'socks5://127.0.0.1:7891',+ ])('keeps the pinned public-target guard on the %s proxy path', async (proxyUrl) => {+ resolverState.resolve.mockResolvedValue(proxyUrl);+ const beforeDispatch = vi.fn(() => {+ throw new Error('authorization expired');+ });++ await expect(+ guardedOutboundFetch('https://93.184.216.34/data', { method: 'GET' }, beforeDispatch),+ ).rejects.toThrow('authorization expired');++ expect(resolverState.resolve).toHaveBeenCalledWith('https://93.184.216.34/data');+ expect(loggerState.debug).toHaveBeenCalledWith(+ 'creating outbound proxy dispatcher',+ expect.objectContaining({ protocol: 'https:' }),+ );+ expect(beforeDispatch).toHaveBeenCalledTimes(1);+ expect(undiciState.fetch).not.toHaveBeenCalled();+ });+it('passes the proxy dispatcher through to undici fetch', async () => {resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');await outboundFetch('https://platform.claude.com/v1/oauth/token', { method: 'POST' });diff --git a/apps/desktop/src/main/maker-host/outbound-fetch.ts b/apps/desktop/src/main/maker-host/outbound-fetch.tsindex f51b90b94e..d9661b5c07 100644--- a/apps/desktop/src/main/maker-host/outbound-fetch.ts+++ b/apps/desktop/src/main/maker-host/outbound-fetch.ts@@ -50,6 +50,10 @@ import {TunnelingHttpsAgent,type OutboundProxyTarget,} from '@cindy/anthropic-compat-proxy';+import {+ fetchSingleHopWithSsrFGuard,+ type SsrFPolicy,+} from '@cindy/browser-control-runtime/ssrf-runtime';import { createMakerLogger } from './logger-adapter.js';import { resolveDesktopOutboundProxy } from './outbound-proxy-resolver.js';@@ -415,6 +419,7 @@ function createProxyDispatcher(proxy: OutboundProxyTarget,protocol: 'http:' | 'https:',agentOptions: UndiciAgent.Options | undefined,+ targetServername?: string,): Dispatcher {log.debug('creating outbound proxy dispatcher', { proxy: proxy.url, protocol });const connect = resolveConnectOptions(agentOptions);@@ -424,7 +429,10 @@ function createProxyDispatcher(const tlsOptions =typeof connect === 'function'? { autoSelectFamilyAttemptTimeout: CONNECT_ATTEMPT_TIMEOUT_MS }- : ((connect ?? {}) as Record<string, unknown>);+ : {+ ...((connect ?? {}) as Record<string, unknown>),+ ...(targetServername ? { servername: targetServername } : {}),+ };return new UndiciAgent({...agentOptions,connect: createSocks5Connector(proxy, tlsOptions),@@ -435,6 +443,120 @@ function createProxyDispatcher(uri: proxy.url,...(proxy.authHeader ? { token: proxy.authHeader } : {}),connect,+ ...(targetServername ? { requestTls: { servername: targetServername } } : {}),+ });+}++function pinnedOrigin(address: string, upstream: URL): string {+ const host = address.includes(':') ? `[${address}]` : address;+ return `${upstream.protocol}//${host}${upstream.port ? `:${upstream.port}` : ''}`;+}++function withOriginalHost(+ headers: Dispatcher.DispatchOptions['headers'],+ host: string,+): Dispatcher.DispatchOptions['headers'] {+ if (Array.isArray(headers)) {+ const next = [...headers];+ for (let i = 0; i < next.length; i += 2) {+ if (String(next[i]).toLowerCase() === 'host') {+ next[i + 1] = host;+ return next;+ }+ }+ next.push('host', host);+ return next;+ }+ const next = { ...(headers ?? {}) } as Record<string, string | string[] | undefined>;+ for (const key of Object.keys(next)) {+ if (key.toLowerCase() === 'host') delete next[key];+ }+ next.host = host;+ return next;+}++/** @internal 导出供安全回归测试断言代理实际拨号目标与 Host 分离。 */+export function rewritePinnedProxyDispatchOptions(+ options: Dispatcher.DispatchOptions,+ upstream: URL,+ address: string,+): Dispatcher.DispatchOptions {+ return {+ ...options,+ origin: pinnedOrigin(address, upstream),+ headers: withOriginalHost(options.headers, upstream.host),+ };+}++/**+ * 代理出口不能让代理再次解析插件提供的域名,否则 DNS 守门与实际连接之间仍有+ * rebinding 窗口。包装层把下游连接目标改成已审核 IP,同时保留原始 Host 与 TLS SNI。+ * dispatcher 为单次请求所有,响应消费完由 SSRF shell 统一关闭。+ */+function createPinnedProxyDispatcher(+ proxy: OutboundProxyTarget,+ upstream: URL,+ addresses: readonly string[],+): Dispatcher {+ const address = addresses[0];+ if (!address) throw new Error(`Unable to resolve hostname: ${upstream.hostname}`);+ const base = createProxyDispatcher(+ proxy,+ upstreamProtocol(upstream),+ undefined,+ upstream.hostname,+ );+ return new (class extends Dispatcher {+ override dispatch(+ options: Dispatcher.DispatchOptions,+ handler: Dispatcher.DispatchHandler,+ ): boolean {+ return base.dispatch(rewritePinnedProxyDispatchOptions(options, upstream, address), handler);+ }++ override async close(): Promise<void> {+ await base.close();+ }++ override async destroy(): Promise<void> {+ await base.destroy();+ }+ })();+}++const PROXIED_PUBLIC_SSRF_POLICY: SsrFPolicy = {+ // Clash / sing-box / Surge 的 fake-IP DNS 只在已经确定走代理时放行;其它+ // RFC1918、loopback、link-local 与 metadata 地址仍由默认策略阻断。+ allowRfc2544BenchmarkRange: true,+ allowIpv6UniqueLocalRange: true,+};++/**+ * Agent 在途访问未声明公网目标的单跳出口:沿用 Desktop 的系统/PAC/env 代理判定,+ * 但无论直连还是代理都只连接 SSRF 守门已确认的地址。beforeDispatch 在代理解析与+ * DNS await 之后执行,避免已经结束的 callId 继续真正发包。+ */+export async function guardedOutboundFetch(+ url: string,+ init: RequestInit,+ beforeDispatch: () => void | Promise<void>,+): Promise<{ response: Response; release: () => Promise<void> }> {+ const upstream = new URL(url);+ const signal = init.signal ?? undefined;+ const proxy = await resolveProxyTarget(upstream, signal);+ return fetchSingleHopWithSsrFGuard({+ url,+ init,+ signal,+ requireHttps: true,+ ...(proxy+ ? {+ policy: PROXIED_PUBLIC_SSRF_POLICY,+ dispatcherFactory: ({ url: guardedUrl, pinned }) =>+ createPinnedProxyDispatcher(proxy, guardedUrl, pinned.addresses),+ }+ : {}),+ beforeDispatch,});}diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex 4b5a206423..a4eb767127 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -101,6 +101,9 @@直接声明,通过校验,在插件详情中如实展示,再由 Host 代码强制守门。- Agent 调用必须同时满足:`callId` 尚在途、绑定同一插件、绑定本地会话。已交卷、他插件、scheduler 脚本、Panel 和后台调用都不得借此绕过自主能力声明。+ 对未声明公网目标,Host 必须在每一跳完成代理选择与 DNS/IP 守门后、真正 dispatch+ 前再次复核同一 `callId`;直连与系统代理都只能连接该次守门确认的 IP,代理不得+ 重新解析插件提供的域名。- 安装/更新不以弹窗点击作为能力授权事实;**prompt 和前端展示都不构成安全边界**。- 新增或修改能力声明时,除同步编写手册与校验(下节 6)外,还必须同步 shared 类型、diff --git a/packages/browser-control-runtime/src/__tests__/ssrf-guard.test.ts b/packages/browser-control-runtime/src/__tests__/ssrf-guard.test.tsindex 250c5395cd..7f4e4ac445 100644--- a/packages/browser-control-runtime/src/__tests__/ssrf-guard.test.ts+++ b/packages/browser-control-runtime/src/__tests__/ssrf-guard.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import {fetchSingleHopWithSsrFGuard,@@ -103,6 +103,31 @@ describe('fetchWithSsrFGuard thin shell', () => {).rejects.toThrow(/blocked/i);});+ it('revalidates only after DNS and dispatcher selection, then closes without dispatching', async () => {+ const events: string[] = [];+ const close = vi.fn(async () => undefined);+ await expect(+ fetchSingleHopWithSsrFGuard({+ url: 'https://public.example/data',+ lookupFn: (async () => {+ events.push('dns');+ return [{ address: '93.184.216.34', family: 4 }];+ }) as unknown as LookupFn,+ dispatcherFactory: async () => {+ events.push('dispatcher');+ return { close } as never;+ },+ beforeDispatch: () => {+ events.push('revalidate');+ throw new Error('authorization expired');+ },+ }),+ ).rejects.toThrow('authorization expired');++ expect(events).toEqual(['dns', 'dispatcher', 'revalidate']);+ expect(close).toHaveBeenCalledTimes(1);+ });+it('does NOT block an allowlisted loopback host (regression: CDP control plane)', async () => {// With the host in allowedHostnames, the policy gate must pass it. We use a// port nothing listens on, so the only acceptable failure is a CONNECTIONdiff --git a/packages/browser-control-runtime/src/shim/ssrf-runtime.ts b/packages/browser-control-runtime/src/shim/ssrf-runtime.tsindex 736eaf73e2..52902dda7e 100644--- a/packages/browser-control-runtime/src/shim/ssrf-runtime.ts+++ b/packages/browser-control-runtime/src/shim/ssrf-runtime.ts@@ -26,6 +26,7 @@ import {createPinnedDispatcher,resolvePinnedHostnameWithPolicy,type LookupFn,+ type PinnedHostname,type SsrFPolicy,} from '../_generated/leaf/src/infra/net/ssrf.js';@@ -40,6 +41,18 @@ export interface GuardedFetchOptions {requireHttps?: boolean;maxRedirects?: number;lookupFn?: LookupFn;+ /**+ * 可选的安全出口适配器。DNS 守门完成后才调用;返回 undefined 时继续使用+ * 默认的直连 pinned dispatcher。调用方若返回自定义 dispatcher,必须保证它+ * 仍只连接 pinned.addresses 中的地址。+ */+ dispatcherFactory?: (params: {+ url: URL;+ pinned: PinnedHostname;+ policy?: SsrFPolicy;+ }) => Dispatcher | undefined | Promise<Dispatcher | undefined>;+ /** DNS 与出口选择完成后、真正 dispatch 前的最后一道同步/异步资格复核。 */+ beforeDispatch?: () => void | Promise<void>;/** Accepted for call-site compatibility; not used by the thin shell. */auditContext?: string;[extra: string]: unknown;@@ -92,11 +105,14 @@ async function guardHop(policy: SsrFPolicy | undefined,lookupFn: LookupFn | undefined,requireHttps: boolean | undefined,+ dispatcherFactory: GuardedFetchOptions['dispatcherFactory'],): Promise<{ url: URL; dispatcher: Dispatcher }> {const url = new URL(rawUrl);assertScheme(url, requireHttps);const pinned = await resolvePinnedHostnameWithPolicy(url.hostname, { policy, lookupFn });- const dispatcher = createPinnedDispatcher(pinned, undefined, policy);+ const dispatcher =+ (await dispatcherFactory?.({ url, pinned, policy }))+ ?? createPinnedDispatcher(pinned, undefined, policy);return { url, dispatcher };}@@ -115,8 +131,10 @@ export async function fetchSingleHopWithSsrFGuard(params.policy,params.lookupFn,params.requireHttps,+ params.dispatcherFactory,);try {+ await params.beforeDispatch?.();const fetchOptions = {...params.init,signal: params.signal ?? params.init?.signal,@@ -167,9 +185,12 @@ export async function fetchWithSsrFGuard(params: GuardedFetchOptions): Promise<Gparams.policy,params.lookupFn,params.requireHttps,+ params.dispatcherFactory,);dispatchers.push(dispatcher);+ await params.beforeDispatch?.();+// undici's fetch accepts a `dispatcher`; its RequestInit differs slightly// from the DOM lib types, so we go through `unknown` for the options bag.const fetchOptions = {