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 注入边界并修复 config 写入原子性

yan68cbb31a4414
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/collabProjectPolicy.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/collabProjectPolicy.test.ts
index 661b79d5aa..0d5109feaf 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/collabProjectPolicy.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/collabProjectPolicy.test.ts
@@ -56,23 +56,31 @@ describe('assertCollabProjectEnabled', () => {
it('allows remote project sessions for both agents without querying local fs policy', () => {
// 远端 workingDir 是远端机器路径, 本机 fs 的项目插件查询无意义 —— remote
- // 一律跳过 isPluginEnabled (main 侧边界: bridge 注入白名单兜底)。
- const isPluginEnabled = () => {
- throw new Error('must not query local fs policy for a remote session');
- };
+ // 跳过项目级查询 (isPluginEnabled 不带 workingDir 调用), 但用户级/全局级
+ // 开关仍生效。
+ for (const agentKind of ['codex', 'claude-code'] as const) {
+ const calls: Array<string | undefined> = [];
+ expect(() =>
+ assertCollabProjectEnabled(
+ { ...project, workingDir: '/remote/repo', remoteHostId: 'host-1', agentKind },
+ (_pluginId, workingDir) => {
+ calls.push(workingDir);
+ return true;
+ },
+ ),
+ ).not.toThrow();
+ expect(calls).toEqual([undefined]);
+ }
+ });
+ it('rejects remote sessions when collab is disabled at the user/global level', () => {
+ // review 回归:remote 提前 return 曾完全绕过 isPluginEnabled — 用户全局
+ // 禁用 Collab 时远端会话仍能建 Orca team, 与本地行为不一致。
expect(() =>
assertCollabProjectEnabled(
{ ...project, workingDir: '/remote/repo', remoteHostId: 'host-1', agentKind: 'codex' },
- isPluginEnabled,
+ () => false,
),
- ).not.toThrow();
-
- expect(() =>
- assertCollabProjectEnabled(
- { ...project, workingDir: '/remote/repo', remoteHostId: 'host-1', agentKind: 'claude-code' },
- isPluginEnabled,
- ),
- ).not.toThrow();
+ ).toThrow('[PRECONDITION_FAILED] collaboration is disabled for this project');
});
});
diff --git a/apps/desktop/src/main/maker-ipc/collabProjectPolicy.ts b/apps/desktop/src/main/maker-ipc/collabProjectPolicy.ts
index 3563b593f5..0d839d189b 100644
--- a/apps/desktop/src/main/maker-ipc/collabProjectPolicy.ts
+++ b/apps/desktop/src/main/maker-ipc/collabProjectPolicy.ts
@@ -19,7 +19,7 @@ export interface CollabProjectPolicyContext {
*/
export function assertCollabProjectEnabled(
context: CollabProjectPolicyContext,
- isPluginEnabled: (pluginId: 'collab', workingDir: string) => boolean,
+ isPluginEnabled: (pluginId: 'collab', workingDir?: string) => boolean,
): void {
const workingDir = typeof context.workingDir === 'string' ? context.workingDir.trim() : null;
if (
@@ -37,9 +37,17 @@ export function assertCollabProjectEnabled(
// (.cindy/plugins.json) 没有意义 —— 命中同路径的本机目录会误判, 查不到又
// 会误拒。远端项目级 collab 配置暂无对应机制; 协同边界由 "session 已在
// 远端建立" + bridge 注入白名单 (cindy_orca / orca_worker_bridge) 兜底。
+ // 但用户级/全局级 collab 开关 (registry Tier 4, 不依赖 workingDir) 对远端
+ // 同样有效 — 用户全局禁用 Collab 时远端会话一样拒绝, 与本地行为一致。
// TODO(follow-up): 远端项目级 collab 开关 (远端 fs 的 .cindy/plugins.json
// 或 per-host 设置) 有需求时再做。
if (context.remoteHostId) {
+ if (!isPluginEnabled('collab')) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'collaboration is disabled for this project',
+ );
+ }
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 3747383921..1b06d8344e 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
@@ -22,6 +22,42 @@ vi.mock('../../mcp-integrations/remoteMcpBridgeToken.js', () => ({
const SERVERS = ['cindy_orca', 'orca_worker_bridge'];
+/** 走完整 ensure 流程的 fake host:读 config 返回给定内容, 其余命令一律成功。 */
+function fakeHost(hostId: string, configContent: string) {
+ const execCmds: string[] = [];
+ const host = {
+ id: hostId,
+ exec: async (cmd: string) => {
+ execCmds.push(cmd);
+ if (cmd.includes('cat "$CODEX_HOME/config.toml"')) {
+ return { exitCode: 0, stdout: configContent, stderr: '' };
+ }
+ // daemon version 探活 / write / bootstrap 一律成功。
+ 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;
+ return { host, execCmds };
+}
+
+/**
+ * 从 write 命令里解出写入的 config 内容。依赖 writeConfigCmd 的
+ * `printf '%s' '<base64>'` 形态 (base64 无单引号):取命令里最长的类
+ * base64 token 解码。
+ */
+function decodeWrittenConfig(execCmds: string[]): string | null {
+ for (const cmd of execCmds) {
+ if (!cmd.includes('base64 -d')) continue;
+ const tokens = cmd.match(/[A-Za-z0-9+/=]{80,}/g) ?? [];
+ const b64 = tokens.sort((a, b) => b.length - a.length)[0];
+ if (b64) return Buffer.from(b64, 'base64').toString('utf-8');
+ }
+ return null;
+}
+
describe('renderManagedMcpBlock', () => {
it('renders one mcp_servers table per server with bridge url and bearer env var', () => {
const block = renderManagedMcpBlock({ remotePort: 47921, serverNames: SERVERS, tokenFingerprint: 'fp-test' });
@@ -313,26 +349,6 @@ describe('ensureRemoteCodexMcpBridge per-host serialization', () => {
});
describe('ensureRemoteCodexMcpBridge live-turn defer', () => {
- function fakeHost(hostId: string, configContent: string) {
- const execCmds: string[] = [];
- const host = {
- id: hostId,
- exec: async (cmd: string) => {
- execCmds.push(cmd);
- if (cmd.includes('cat "$CODEX_HOME/config.toml"')) {
- return { exitCode: 0, stdout: configContent, stderr: '' };
- }
- // daemon version 探活 / write / bootstrap 一律成功。
- 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;
- return { host, execCmds };
- }
-
const bridgeDeps = {
ensureBridgeStarted: async () => ({ port: 38080, serverNames: SERVERS }),
};
@@ -362,6 +378,9 @@ describe('ensureRemoteCodexMcpBridge live-turn defer', () => {
const joined = execCmds.join('\n');
expect(joined).toContain('base64 -d');
expect(joined).toContain('bootstrap');
+ // 原子写 (review P1 回归):decode 到 tmp 后 mv 就位, 不直接截断 config.toml。
+ expect(joined).toContain('config.toml.tmp');
+ expect(joined).toContain('mv ');
});
it('passes the bridge token to daemon bootstrap via stdin, never argv', async () => {
@@ -396,3 +415,40 @@ describe('ensureRemoteCodexMcpBridge live-turn defer', () => {
expect(inputs).toContain('LIZI_MCP_TOKEN=test-persistent-token\n\n');
});
});
+
+describe('ensureRemoteCodexMcpBridge server whitelist', () => {
+ it('writes only collab whitelist servers into the remote managed block', async () => {
+ // review P1 回归:bridge 上还挂着 cindy_memory / cindy_ssh 等 in-process
+ // provider — 全量写进远端 daemon config 会让远端 session 获得本机 MCP
+ // 能力, 越出协同边界。远端只注入 cindy_orca / orca_worker_bridge。
+ const { host, execCmds } = fakeHost('host-whitelist', '');
+ const result = await ensureRemoteCodexMcpBridge(host, {
+ ensureBridgeStarted: async () => ({
+ port: 38080,
+ serverNames: ['cindy_orca', 'cindy_memory', 'orca_worker_bridge', 'cindy_ssh'],
+ }),
+ hasLiveTurnOnHost: () => false,
+ });
+ expect(result.ok).toBe(true);
+ const written = decodeWrittenConfig(execCmds);
+ expect(written).not.toBeNull();
+ expect(written).toContain('[mcp_servers.cindy_orca]');
+ expect(written).toContain('[mcp_servers.orca_worker_bridge]');
+ expect(written).not.toContain('cindy_memory');
+ expect(written).not.toContain('cindy_ssh');
+ });
+
+ it('is a no-op success when the bridge exposes no whitelist server', async () => {
+ // collab plugin 禁用 → bridge 上没有 cindy_orca:不写 config, 不重启
+ // daemon, 按"远端无 MCP"放行。
+ const { host, execCmds } = fakeHost('host-no-whitelist', '');
+ const result = await ensureRemoteCodexMcpBridge(host, {
+ ensureBridgeStarted: async () => ({ port: 38080, serverNames: ['cindy_memory'] }),
+ hasLiveTurnOnHost: () => false,
+ });
+ expect(result.ok).toBe(true);
+ const joined = execCmds.join('\n');
+ expect(joined).not.toContain('base64 -d');
+ expect(joined).not.toContain('bootstrap');
+ });
+});
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 70cb718a9f..f285b149cd 100644
--- a/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts
+++ b/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts
@@ -38,6 +38,14 @@ import { getRemoteMcpBridgeToken } from '../mcp-integrations/remoteMcpBridgeToke
const log = createLogger('codex-remote-mcp');
const TOKEN_ENV = 'LIZI_MCP_TOKEN';
+/**
+ * 远端允许经 remote-forward 暴露的 server 白名单 — 与 cc 侧
+ * CC_REMOTE_HTTP_MCP_SERVER_NAMES (maker-host/cc-remote-mcp.ts) 同意同值:
+ * 只放协同必需的 cindy_orca / orca_worker_bridge;bridge 上的其余
+ * in-process server (cindy_memory / cindy_ssh 等) 不注入远端 daemon
+ * config, 维持"远端不可用"现状, 收窄影响面。两侧改动必须同步。
+ */
+const CODEX_REMOTE_MCP_SERVER_NAMES = new Set(['cindy_orca', 'orca_worker_bridge']);
const MANAGED_BEGIN = '# >>> cindy-remote-mcp (managed, do not edit) >>>';
const MANAGED_END = '# <<< cindy-remote-mcp <<<';
/**
@@ -292,9 +300,13 @@ function readConfigCmd(): string {
}
function writeConfigCmd(contentBase64: string): string {
+ // 原子写:先 decode 到 tmp 再 mv 就位。直接 `> config.toml` 时, decode
+ // 失败或 SSH 中断会把用户配置截断成空/半截 — 这里编辑的是真实远端
+ // config.toml, 错误路径不得破坏现有内容 (tmp 残留无害, 下次覆盖)。
return `bash -c ${shellQuoteSh(
`${codexHomePrefix(DEFAULT_INSTALL_ROOT)}; mkdir -p "$CODEX_HOME" && ` +
- `printf '%s' ${shellQuoteSh(contentBase64)} | base64 -d > "$CODEX_HOME/config.toml"`,
+ `printf '%s' ${shellQuoteSh(contentBase64)} | base64 -d > "$CODEX_HOME/config.toml.tmp" && ` +
+ `mv "$CODEX_HOME/config.toml.tmp" "$CODEX_HOME/config.toml"`,
)}`;
}
@@ -455,7 +467,11 @@ async function doEnsureRemoteCodexMcpBridge(
log.warn('remote MCP injection skipped: http bridge unavailable', { host: host.id });
return { ok: false, reason: 'bridge-unavailable' };
}
- if (bridge.serverNames.length === 0) {
+ // 只注入协同白名单 server:bridge 上还挂着其他 in-process provider
+ // (cindy_memory / cindy_ssh 等), 全量写进远端 daemon config 会让远端
+ // session 获得本机 MCP 能力, 越出协同边界 (与 cc 侧白名单同语义)。
+ const serverNames = bridge.serverNames.filter((n) => CODEX_REMOTE_MCP_SERVER_NAMES.has(n));
+ if (serverNames.length === 0) {
// collab plugin 被禁用等场景:cindy_orca 不在 bridge 上,没有可注入的
// server。视为成功 (无需注入),daemon config 也不写管理段。
return { ok: true };
@@ -474,11 +490,11 @@ async function doEnsureRemoteCodexMcpBridge(
const existing = await readRemoteConfig(host);
const block = renderManagedMcpBlock({
remotePort,
- serverNames: bridge.serverNames,
+ serverNames,
tokenFingerprint,
});
const { next, changed, strippedUserServers } = mergeManagedMcpBlock(existing, block, {
- serverNames: bridge.serverNames,
+ serverNames,
});
if (strippedUserServers.length > 0) {
log.warn('user-defined mcp_servers blocks taken over by managed block', {
@@ -499,7 +515,7 @@ async function doEnsureRemoteCodexMcpBridge(
log.info('remote codex config.toml mcp_servers updated', {
host: host.id,
remotePort,
- servers: bridge.serverNames,
+ servers: serverNames,
});
}