Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 远端 MCP 清理与闸门补全 R20 四案

yan1fff4e84d37b
diff --git a/apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.ts b/apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.ts
index 6ddf045c94..aa77214109 100644
--- a/apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.ts
@@ -49,6 +49,28 @@ describe('buildCcRemoteHttpMcpServers', () => {
expect(() => cleanup()).not.toThrow();
});
+ it('returns empty when collab is globally disabled even though the bridge still lists cindy_orca (R20 P2)', async () => {
+ // provider 层为工具面稳定在禁用时仍注册 cindy_orca — bridge 名单不
+ // 反映开关, 远端 cc 注入以同一全局闸门为准: 禁用即整个不注入。
+ const { bridge, registered } = fakeBridge();
+ const { servers, cleanup } = await buildCcRemoteHttpMcpServers(
+ { host: HOST, sessionId: 's1', workingDir: '/remote/repo' },
+ {
+ ensureBridgeStarted: async () => ({
+ port: 38080,
+ serverNames: ['cindy_orca', 'orca_worker_bridge'],
+ bridge,
+ }),
+ ensureForward: vi.fn(async () => 47921),
+ getBridgeToken: async () => 'persistent-test-token',
+ isCollabEnabled: () => false,
+ },
+ );
+ expect(servers).toEqual({});
+ expect(registered.size).toBe(0); // 不注册任何 session ctx
+ expect(() => cleanup()).not.toThrow();
+ });
+
it('injects only whitelisted servers with the persistent token and ?session= routing', async () => {
const { bridge, registered } = fakeBridge();
const { servers } = await buildCcRemoteHttpMcpServers(
diff --git a/apps/desktop/src/main/maker-host/cc-remote-mcp.ts b/apps/desktop/src/main/maker-host/cc-remote-mcp.ts
index 2b484ca006..db4ac49092 100644
--- a/apps/desktop/src/main/maker-host/cc-remote-mcp.ts
+++ b/apps/desktop/src/main/maker-host/cc-remote-mcp.ts
@@ -68,6 +68,13 @@ export interface CcRemoteHttpMcpDeps {
} | null>;
ensureForward: (host: RemoteHost, localBridgePort: number) => Promise<number>;
synthesizeVendorOptions?: (sessionId: string) => Promise<Record<string, unknown>>;
+ /**
+ * Collab 全局开关 (plugin registry Tier 4)。缺省视为开启。provider 层在
+ * 禁用时仍注册 cindy_orca (keepOrcaProviderStable 保工具面稳定), bridge
+ * 名单不反映开关 — 远端注入必须以本闸门为准, 禁用时整个不注入
+ * (codex-connector R20 P2, 与 codex daemon 侧同一语义)。
+ */
+ isCollabEnabled?: () => boolean;
/**
* 持久 bridge token;测试注入 stub,生产默认 safeStorage 真源。
* 可同步可异步;返回 null = token 不可用,注入降级为空 (不得下发
@@ -106,7 +113,12 @@ export async function buildCcRemoteHttpMcpServers(
const empty = { servers: {}, cleanup: () => {} };
const started = await deps.ensureBridgeStarted();
if (!started) return empty;
- const names = started.serverNames.filter((n) => CC_REMOTE_HTTP_MCP_SERVER_NAMES.has(n));
+ // collab 全局禁用时 bridge 名单不反映开关 (keepOrcaProviderStable) —
+ // 远端注入以同一闸门为准, 整个不注入 (codex-connector R20 P2)。
+ const collabEnabled = deps.isCollabEnabled?.() ?? true;
+ const names = collabEnabled
+ ? started.serverNames.filter((n) => CC_REMOTE_HTTP_MCP_SERVER_NAMES.has(n))
+ : [];
if (names.length === 0) return empty;
const remotePort = await deps.ensureForward(args.host, started.port);
// token 可用性必须在 register 之前确认:null 时下发出 "Bearer null" 还
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 84ba063119..75e2e60bd5 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -626,6 +626,9 @@ export function getMaker(): Maker {
{
ensureBridgeStarted: ensureCodexMcpBridgeStartedForRemote,
ensureForward: ensureRemoteMcpForward,
+ // collab 全局禁用 (Tier 4) 时整个不注入 — bridge 名单不反映
+ // 开关 (codex-connector R20 P2, 与 codex daemon 侧同闸门)。
+ isCollabEnabled: () => pluginRegistry.isEnabled('collab'),
},
);
mcpCleanup = injected.cleanup;
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 453407270a..4e5651f87f 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -256,6 +256,7 @@ import {
} from '../messagePersistBroadcaster.js';
import { ensureCcManagerInstalledOrInstall } from '../remote-ssh/cc-manager-install.js';
import { ensureRemoteCodexMcpBridge } from '../remote-ssh/codex-remote-mcp.js';
+import { reconcileCodexAgentProxyEnv } from '../remote-ssh/agent-proxy.js';
import { ensureRemoteAgentInstalledOrInstall, ensureRemoteHostReady, getRemoteSshPool, isCcMgrUpgradeInFlight } from '../remote-ssh/index.js';
import {
recordSessionContextSnapshot,
@@ -4379,12 +4380,23 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (ensureAgentKind === 'codex') {
const host = getRemoteSshPool().get(remoteHostIdToEnsure);
if (host?.getStatus() === 'ready') {
+ // proxy 对账必须先于 MCP bootstrap:marker 漂移时 reconcile 会 pkill
+ // daemon, 若 MCP 先 bootstrap (带 token) 再被 pkill, transport
+ // startDaemon 重启的 daemon 只有 proxy env 没有 LIZI_MCP_TOKEN —
+ // 且 desiredFp===appliedFp 让 driftUnapplied 漏判, 协同 401 持续到
+ // 下次 token/代际变化 (codex-connector R20 P1)。先 reconcile 让
+ // 最后一次启动恒为携带双方的 MCP bootstrap;marker 一致时仅 1 次
+ // cat RTT 零副作用。
+ await reconcileCodexAgentProxyEnv(host);
await ensureRemoteCodexMcpBridge(host, {
ensureBridgeStarted: ensureCodexMcpBridgeStartedForRemote,
// config 漂移生效要重启 daemon, 重启会断同 host 的 live turn:
// 有 turn 在跑时 config 照写但 bootstrap 推迟 (driftUnapplied 持久,
// turn-done 挂钩补刀)。
hasLiveTurnOnHost: codexRemoteHasLiveTurn,
+ // collab 全局禁用 (Tier 4) 时按清理路径剥远端受管段 — bridge
+ // 名单不反映开关 (codex-connector R20 P2)。
+ isCollabEnabled: () => getPluginRegistry().isEnabled('collab'),
});
}
}
@@ -4422,6 +4434,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
void ensureRemoteCodexMcpBridge(host, {
ensureBridgeStarted: ensureCodexMcpBridgeStartedForRemote,
hasLiveTurnOnHost: codexRemoteHasLiveTurn,
+ isCollabEnabled: () => getPluginRegistry().isEnabled('collab'),
});
return;
}
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts
index f186ce15b4..4a45cf00cb 100644
--- a/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts
+++ b/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts
@@ -896,3 +896,119 @@ describe('codex-connector R19 regressions', () => {
expect(execCmds.join('\n')).not.toContain('bootstrap'); // 无清理对象不动作
});
});
+
+describe('codex-connector R20 regressions', () => {
+ it('cleanup path does not arm a forward, releases the stale one, and survives forward rejection (R20 P2)', async () => {
+ // 清理路径 (collab 禁用/token 失效) 剥 config + 清 env 都不经隧道:
+ // 不 arm 新 forward (forward 被拒不该阻断清理), 有旧 forward 则拆。
+ const stale = renderManagedMcpBlock({ remotePort: 47921, serverNames: SERVERS, tokenFingerprint: 'fp-old' });
+ let configContent = `model = "gpt-5.5"\n\n${stale}\n`;
+ const execCmds: string[] = [];
+ const closeCalls: Array<{ addr: string; port: number }> = [];
+ const host = {
+ id: 'host-cleanup-noforward',
+ exec: async (cmd: string, opts?: { input?: string }) => {
+ execCmds.push(cmd);
+ if (cmd.includes('cat "$CODEX_HOME/config.toml"')) {
+ return { exitCode: 0, stdout: configContent, stderr: '' };
+ }
+ if (cmd.includes('base64 -d')) {
+ const written = decodeWrittenConfig(opts?.input ? [opts.input] : []);
+ if (written !== null) configContent = written;
+ }
+ return { exitCode: 0, stdout: 'ok', stderr: '' };
+ },
+ ensureRemoteForward: async () => {
+ throw new Error('forwardIn rejected: administratively prohibited'); // arm 被拒
+ },
+ closeRemoteForward: async (addr: string, port: number) => {
+ closeCalls.push({ addr, port });
+ },
+ } as unknown as RemoteHost;
+ const deps = {
+ ensureBridgeStarted: async () => ({ port: 38080, serverNames: ['cindy_memory'], bridgeInstanceId: 'bridge-1' }),
+ hasLiveTurnOnHost: () => false,
+ };
+
+ // 先注入成功 (留下 bridgeLocalPort 记录) — 需要一个能 arm 的 fake。
+ const hostForInject = {
+ id: 'host-cleanup-noforward',
+ exec: async (cmd: string, opts?: { input?: string }) => {
+ if (cmd.includes('cat "$CODEX_HOME/config.toml"')) {
+ return { exitCode: 0, stdout: configContent, stderr: '' };
+ }
+ if (cmd.includes('base64 -d')) {
+ const written = decodeWrittenConfig(opts?.input ? [opts.input] : []);
+ if (written !== null) configContent = written;
+ }
+ return { exitCode: 0, stdout: 'ok', stderr: '' };
+ },
+ ensureRemoteForward: async (spec: { localHost: string; localPort: number; preferredRemotePort?: number }) => ({
+ remotePort: spec.preferredRemotePort ?? 47921,
+ close: async () => {},
+ }),
+ } as unknown as RemoteHost;
+ expect((await ensureRemoteCodexMcpBridge(hostForInject, {
+ ensureBridgeStarted: async () => ({ port: 38080, serverNames: SERVERS, bridgeInstanceId: 'bridge-1' }),
+ hasLiveTurnOnHost: () => false,
+ })).ok).toBe(true);
+ expect(prefsOf('host-cleanup-noforward')?.bridgeLocalPort).toBe(38080);
+
+ // collab 禁用 (serverNames 空):forward 被拒也不阻断清理, 旧 forward 被拆。
+ const result = await ensureRemoteCodexMcpBridge(host, deps);
+ expect(result.ok).toBe(true);
+ expect(execCmds.join('\n')).toContain('bootstrap'); // 清 env 完成
+ expect(configContent).not.toContain('cindy-remote-mcp'); // 受管段剥除
+ expect(closeCalls).toEqual([{ addr: '127.0.0.1', port: 38080 }]); // 旧 forward 拆除
+ expect(prefsOf('host-cleanup-noforward')?.bridgeLocalPort).toBeUndefined();
+ });
+
+ it('writes the remote config with umask 077 (R20 P2: secrets stay unreadable to other local users)', async () => {
+ const { host, execCmds } = fakeHost('host-config-umask', '');
+ const result = await ensureRemoteCodexMcpBridge(host, {
+ ensureBridgeStarted: async () => ({ port: 38080, serverNames: SERVERS, bridgeInstanceId: 'bridge-1' }),
+ hasLiveTurnOnHost: () => false,
+ });
+ expect(result.ok).toBe(true);
+ const writeCmd = execCmds.find((c) => c.includes('base64 -d'));
+ expect(writeCmd).toBeTruthy();
+ expect(writeCmd).toContain('umask 077');
+ });
+
+ it('strips the managed block and rebootstraps when collab is globally disabled (R20 P2)', async () => {
+ // provider 层为工具面稳定在 collab 禁用时仍注册 cindy_orca — bridge
+ // 名单不反映开关, 远端注入必须以全局闸门为准: 禁用即清理。
+ const stale = renderManagedMcpBlock({ remotePort: 47921, serverNames: SERVERS, tokenFingerprint: 'fp-old' });
+ let configContent = `model = "gpt-5.5"\n\n${stale}\n`;
+ const execCmds: string[] = [];
+ const host = {
+ id: 'host-collab-gate',
+ exec: async (cmd: string, opts?: { input?: string }) => {
+ execCmds.push(cmd);
+ if (cmd.includes('cat "$CODEX_HOME/config.toml"')) {
+ return { exitCode: 0, stdout: configContent, stderr: '' };
+ }
+ if (cmd.includes('base64 -d')) {
+ const written = decodeWrittenConfig(opts?.input ? [opts.input] : []);
+ if (written !== null) configContent = written;
+ }
+ return { exitCode: 0, stdout: 'ok', stderr: '' };
+ },
+ ensureRemoteForward: async (spec: { localHost: string; localPort: number; preferredRemotePort?: number }) => ({
+ remotePort: spec.preferredRemotePort ?? 47921,
+ close: async () => {},
+ }),
+ closeRemoteForward: async () => {},
+ } as unknown as RemoteHost;
+
+ const result = await ensureRemoteCodexMcpBridge(host, {
+ ensureBridgeStarted: async () => ({ port: 38080, serverNames: SERVERS, bridgeInstanceId: 'bridge-1' }),
+ hasLiveTurnOnHost: () => false,
+ isCollabEnabled: () => false, // 全局禁用
+ });
+ expect(result.ok).toBe(true);
+ expect(execCmds.join('\n')).toContain('bootstrap');
+ expect(configContent).not.toContain('cindy-remote-mcp'); // 剥段
+ expect(configContent).toContain('model = "gpt-5.5"'); // 用户配置保留
+ });
+});
diff --git a/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts b/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts
index 0512d6b708..d625d0de97 100644
--- a/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts
+++ b/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts
@@ -359,8 +359,11 @@ function writeConfigCmd(): string {
// (其他 MCP server 的 bearer / provider token), argv 在远端 `ps` / audit
// log 可见 — 与 bootstrap token 的 "secrets only live in stdin" 同约束
// (review: PR #778 codex-connector R17 P1)。
+ // umask 077:同一份 secret 内容也不得被远端其他本地用户读到 — 默认 022
+ // 下 tmp / config 与新建 $CODEX_HOME 都是世界可读的 (codex-connector
+ // R20 P2;与 ssh-keys.ts 的 0o700 私钥目录同语义)。
return `bash -c ${shellQuoteSh(
- `${codexHomePrefix(DEFAULT_INSTALL_ROOT)}; mkdir -p "$CODEX_HOME" && ` +
+ `umask 077; ${codexHomePrefix(DEFAULT_INSTALL_ROOT)}; mkdir -p "$CODEX_HOME" && ` +
`base64 -d > "$CODEX_HOME/config.toml.tmp" && ` +
`mv "$CODEX_HOME/config.toml.tmp" "$CODEX_HOME/config.toml"`,
)}`;
@@ -490,6 +493,32 @@ export function setRemoteMcpForwardRearmedHook(fn: (hostId: string, remotePort:
rearmedHook = fn;
}
+/**
+ * 清理路径 (serverNames 空) 拆除本 host 的 MCP forward 并摘除
+ * bridgeLocalPort 记录:collab 禁用 / token 失效后远端不再需要到本机
+ * bridge 的隧道, 残留 forward 是无谓的远端端口占用 (R20 P2 同源)。
+ * close 失败不阻断清理 (记录照摘, 服务端残留随连接死亡消失)。
+ */
+async function releaseRemoteMcpForwardIfAny(host: RemoteHost): Promise<void> {
+ const stale = readPortPrefs()[host.id]?.bridgeLocalPort;
+ if (stale === undefined) return;
+ try {
+ await host.closeRemoteForward('127.0.0.1', stale);
+ log.info('remote MCP forward released on cleanup path', { host: host.id, staleLocalPort: stale });
+ } catch (err) {
+ log.warn('release remote MCP forward failed (continuing cleanup)', {
+ host: host.id,
+ staleLocalPort: stale,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ const current = readPortPrefs()[host.id];
+ if (!current?.bridgeLocalPort) return;
+ const next = { ...readPortPrefs() };
+ delete next[host.id].bridgeLocalPort;
+ writePortPrefs(next);
+}
+
// ── per-host 串行锁与共用 forward 入口 ───────────────────────────────────────
/**
@@ -548,6 +577,13 @@ export function ensureRemoteCodexMcpBridge(
* 漂移并重试), 降级为远端无 MCP。未注入时按无 live turn 处理。
*/
hasLiveTurnOnHost?: (hostId: string) => boolean;
+ /**
+ * Collab 全局开关 (plugin registry Tier 4, 不依赖 workingDir)。缺省视为
+ * 开启。provider 层为工具面稳定在禁用时仍注册 cindy_orca
+ * (keepOrcaProviderStable), bridge 名单不反映开关 — 远端注入必须以本
+ * 闸门为准: 禁用时按清理路径剥受管段 (codex-connector R20 P2)。
+ */
+ isCollabEnabled?: () => boolean;
},
): Promise<EnsureRemoteCodexMcpResult> {
return withHostSerial(host.id, () => doEnsureRemoteCodexMcpBridge(host, deps));
@@ -558,6 +594,13 @@ async function doEnsureRemoteCodexMcpBridge(
deps: {
ensureBridgeStarted: () => Promise<RemoteMcpBridgeEndpoint | null>;
hasLiveTurnOnHost?: (hostId: string) => boolean;
+ /**
+ * Collab 全局开关 (plugin registry Tier 4, 不依赖 workingDir)。缺省视为
+ * 开启。provider 层为工具面稳定在禁用时仍注册 cindy_orca
+ * (keepOrcaProviderStable), bridge 名单不反映开关 — 远端注入必须以本
+ * 闸门为准: 禁用时按清理路径剥受管段 (codex-connector R20 P2)。
+ */
+ isCollabEnabled?: () => boolean;
},
): Promise<EnsureRemoteCodexMcpResult> {
try {
@@ -571,7 +614,14 @@ async function doEnsureRemoteCodexMcpBridge(
// session 获得本机 MCP 能力, 越出协同边界 (与 cc 侧白名单同语义)。
const filteredNames = bridge.serverNames.filter((n) => CODEX_REMOTE_MCP_SERVER_NAMES.has(n));
const token = getRemoteMcpBridgeToken();
- let serverNames = filteredNames;
+ const collabEnabled = deps.isCollabEnabled?.() ?? true;
+ let serverNames = collabEnabled ? filteredNames : [];
+ if (!collabEnabled && filteredNames.length > 0) {
+ // collab 全局禁用:bridge 名单不反映开关 (keepOrcaProviderStable) —
+ // 按清理路径剥受管段, 远端从「工具可见但调用必败」降级为不暴露
+ // (codex-connector R20 P2)。
+ log.info('collab globally disabled — cleaning remote managed block', { host: host.id });
+ }
if (serverNames.length > 0 && !token) {
// token 不可用但本 host 之前注入过 (appliedFingerprint 在):旧 config
// 与 daemon env 会让远端继续暴露 cindy_orca / orca_worker_bridge 而
@@ -593,7 +643,15 @@ async function doEnsureRemoteCodexMcpBridge(
// 指纹, bootstrap 传空 token — daemon 不再持有有效 token 正是清理目标。
const effectiveToken = token ?? '';
- const remotePort = await ensureRemotePort(host, bridge.port);
+ // 只有确实要下发 server 时才 arm forward:清理路径 (serverNames 空)
+ // 剥 config / 清 env 都不经隧道 — forward 被拒或扫描窗口耗尽不该
+ // 阻断清理, 否则旧受管段与 daemon env 残留成「持续暴露死 MCP」
+ // (codex-connector R20 P2)。清理路径下 MCP forward 本身也是清理对象:
+ // 有 bridgeLocalPort 记录就拆掉。
+ const remotePort = serverNames.length > 0 ? await ensureRemotePort(host, bridge.port) : 0;
+ if (serverNames.length === 0) {
+ await releaseRemoteMcpForwardIfAny(host);
+ }
// token 与 bridge 代际一起进指纹:token 轮换 (账号切换) 与 bridge 重建
// (旧 mcp-session-id 全失效, codex-connector P2) 都构成 config 漂移,