Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): gate SSH Pi loopback MCPs and recheck delegation permissions
zqchris0c74596ab1e2
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 48ffbc0497..ef9cb51b1e 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -2073,6 +2073,42 @@ describe('Bot canonical Session lifecycle', () => {await expect(service.select({ ...input, joined: true })).resolves.toMatchObject({ ok: true, joined: true });});+ it('rejects desktop-loopback custom MCPs on SSH Pi while keeping public HTTPS', async () => {+ h.customMcpConfigs.push({+ id: 'local-http', name: 'Local HTTP', transport: 'http',+ url: 'http://127.0.0.1:4321/mcp', headers: {},+ });+ h.mcpProviders.push(new CustomMcpProvider(h.customMcpConfigs[1]!, () => null));+ await invoke('local-db:bots:update', {+ id: 'bot-1', capabilities: { mcpServers: ['shared-docs', 'local-http'], mcpMode: 'allowlist' },+ });+ const created = await invoke('local-db:bots:create-canonical-session', {+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 2,+ });+ h.sqlite!.prepare('UPDATE sessions SET remote_host_id = ? WHERE id = ?').run('ssh-host', created.session.id);+ const service = createBotCapabilityService({ ...capabilityDeps, resolveBotAgentKind: async () => 'pi' });+ const input = { callerSessionId: created.session.id, kind: 'mcp' as const };+ await expect(service.list(input)).resolves.toMatchObject({+ capabilities: expect.arrayContaining([+ expect.objectContaining({ id: 'shared-docs', joined: true, available: true }),+ expect.objectContaining({ id: 'local-http', joined: true, available: false }),+ ]),+ });+ const snapshot = await hydrateBotProfileRuntime({+ id: created.session.id, agentKind: 'pi', workingDir: '/srv/bot', remoteHostId: 'ssh-host',+ workspaceKind: 'project', model: 'test-model', permissionMode: 'auto',+ }, { listMcpServers: capabilityDeps.listMcpServers });+ expect(snapshot).toMatchObject({+ configuredMcpServers: ['shared-docs', 'local-http'],+ resolvedMcpServers: ['shared-docs'],+ unavailableMcpServers: ['local-http'],+ });+ await expect(service.select({ ...input, id: 'local-http', joined: true }))+ .resolves.toMatchObject({ ok: false, errorCode: 'CAPABILITY_UNAVAILABLE' });+ await expect(service.select({ ...input, id: 'local-http', joined: false }))+ .resolves.toMatchObject({ ok: true, joined: false });+ });+it.each(['contacts', 'lsp'])('rejects gated %s despite registry enablement and keeps joined references removable', async (id) => {const created = await invoke('local-db:bots:create-canonical-session', { botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1 });const input = { callerSessionId: created.session.id, kind: 'toolset' as const, id };@@ -3394,6 +3430,41 @@ describe('Bot Session task end-to-end runtime', () => {}});+ it.each(['ask', 'auto', null])('aborts a child whose caller permission changed during persistence: %s', async (settledMode) => {+ await seedPair();+ let permission: string | null = 'bypassPermissions';+ let release!: () => void;+ const barrier = new Promise<void>((resolve) => { release = resolve; });+ let entered!: () => void;+ const atBoundary = new Promise<void>((resolve) => { entered = resolve; });+ const realTx = h.tx!;+ h.tx = async (name, args) => {+ if (name === 'bots.createDelegation') {+ entered();+ await barrier;+ }+ return realTx(name, args);+ };+ const runtime = createDelegationRuntime({ readCallerPermission: () => permission });+ const starting = runtime.delegation.startSessionTask({+ callerSessionId: 'session-1', objective: 'Run the requested checks.',+ });+ try {+ await atBoundary;+ permission = settledMode;+ release();+ const result = await starting;+ expect(result).toMatchObject({ ok: false, errorCode: 'CALLER_PERMISSION_UNAVAILABLE' });+ expect(runtime.started).toEqual([]);+ expect(h.sqlite!.prepare('SELECT status FROM bot_delegations').pluck().get()).toBe('failed');+ } finally {+ release();+ await starting.catch(() => undefined);+ h.tx = realTx;+ runtime.dispose();+ }+ });+it('does not start a child with stale permissions during a live permission change', async () => {await seedPair();const runtime = createDelegationRuntime({ readCallerPermission: () => null });diff --git a/apps/desktop/src/main/maker-host/botMcpCatalog.ts b/apps/desktop/src/main/maker-host/botMcpCatalog.tsindex ee96646e7e..3d9d74277c 100644--- a/apps/desktop/src/main/maker-host/botMcpCatalog.ts+++ b/apps/desktop/src/main/maker-host/botMcpCatalog.ts@@ -9,13 +9,13 @@ function isCustomMcpAvailable(input: {custom?: { transport: McpTransport };}): boolean {// SSH Codex receives only REMOTE_ALLOWED_SERVER_NAMES; user configs are not- // written into its daemon. Remote Claude serializes http/sse into startParams,- // and remote Pi tunnels custom servers through the existing URL gate.+ // written into its daemon. Remote Claude serializes http/sse into startParams.+ // Remote Pi connects to custom HTTP MCPs directly (`s.remote` is not tunneled).if (input.agentKind === 'codex') {return !input.remoteHostId && input.custom?.transport !== 'sse';}if (input.agentKind === 'pi' && input.custom) {- return isPiCustomMcpProviderAvailable(input.provider);+ return isPiCustomMcpProviderAvailable(input.provider, { remoteHostId: input.remoteHostId });}return true;}diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.tsindex b36a854af9..4177450297 100644--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts@@ -1566,6 +1566,23 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {title: input.session.title,source: input.session.source,};+ const liveCallerPermission = (): string | null =>+ deps.readCallerPermission+ ? deps.readCallerPermission(input.callerSessionId)+ : input.caller.permissionMode;+ const rejectStaleCallerPermission = async () => {+ await updateTerminal({+ delegationId,+ status: 'failed',+ lastError: 'CALLER_PERMISSION_UNAVAILABLE: 伙伴权限已变更,任务未启动',+ abortChild: true,+ });+ return {+ ok: false as const,+ errorCode: 'CALLER_PERMISSION_UNAVAILABLE',+ message: '伙伴权限正在切换或任务正在关闭,请稍后重试',+ };+ };try {await getDbClient().tx('bots.createDelegation', {maxActiveChildren,@@ -1602,6 +1619,11 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {createdAt,},});+ // Persistence itself is asynchronous (worker RPC). Recheck the live+ // permission generation/mode before the child becomes visible or starts.+ if (liveCallerPermission() !== callerPermission) {+ return await rejectStaleCallerPermission();+ }emitChanged({delegationId,parentSessionId: input.callerSessionId,@@ -1654,6 +1676,9 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {};}scheduleTimeout(delegationId, plan.limits.deadlineAt);+ if (liveCallerPermission() !== callerPermission) {+ return await rejectStaleCallerPermission();+ }const dispatchResult = await attemptDispatch(delegationId);return {ok: true,diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.tsindex e198b319c8..ae17650966 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts@@ -788,6 +788,35 @@ describe('piEnvironment per-session identity', () => {}});+ it('does not advertise desktop-loopback custom MCPs to SSH Pi', async () => {+ const configs = [+ { id: 'https', transport: 'http' as const, url: 'https://example.test/mcp' },+ { id: 'local-http', transport: 'http' as const, url: 'http://localhost:4321/mcp' },+ { id: 'ipv4', transport: 'http' as const, url: 'http://127.0.0.1:4321/mcp' },+ { id: 'ipv6', transport: 'http' as const, url: 'http://[::1]:4321/mcp' },+ ].map((config) => ({ ...config, name: config.id, headers: {}, updatedAt: 1 }));+ const builtin = makeProvider('cindy_memory');+ const providers = [builtin, ...configs.map((config) => new CustomMcpProvider(config, () => 'TOKEN_CANARY'))];+ const catalog = buildBotMcpCatalog({+ agentKind: 'pi', remoteHostId: 'ssh-host', providers,+ builtinNames: ['cindy_memory'], customServers: configs,+ });+ expect(catalog.filter((entry) => entry.available).map((entry) => entry.name))+ .toEqual(['cindy_memory', 'https']);+ expect(JSON.stringify(catalog)).not.toMatch(/TOKEN_CANARY|example.test|localhost|127\.0\.0\.1/);++ const config = await getPiExtraSpawnConfig(providers, noopLogger(), {+ workingDir: '', memoryEnabled: true, remoteHostId: 'ssh-host',+ });+ try {+ expect(config?.mcpBridge?.servers.map((server) => server.name)).toEqual(['cindy_memory', 'https']);+ expect(config?.mcpBridge?.servers.some((server) => server.remote && /localhost|127\.0\.0\.1|::1/.test(server.url)))+ .toBe(false);+ } finally {+ config?.disposeSessionCtx?.();+ }+ });+it('snapshots remote MCP lifecycle changes for new sessions while old leases keep their startup config', async () => {let enabled = true;let url = 'https://old.example.test/mcp';diff --git a/apps/desktop/src/main/mcp-integrations/piEnvironment.ts b/apps/desktop/src/main/mcp-integrations/piEnvironment.tsindex cdf9cd54e3..a8ba0e5aed 100644--- a/apps/desktop/src/main/mcp-integrations/piEnvironment.ts+++ b/apps/desktop/src/main/mcp-integrations/piEnvironment.ts@@ -57,7 +57,7 @@ import { pluginIdForKnownProviderName } from '../maker-host/plugins/builtin-plug// 直接取 plugins 模块的 registry 单例,不经 maker-host/index.ts —— 后者 import pi-host,// 从 mcp-integrations 反向 import 会成环。import { createPluginRegistry } from '../maker-host/plugins/index.js';-import { isAllowedRemoteMcpUrl } from './piMcpTransport.js';+import { isAllowedRemoteMcpUrl, isDesktopLoopbackMcpUrl } from './piMcpTransport.js';interface StartedPiBridge {bridge: CodexHttpBridge | null;@@ -191,6 +191,15 @@ export async function getPiExtraSpawnConfig(if (server.name === 'cindy_memory' && sessionCtx?.memoryEnabled !== true) return false;if (!isBotMcpServerAllowed(sessionCtx?.botMcpPolicy, server.name)) return false;if (!collabEnabled && REMOTE_COLLAB_SERVER_NAMES.has(server.name)) return false;+ // Custom HTTP MCPs are `s.remote` and skip the SSH URL rewriter. Desktop+ // loopback would hit the remote machine itself, not the desktop service.+ if (sessionCtx?.remoteHostId && server.remote) {+ try {+ if (isDesktopLoopbackMcpUrl(new URL(server.url))) return false;+ } catch {+ return false;+ }+ }const pluginId = pluginIdForKnownProviderName(server.name);if (pluginId) {return !disabledPluginIds.includes(pluginId)diff --git a/apps/desktop/src/main/mcp-integrations/piMcpTransport.ts b/apps/desktop/src/main/mcp-integrations/piMcpTransport.tsindex 7e2477f719..66eb8c17bf 100644--- a/apps/desktop/src/main/mcp-integrations/piMcpTransport.ts+++ b/apps/desktop/src/main/mcp-integrations/piMcpTransport.ts@@ -1,25 +1,36 @@import type { McpProvider } from '@cindy/maker-core';+/** Desktop-owned loopback hosts. Remote Pi's loopback is a different machine. */+export function isDesktopLoopbackMcpUrl(url: URL): boolean {+ const hostname = url.hostname.toLowerCase();+ return hostname === 'localhost' || hostname === '127.0.0.1' ||+ hostname === '::1' || hostname === '[::1]';+}+/** Pi direct MCP URLs must match the bridge's HTTPS / explicit loopback boundary. */export function isAllowedRemoteMcpUrl(url: URL): boolean {if (url.username || url.password) return false;if (url.protocol === 'https:') return true;- const hostname = url.hostname.toLowerCase();- return url.protocol === 'http:' && (- hostname === 'localhost' || hostname === '127.0.0.1' ||- hostname === '::1' || hostname === '[::1]'- );+ return url.protocol === 'http:' && isDesktopLoopbackMcpUrl(url);}/*** Registered user MCPs are HTTP/SSE configs, never in-process SDK servers.* Pi consumes their Codex serialization; a Claude SSE config cannot be its SDK fallback.* Inspect only the serialized route, without starting a bridge or returning secrets.+ * SSH Pi connects to custom HTTP MCPs directly (`s.remote` is not tunneled), so+ * desktop loopback URLs are unavailable whenever `remoteHostId` is set.*/-export function isPiCustomMcpProviderAvailable(provider: McpProvider): boolean {+export function isPiCustomMcpProviderAvailable(+ provider: McpProvider,+ opts?: { remoteHostId?: string | null },+): boolean {try {const config = provider.toCodexMcpConfig?.({ agentKind: 'pi', workingDir: '', vendorOptions: {} });- return config?.type === 'http' && isAllowedRemoteMcpUrl(new URL(config.url));+ if (config?.type !== 'http') return false;+ const url = new URL(config.url);+ if (!isAllowedRemoteMcpUrl(url)) return false;+ return !(opts?.remoteHostId && isDesktopLoopbackMcpUrl(url));} catch {return false;}