Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugin): guard agent network targets
liugaowei64c2a8c3ecef
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.connection.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.connection.test.tsindex 3c07f9e410..cc3a9c50ea 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.connection.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.connection.test.ts@@ -64,6 +64,7 @@ function makeSlot(overrides: Partial<NetworkSlotDeps> = {}) {readSecret: () => null,getLoginEmail: () => null,fetchImpl,+ fetchPublicImpl: async () => ({ response: response(), release: async () => undefined }),readGhostMedia: async () => null,takeDirDeposit: () => null,writeSaveDeposit: async () => null,diff --git a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.file.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.file.test.tsindex bb490a88e1..dca4b55acd 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.file.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.file.test.ts@@ -51,6 +51,7 @@ function makeSlot(overrides: Partial<NetworkSlotDeps> = {}): {readSecret: () => null,getLoginEmail: () => null,fetchImpl: fetchImpl as unknown as NetworkSlotDeps['fetchImpl'],+ fetchPublicImpl: async () => ({ response: bytesResponse(), release: async () => undefined }),saveGhostMedia: async () => ({ url: 'cindy-media://blobs/a.png', hash: 'a'.repeat(64), ext: '.png' }),isSupportedMediaMime: () => false,readGhostMedia: async () => null,diff --git a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.oauth.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.oauth.test.tsindex bfaac1e86c..6225441efc 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.oauth.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.oauth.test.ts@@ -62,6 +62,7 @@ function makeSlot(params: {readSecret: () => null,getLoginEmail: () => null,fetchImpl: fetchImpl as unknown as NetworkSlotDeps['fetchImpl'],+ fetchPublicImpl: async () => ({ response: fakeResponse(), release: async () => undefined }),saveGhostMedia: async () => ({ url: 'cindy-media://blobs/a.png', hash: 'a'.repeat(64), ext: '.png' }),isSupportedMediaMime: () => false,readGhostMedia: async () => null,diff --git a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.tsindex 9e8f383b0f..02f6152435 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts@@ -96,10 +96,15 @@ function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {function makeSlot(overrides: Partial<NetworkSlotDeps> = {}): {slot: GhostNetworkSlot;fetchImpl: ReturnType<typeof vi.fn>;+ fetchPublicImpl: ReturnType<typeof vi.fn>;readSecret: ReturnType<typeof vi.fn>;saveGhostMedia: ReturnType<typeof vi.fn>;} {const fetchImpl = vi.fn(async () => fakeResponse());+ const fetchPublicImpl = vi.fn(async () => ({+ response: fakeResponse(),+ release: async () => undefined,+ }));const readSecret = vi.fn((_ghostId: string, key: string) =>key === 'brave_api_key' ? 'BSA-secret' : key === 'tavily_api_key' ? 'tvly-secret' : null,);@@ -116,6 +121,7 @@ function makeSlot(overrides: Partial<NetworkSlotDeps> = {}): {readSecret,getLoginEmail: () => '[email protected]',fetchImpl: fetchImpl as unknown as NetworkSlotDeps['fetchImpl'],+ fetchPublicImpl: fetchPublicImpl as unknown as NetworkSlotDeps['fetchPublicImpl'],saveGhostMedia: saveGhostMedia as unknown as NetworkSlotDeps['saveGhostMedia'],isSupportedMediaMime,// 缺省"查无此媒体":上传套件按需覆盖。@@ -126,7 +132,7 @@ function makeSlot(overrides: Partial<NetworkSlotDeps> = {}): {writeSaveDeposit: async () => null,...overrides,};- return { slot: new GhostNetworkSlot(deps), fetchImpl, readSecret, saveGhostMedia };+ return { slot: new GhostNetworkSlot(deps), fetchImpl, fetchPublicImpl, readSecret, saveGhostMedia };}const BRAVE_URL = 'https://api.search.brave.com/res/v1/web/search?q=hi';@@ -213,6 +219,8 @@ describe('networkSlot · 能力资格审', () => {callId: 'call-agent',}),).toMatchObject({ ok: true });+ expect(allowed.fetchPublicImpl).toHaveBeenCalledTimes(1);+ expect(allowed.fetchImpl).not.toHaveBeenCalled();const wrongOwner = makeSlot({getGhost: () => fakeGhost({ network: null }),@@ -238,6 +246,41 @@ describe('networkSlot · 能力资格审', () => {}),).toMatchObject({ ok: false });});++ it('Agent 未声明目标的 SSRF 守门失败时不回退普通 fetch', async () => {+ const guardedError = new Error('Blocked: resolves to private/internal/special-use IP address');+ const guardedFetch = vi.fn(async () => { throw guardedError; });+ const { slot, fetchImpl } = makeSlot({+ getGhost: () => fakeGhost({ network: null }),+ inFlightCallInfo: () => ({ ghostId: 'web-search', sessionId: 'session-1', channel: 'session' }),+ fetchPublicImpl: guardedFetch,+ });++ const result = await slot.handleFetchRequest('web-search', {+ url: 'https://localhost/private',+ callId: 'call-agent',+ });++ expect(result).toMatchObject({ ok: false });+ 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: [] } }),+ inFlightCallInfo: () => ({ ghostId: 'web-search', sessionId: 'session-1', channel: 'session' }),+ });++ const result = await slot.handleFetchRequest('web-search', {+ url: 'https://127.0.0.1/private',+ callId: 'call-agent',+ });++ expect(result).toMatchObject({ ok: true });+ expect(fetchImpl).toHaveBeenCalledTimes(1);+ expect(fetchPublicImpl).not.toHaveBeenCalled();+ });});describe('networkSlot · headers 消毒与凭证注入', () => {@@ -373,6 +416,34 @@ describe('networkSlot · 重定向逐跳守门', () => {expect(r.ok).toBe(false);if (!r.ok) expect(r.message).toContain('次数过多');});++ it('Agent 未声明目标的每一跳都重新经过 SSRF 守门', async () => {+ const release = vi.fn(async () => undefined);+ const guardedFetch = vi.fn()+ .mockResolvedValueOnce({+ response: redirectTo('https://cdn.example.com/next'),+ release,+ })+ .mockResolvedValueOnce({ response: fakeResponse(), release });+ const { slot, fetchImpl } = makeSlot({+ getGhost: () => fakeGhost({ network: null }),+ inFlightCallInfo: () => ({ ghostId: 'web-search', sessionId: 'session-1', channel: 'session' }),+ fetchPublicImpl: guardedFetch,+ });++ const result = await slot.handleFetchRequest('web-search', {+ url: 'https://example.com/start',+ callId: 'call-agent',+ });++ expect(result).toMatchObject({ ok: true });+ expect(guardedFetch.mock.calls.map(([target]) => target)).toEqual([+ 'https://example.com/start',+ 'https://cdn.example.com/next',+ ]);+ expect(release).toHaveBeenCalledTimes(2);+ expect(fetchImpl).not.toHaveBeenCalled();+ });});describe('networkSlot · 响应收敛', () => {diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex a7590007b1..c97c04c32c 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -341,6 +341,7 @@ 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,@@ -4846,6 +4847,15 @@ export function getGhostNetworkSlot(): GhostNetworkSlot {// init 收窄:body 的 Uint8Array 在 lib.dom 的 BodyInit 泛型下对不齐,// 运行时 undici 原生支持,按 RequestInit 交给 fetch。fetchImpl: (url, init) => outboundFetch(url, init as RequestInit),+ // 未在 manifest / 连接白名单声明的 Agent 在途目标不能复用普通+ // outboundFetch:它会重新解析 hostname,留下 DNS rebinding 窗口。+ // 这里每跳都以复核后的 DNS 地址建立 pinned dispatcher。+ fetchPublicImpl: (url, init) => fetchSingleHopWithSsrFGuard({+ url,+ init: init as RequestInit,+ signal: init.signal,+ requireHttps: true,+ }),// 媒体模式(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 b8a71aa021..13a21b5c32 100644--- a/apps/desktop/src/main/cindy-brain/networkSlot.ts+++ b/apps/desktop/src/main/cindy-brain/networkSlot.ts@@ -99,6 +99,17 @@ export interface NetworkSlotDeps {signal: AbortSignal;redirect: 'manual';}): Promise<Response>;+ /**+ * Agent 在途访问未声明公网目标时使用的单跳安全 fetch。实现必须在连接前+ * 复核 DNS 结果并把连接钉到已复核地址;调用方消费完响应后执行 release。+ */+ fetchPublicImpl(url: string, init: {+ method: string;+ headers: Record<string, string>;+ body?: string | Uint8Array;+ signal: AbortSignal;+ redirect: 'manual';+ }): Promise<{ response: Response; release: () => Promise<void> }>;/*** 上传通道:按指纹读"该意识名下"的总仓媒体字节(生产实现内做归属查账* ghostCanRead——出生自它 / 挂它画廊 / 用户显式过户;越权与不存在统一@@ -1100,6 +1111,7 @@ export class GhostNetworkSlot {const timer = setTimeout(() => controller.abort(), timeoutMs);timer.unref?.();let holdingMediaGate = false;+ const guardedFetchReleases: Array<() => Promise<void>> = [];try {this.deps.log?.info('ghost fetch-request start', {ghostId, callId, method, host: url.hostname, path: url.pathname,@@ -1231,13 +1243,20 @@ export class GhostNetworkSlot {};}}- response = await this.deps.fetchImpl(currentUrl.toString(), {+ const fetchInit = {method: currentMethod,headers: hopHeaders,...(currentBody !== undefined ? { body: currentBody } : {}),signal: controller.signal,- redirect: 'manual',- });+ redirect: 'manual' as const,+ };+ if (agentMediated && !hostDeclared(currentUrl.hostname)) {+ const guarded = await this.deps.fetchPublicImpl(currentUrl.toString(), fetchInit);+ guardedFetchReleases.push(guarded.release);+ response = guarded.response;+ } else {+ response = await this.deps.fetchImpl(currentUrl.toString(), fetchInit);+ }responseConnectionInjected = currentConnectionInjected;responseMethod = currentMethod;if (![301, 302, 303, 307, 308].includes(response.status)) break;@@ -1504,6 +1523,7 @@ export class GhostNetworkSlot {return { ok: false, message: `请求失败:${message}` };} finally {clearTimeout(timer);+ await Promise.allSettled(guardedFetchReleases.map((release) => release()));if (holdingMediaGate) this.mediaReadsInflight -= 1;const left = (this.inflight.get(ghostId) ?? 1) - 1;if (left <= 0) this.inflight.delete(ghostId);diff --git a/packages/browser-control-runtime/src/__tests__/ssrf-guard.test.ts b/packages/browser-control-runtime/src/__tests__/ssrf-guard.test.tsindex cb62370829..250c5395cd 100644--- a/packages/browser-control-runtime/src/__tests__/ssrf-guard.test.ts+++ b/packages/browser-control-runtime/src/__tests__/ssrf-guard.test.ts@@ -1,6 +1,9 @@import { describe, expect, it } from 'vitest';-import { fetchWithSsrFGuard } from '../shim/ssrf-runtime.js';+import {+ fetchSingleHopWithSsrFGuard,+ fetchWithSsrFGuard,+} from '../shim/ssrf-runtime.js';import {isBlockedHostnameOrIp,isPrivateIpAddress,@@ -91,6 +94,15 @@ describe('fetchWithSsrFGuard thin shell', () => {await expect(fetchWithSsrFGuard({ url: 'http://10.0.0.5/' })).rejects.toThrow(/blocked/i);});+ it('blocks a hostname whose pinned DNS answer is private before a single-hop fetch', async () => {+ await expect(+ fetchSingleHopWithSsrFGuard({+ url: 'https://public.example/data',+ lookupFn: lookupAddresses([{ address: '127.0.0.1', family: 4 }]),+ }),+ ).rejects.toThrow(/blocked/i);+ });+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 1ea600cd3f..736eaf73e2 100644--- a/packages/browser-control-runtime/src/shim/ssrf-runtime.ts+++ b/packages/browser-control-runtime/src/shim/ssrf-runtime.ts@@ -100,6 +100,43 @@ async function guardHop(return { url, dispatcher };}+/**+ * Guard and execute exactly one manually redirected HTTP hop.+ *+ * Callers that own redirect semantics can re-run this function for every hop;+ * the returned dispatcher keeps the vetted DNS answers pinned until the+ * response body has been consumed and `release()` is called.+ */+export async function fetchSingleHopWithSsrFGuard(+ params: GuardedFetchOptions,+): Promise<{ response: Response; release: () => Promise<void> }> {+ const { url, dispatcher } = await guardHop(+ params.url,+ params.policy,+ params.lookupFn,+ params.requireHttps,+ );+ try {+ const fetchOptions = {+ ...params.init,+ signal: params.signal ?? params.init?.signal,+ redirect: 'manual' as const,+ dispatcher,+ };+ const response = (await undiciFetch(+ url.href,+ fetchOptions as unknown as Parameters<typeof undiciFetch>[1],+ )) as unknown as Response;+ return {+ response,+ release: () => closeDispatcher(dispatcher),+ };+ } catch (err) {+ await closeDispatcher(dispatcher);+ throw err;+ }+}+function stripSensitiveHeaders(init: RequestInit | undefined): RequestInit | undefined {if (!init?.headers) return init;const headers = new Headers(init.headers);