Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): persistent token 按白名单 scope + 远端 daemon 全量漂移自愈
yan2f1d5e495ee8
diff --git a/apps/desktop/src/main/maker-host/__tests__/orcaTeamStoreAdapter.test.ts b/apps/desktop/src/main/maker-host/__tests__/orcaTeamStoreAdapter.test.tsindex 43877f2e50..b3bdc55257 100644--- a/apps/desktop/src/main/maker-host/__tests__/orcaTeamStoreAdapter.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/orcaTeamStoreAdapter.test.ts@@ -22,6 +22,7 @@ const workerLink: OrcaWorkerLinkRecord = {fastMode: false,sdkSessionId: 'sdk-lead-1',title: 'Lead session',+ remoteHostId: 'host-remote-1',},};@@ -63,6 +64,8 @@ describe('maker host orca team store adapter', () => {fastMode: false,sdkSessionId: 'sdk-lead-1',title: 'Lead session',+ // DB 带出的 host id 必须透传进 bridge 快照 (rehydrate 要用)。+ remoteHostId: 'host-remote-1',},});expect(deps.markKnownOrcaWorkerSession).toHaveBeenCalledWith('worker-session-1');diff --git a/apps/desktop/src/main/maker-host/cc-remote-mcp.ts b/apps/desktop/src/main/maker-host/cc-remote-mcp.tsindex 274c450423..2b484ca006 100644--- a/apps/desktop/src/main/maker-host/cc-remote-mcp.ts+++ b/apps/desktop/src/main/maker-host/cc-remote-mcp.ts@@ -16,16 +16,18 @@import type { RemoteHost } from '@cindy/maker-remote-ssh';import type { CodexHttpBridge } from '../mcp-integrations/codexHttpBridge.js';+import { REMOTE_COLLAB_SERVER_NAMES } from '../mcp-integrations/codexHttpBridge.js';import { getRemoteMcpBridgeToken } from '../mcp-integrations/remoteMcpBridgeToken.js';import { getSessionOrcaRole, getWorkerLink } from '../localDb/orcaTeamStore.js';/**- * cc 远端允许经 remote-forward 暴露的 server 白名单。只放协同必需的- * cindy_orca / orca_worker_bridge:其余 in-process server (cindy_memory 远端- * 本就显式禁用、cindy_ssh 的 exec 从本机发起等) 维持"远端不可用"现状,- * 收窄影响面,后续按需逐个评估放开。+ * cc 远端允许经 remote-forward 暴露的 server 白名单 — 唯一真源在+ * codexHttpBridge.ts (REMOTE_COLLAB_SERVER_NAMES, bridge 鉴权层对+ * persistent token 也按它 scope):只放协同必需的 cindy_orca /+ * orca_worker_bridge;其余 in-process server (cindy_memory 远端本就显式+ * 禁用、cindy_ssh 的 exec 从本机发起等) 维持"远端不可用"现状,收窄影响面。*/-const CC_REMOTE_HTTP_MCP_SERVER_NAMES = new Set(['cindy_orca', 'orca_worker_bridge']);+const CC_REMOTE_HTTP_MCP_SERVER_NAMES = REMOTE_COLLAB_SERVER_NAMES;/*** cc remote 的 MCP session ctx 合成:与 synthesizeOrcaVendorOptionsFromDbdiff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 6ce809fa4f..a7e465c700 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -282,6 +282,7 @@ export function setBeforeLocalCodexSessionStartHook(hook: (() => Promise<void>)export async function ensureCodexMcpBridgeStartedForRemote(): Promise<{port: number;serverNames: string[];+ bridgeInstanceId: string;bridge: CodexHttpBridge;} | null> {if (!_codexMcpProviders) return null;@@ -301,7 +302,12 @@ export async function ensureCodexMcpBridgeStartedForRemote(): Promise<{forcedFreshCcBridgeSessions.clear();_lastBridgeForForcedFresh = cfg.bridge;}- return { port: cfg.bridge.port, serverNames: cfg.bridgeServerNames, bridge: cfg.bridge };+ return {+ port: cfg.bridge.port,+ serverNames: cfg.bridgeServerNames,+ bridgeInstanceId: cfg.bridge.instanceId,+ bridge: cfg.bridge,+ };} catch (err) {desktopMakerLogger.error('ensureCodexMcpBridgeStartedForRemote failed', {message: err instanceof Error ? err.message : String(err),diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.tsindex d4d22e8d53..023cd5ee02 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts@@ -77,7 +77,7 @@ describe('codexHttpBridge', () => {it('accepts an additional bearer token (remote daemon) and rejects unknown tokens', async () => {bridge = await startCodexHttpBridge({- serverFactories: { cindy_test: createTestServer },+ serverFactories: { cindy_orca: createTestServer, cindy_test: createTestServer },additionalBearerTokens: () => ['remote-persistent-token'],logger: noopLogger(),});@@ -92,8 +92,8 @@ describe('codexHttpBridge', () => {clientInfo: { name: 'test-client', version: '1.0.0' },},});- const postInit = (token: string) =>- fetch(bridge!.url('cindy_test'), {+ const postInit = (serverName: string, token: string) =>+ fetch(bridge!.url(serverName), {method: 'POST',headers: {authorization: `Bearer ${token}`,@@ -103,18 +103,26 @@ describe('codexHttpBridge', () => {body: initBody,});- // 主 token (per-run, 本地 codex 子进程) 可用 — 现状不变。- const mainResp = await postInit(bridge.token);+ // 主 token (per-run, 本地 codex 子进程) 全通 — 白名单与非白名单都可用。+ const mainResp = await postInit('cindy_orca', bridge.token);expect(mainResp.status).toBe(200);await mainResp.text();-- // additional token (远端常驻 daemon 的 persistent token) 同样放行。- const remoteResp = await postInit('remote-persistent-token');+ const mainNonCollab = await postInit('cindy_test', bridge.token);+ expect(mainNonCollab.status).toBe(200);+ await mainNonCollab.text();++ // additional token (远端常驻 daemon 的 persistent token) 仅限协同白名单:+ // 同一 remote-forward 能摸到完整 /mcp/<name> 路由, 拿到 token 的远端+ // 进程不得初始化本机非协同 server (codex-connector P1 回归)。+ const remoteResp = await postInit('cindy_orca', 'remote-persistent-token');expect(remoteResp.status).toBe(200);await remoteResp.text();+ const remoteNonCollab = await postInit('cindy_test', 'remote-persistent-token');+ expect(remoteNonCollab.status).toBe(403);+ await remoteNonCollab.text();// 未知 token 一律 401 (防呆过滤)。- const badResp = await postInit('not-a-real-token');+ const badResp = await postInit('cindy_orca', 'not-a-real-token');expect(badResp.status).toBe(401);await badResp.text();});@@ -557,7 +565,9 @@ describe('codexHttpBridge', () => {it('resolves identity from ?session= query without _meta.threadId (remote cc)', async () => {bridge = await startCodexHttpBridge({- serverFactories: { cindy_test: createTestServer },+ // remote cc 走 persistent token, 仅限协同白名单 — 用白名单内的+ // cindy_orca 模拟真实 cc 流量 (scope 收窄后 cindy_test 会被 403)。+ serverFactories: { cindy_orca: createTestServer },additionalBearerTokens: () => ['remote-persistent-token'],logger: noopLogger(),});@@ -573,7 +583,7 @@ describe('codexHttpBridge', () => {accept: 'application/json, text/event-stream','content-type': 'application/json',};- const sessionUrl = `${bridge.url('cindy_test')}?session=cc-session-1`;+ const sessionUrl = `${bridge.url('cindy_orca')}?session=cc-session-1`;const initBody = (id: number) =>JSON.stringify({jsonrpc: '2.0',@@ -664,8 +674,10 @@ describe('codexHttpBridge', () => {it('applies the frozen plugin policy to ?session= ctx tool calls (remote cc)', async () => {bridge = await startCodexHttpBridge({- serverFactories: { cindy_test: createTestServer },- pluginIdByServerName: { cindy_test: 'ssh' },+ // server 名用白名单内的 cindy_orca 模拟真实 remote cc 流量+ // (persistent token scope 收窄后非白名单 server 会被 403)。+ serverFactories: { cindy_orca: createTestServer },+ pluginIdByServerName: { cindy_orca: 'ssh' },additionalBearerTokens: () => ['remote-persistent-token'],logger: noopLogger(),});@@ -685,7 +697,7 @@ describe('codexHttpBridge', () => {accept: 'application/json, text/event-stream','content-type': 'application/json',};- const sessionUrl = `${bridge.url('cindy_test')}?session=cc-disabled`;+ const sessionUrl = `${bridge.url('cindy_orca')}?session=cc-disabled`;const initResp = await fetch(sessionUrl, {method: 'POST',headers,@@ -725,8 +737,10 @@ describe('codexHttpBridge', () => {// threadId 时, policy 判定不得按那个 thread ctx 放行 —— 执行态身份与// policy ctx 都必须是 ?session= 强优先。bridge = await startCodexHttpBridge({- serverFactories: { cindy_test: createTestServer },- pluginIdByServerName: { cindy_test: 'ssh' },+ // server 名用白名单内的 cindy_orca 模拟真实 remote cc 流量+ // (persistent token scope 收窄后非白名单 server 会被 403)。+ serverFactories: { cindy_orca: createTestServer },+ pluginIdByServerName: { cindy_orca: 'ssh' },additionalBearerTokens: () => ['remote-persistent-token'],logger: noopLogger(),});@@ -751,7 +765,7 @@ describe('codexHttpBridge', () => {accept: 'application/json, text/event-stream','content-type': 'application/json',};- const sessionUrl = `${bridge.url('cindy_test')}?session=cc-disabled`;+ const sessionUrl = `${bridge.url('cindy_orca')}?session=cc-disabled`;const initResp = await fetch(sessionUrl, {method: 'POST',headers,diff --git a/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts b/apps/desktop/src/main/mcp-integrations/codexHttpBridge.tsindex 808d1cf032..3ebb554bc4 100644--- a/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts+++ b/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts@@ -30,6 +30,18 @@ import { CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY } from './codexBuiltinToolPolicy.const SERVER_HEADER = 'Lizi_MCPS/1.0';const MCP_PATH_PREFIX = '/mcp/';const SHUTDOWN_TIMEOUT_MS = 5_000;+/**+ * 远端 (SSH remote-forward) 允许暴露的 server 白名单 — additionalBearerTokens+ * (persistent token) 认证的请求只能访问这些 server。这是 codex/cc 两条远端+ * 注入路径共享的唯一真源 (remote-ssh/codex-remote-mcp.ts 与+ * maker-host/cc-remote-mcp.ts 都引用它, 不要各自另立常量):只放协同必需的+ * cindy_orca / orca_worker_bridge;拿到 persistent token 的远端进程不得经+ * bridge 初始化 cindy_ssh / cindy_memory 等本机 server。+ */+export const REMOTE_COLLAB_SERVER_NAMES: ReadonlySet<string> = new Set([+ 'cindy_orca',+ 'orca_worker_bridge',+]);/*** init request body 上限 (1MB)。codex MCP init payload 实际 < 1KB,* 1MB 给极端情况留余量。超限直接 413 拒绝 — 防巨大 body 在 JSON.parse@@ -42,6 +54,12 @@ const INIT_BODY_MAX_BYTES = 1 * 1024 * 1024;export interface CodexHttpBridge {port: number;token: string;+ /**+ * 本实例的代际 id (每次启动随机生成)。bridge 重建后旧实例签发的+ * mcp-session-id 全部失效 — 远端常驻 daemon 的漂移检测据此触发+ * re-bootstrap (写进受管段指纹), cc 侧据此清空 forcedFresh 集合。+ */+ instanceId: string;/** 拼出 codex 端 config 用的 URL,例如 http://127.0.0.1:54321/mcp/lizi_feishu */url(serverName: string): string;registerThreadContext(threadId: string, ctx: LiziMcpSessionContext): void;@@ -122,15 +140,18 @@ export async function startCodexHttpBridge(}// bearer token 鉴权:主 token (per-run, 本地 codex 子进程) / 额外 token- // (persistent, 远端常驻 codex daemon 与远端 cc 共用)。+ // (persistent, 远端常驻 codex daemon 与远端 cc 共用)。两类 token 权限+ // 不同:主 token 全通;额外 token 只允许访问 REMOTE_COLLAB_SERVER_NAMES+ // 白名单 (远端进程拿到 token 也不得初始化本机非协同 server)。const auth = req.headers['authorization'];const presented =typeof auth === 'string' && auth.startsWith('Bearer ') ? auth.slice(7) : null;- const accepted =+ const isPrimaryToken = presented !== null && presented === token;+ const isScopedRemoteToken =+ !isPrimaryToken &&presented !== null &&- (presented === token ||- (opts.additionalBearerTokens?.().includes(presented) ?? false));- if (!accepted) {+ (opts.additionalBearerTokens?.().includes(presented) ?? false);+ if (!isPrimaryToken && !isScopedRemoteToken) {res.statusCode = 401;res.setHeader('WWW-Authenticate', 'Bearer');res.end();@@ -171,6 +192,15 @@ export async function startCodexHttpBridge(res.end();return;}+ // scoped (persistent) token 仅限协同白名单 server:同一 remote-forward+ // 能摸到完整 /mcp/<name> 路由, 不得经它初始化本机非协同 server+ // (cindy_ssh / cindy_memory 等) — codex-connector P1。+ if (isScopedRemoteToken && !REMOTE_COLLAB_SERVER_NAMES.has(serverName)) {+ res.statusCode = 403;+ res.end();+ log.warn('rejected scoped remote token for non-collab server', { serverName });+ return;+ }const createMcpServer = opts.serverFactories[serverName];const transports = transportsByServer.get(serverName);if (!createMcpServer || !transports) {@@ -296,6 +326,7 @@ export async function startCodexHttpBridge(return {port,token,+ instanceId: randomBytes(8).toString('hex'),url: (serverName) => `http://127.0.0.1:${port}${MCP_PATH_PREFIX}${encodeURIComponent(serverName)}`,registerThreadContext: threadContextStore.registerThreadContext,unregisterThreadContext: threadContextStore.unregisterThreadContext,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.tsindex c29f2853bc..e1c5b568e7 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@@ -46,12 +46,13 @@ function fakeHost(hostId: string, configContent: string) {/*** 从 write 命令里解出写入的 config 内容。依赖 writeConfigCmd 的* `printf '%s' '<base64>'` 形态 (base64 无单引号):取命令里最长的类- * base64 token 解码。+ * base64 token 解码。下限 16:清理后的小 config (如只剩一行 model) 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 tokens = cmd.match(/[A-Za-z0-9+/=]{16,}/g) ?? [];const b64 = tokens.sort((a, b) => b.length - a.length)[0];if (b64) return Buffer.from(b64, 'base64').toString('utf-8');}@@ -350,7 +351,7 @@ describe('ensureRemoteCodexMcpBridge per-host serialization', () => {describe('ensureRemoteCodexMcpBridge live-turn defer', () => {const bridgeDeps = {- ensureBridgeStarted: async () => ({ port: 38080, serverNames: SERVERS }),+ ensureBridgeStarted: async () => ({ port: 38080, serverNames: SERVERS, bridgeInstanceId: 'bridge-1' }),};it('defers config write and daemon restart while a live turn exists on the host', async () => {@@ -454,7 +455,7 @@ describe('ensureRemoteCodexMcpBridge bootstrap retry', () => {} as unknown as RemoteHost;const deps = {- ensureBridgeStarted: async () => ({ port: 38080, serverNames: SERVERS }),+ ensureBridgeStarted: async () => ({ port: 38080, serverNames: SERVERS, bridgeInstanceId: 'bridge-1' }),hasLiveTurnOnHost: () => false,};const first = await ensureRemoteCodexMcpBridge(host, deps);@@ -483,6 +484,7 @@ describe('ensureRemoteCodexMcpBridge server whitelist', () => {ensureBridgeStarted: async () => ({port: 38080,serverNames: ['cindy_orca', 'cindy_memory', 'orca_worker_bridge', 'cindy_ssh'],+ bridgeInstanceId: 'bridge-1',}),hasLiveTurnOnHost: () => false,});@@ -495,12 +497,12 @@ describe('ensureRemoteCodexMcpBridge server whitelist', () => {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"放行。+ it('is a no-op success when the bridge exposes no whitelist server and nothing was ever injected', async () => {+ // collab plugin 禁用 → bridge 上没有 cindy_orca;远端 config 本来就没+ // 注入过 → merge('') 无漂移:不写 config, 不重启 daemon。const { host, execCmds } = fakeHost('host-no-whitelist', '');const result = await ensureRemoteCodexMcpBridge(host, {- ensureBridgeStarted: async () => ({ port: 38080, serverNames: ['cindy_memory'] }),+ ensureBridgeStarted: async () => ({ port: 38080, serverNames: ['cindy_memory'], bridgeInstanceId: 'bridge-1' }),hasLiveTurnOnHost: () => false,});expect(result.ok).toBe(true);@@ -508,4 +510,56 @@ describe('ensureRemoteCodexMcpBridge server whitelist', () => {expect(joined).not.toContain('base64 -d');expect(joined).not.toContain('bootstrap');});++ it('clears a stale managed block and rebootstraps when collab gets disabled after a prior injection', async () => {+ // review P2 回归:之前注入过的 host 上 collab 被禁用 (白名单为空) 时,+ // 不能早退 — 旧受管段必须剥除并重启 daemon (清掉 token env 与死配置),+ // 否则远端 session 继续调用已失效的 MCP endpoint。+ const stale = renderManagedMcpBlock({ remotePort: 47921, serverNames: SERVERS, tokenFingerprint: 'fp-old' });+ const existing = `model = "gpt-5.5"\n\n${stale}\n`;+ const { host, execCmds } = fakeHost('host-cleanup', existing);+ const result = await ensureRemoteCodexMcpBridge(host, {+ ensureBridgeStarted: async () => ({ port: 38080, serverNames: ['cindy_memory'], bridgeInstanceId: 'bridge-1' }),+ hasLiveTurnOnHost: () => false,+ });+ expect(result.ok).toBe(true);+ const joined = execCmds.join('\n');+ expect(joined).toContain('base64 -d'); // 写了清理后的 config+ expect(joined).toContain('bootstrap'); // 重启 daemon 清 env+ const written = decodeWrittenConfig(execCmds);+ expect(written).not.toBeNull();+ expect(written).not.toContain('cindy-remote-mcp'); // 受管段已剥除+ expect(written).toContain('model = "gpt-5.5"'); // 用户配置保留+ });++ it('rebootstraps when the bridge instance is recreated with the same token and port', async () => {+ // review P2 回归:bridge 重建后旧 mcp-session-id 全失效, 但 token+ // (persistent) 与端口 (per-host 固定) 不变 — 代际 id 必须进漂移指纹,+ // 否则常驻 daemon 持旧 id 打新 bridge 全部 404。+ const { host: host1, execCmds: execCmds1 } = fakeHost('host-regen', '');+ const deps = (instanceId: string) => ({+ ensureBridgeStarted: async () => ({ port: 38080, serverNames: SERVERS, bridgeInstanceId: instanceId }),+ hasLiveTurnOnHost: () => false,+ });+ const first = await ensureRemoteCodexMcpBridge(host1, deps('bridge-1'));+ expect(first.ok).toBe(true);+ const writtenFirst = decodeWrittenConfig(execCmds1);+ expect(writtenFirst).toContain('# cindy-token-fingerprint:');++ // 远端 config 已是 bridge-1 指纹;bridge 重建 (bridge-2) → 指纹漂移 →+ // 重写 config 并再 bootstrap (daemon 仍存活, changed 是唯一触发)。+ const { host: host2, execCmds: execCmds2 } = fakeHost('host-regen', writtenFirst ?? '');+ const second = await ensureRemoteCodexMcpBridge(host2, deps('bridge-2'));+ expect(second.ok).toBe(true);+ const joined2 = execCmds2.join('\n');+ expect(joined2).toContain('base64 -d');+ expect(joined2).toContain('bootstrap');+ // 幂等对照:同代际重复 ensure 不触发重写/重启。+ const { host: host3, execCmds: execCmds3 } = fakeHost('host-regen', decodeWrittenConfig(execCmds2) ?? '');+ const third = await ensureRemoteCodexMcpBridge(host3, deps('bridge-2'));+ expect(third.ok).toBe(true);+ const joined3 = execCmds3.join('\n');+ expect(joined3).not.toContain('base64 -d');+ expect(joined3).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.tsindex 4cbb3c9a32..cac8e5d867 100644--- a/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts+++ b/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts@@ -33,19 +33,15 @@ import path from 'node:path';import type { RemoteHost } from '@cindy/maker-remote-ssh';import { createLogger } from '../logger.js';+import { REMOTE_COLLAB_SERVER_NAMES } from '../mcp-integrations/codexHttpBridge.js';import { getRemoteMcpBridgeToken } from '../mcp-integrations/remoteMcpBridgeToken.js';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']);+// 远端注入白名单的唯一真源在 codexHttpBridge.ts (bridge 鉴权层也用它+// scope persistent token) — 这里取别名保持本文件既有引用点不变。+const CODEX_REMOTE_MCP_SERVER_NAMES = REMOTE_COLLAB_SERVER_NAMES;const MANAGED_BEGIN = '# >>> cindy-remote-mcp (managed, do not edit) >>>';const MANAGED_END = '# <<< cindy-remote-mcp <<<';/**@@ -63,6 +59,12 @@ export interface RemoteMcpBridgeEndpoint {port: number;/** bridge 上实际挂出的 server 名 (如 cindy_orca / orca_worker_bridge)。 */serverNames: string[];+ /**+ * bridge 实例代际 id (CodexHttpBridge.instanceId)。bridge 重建后旧实例+ * 签发的 mcp-session-id 全部失效,但常驻 daemon 无感知 — 代际进漂移+ * 指纹, 让重建也触发 re-bootstrap (codex-connector P2)。+ */+ bridgeInstanceId: string;}export interface EnsureRemoteCodexMcpResult {@@ -261,7 +263,15 @@ export function mergeManagedMcpBlock(kept.push(line);}const trimmed = kept.join('\n').replace(/\s+$/, '');- const next = (trimmed.length > 0 ? `${trimmed}\n\n${block}\n` : `${block}\n`);+ // block='' (清理路径, 见 doEnsure 空白名单分支):只剥除受管段, 不重建。+ const next =+ block === ''+ ? trimmed.length > 0+ ? `${trimmed}\n`+ : ''+ : trimmed.length > 0+ ? `${trimmed}\n\n${block}\n`+ : `${block}\n`;return { next, changed: next !== existing, strippedUserServers: [...stripped] };}@@ -482,28 +492,37 @@ async function doEnsureRemoteCodexMcpBridge(// (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 };- }const token = getRemoteMcpBridgeToken();- if (!token) {+ if (serverNames.length > 0 && !token) {log.warn('remote MCP injection skipped: persistent token unavailable (safeStorage?)', {host: host.id,});return { ok: false, reason: 'token-unavailable' };}+ // 清理路径 (白名单为空, collab 被禁用等) 不强求 token:剥除受管段不需要+ // 指纹, bootstrap 传空 token — daemon 不再持有有效 token 正是清理目标。+ const effectiveToken = token ?? '';const remotePort = await ensureRemotePort(host, bridge.port);- const tokenFingerprint = createHash('sha256').update(token, 'utf8').digest('hex').slice(0, 12);+ // token 与 bridge 代际一起进指纹:token 轮换 (账号切换) 与 bridge 重建+ // (旧 mcp-session-id 全失效, codex-connector P2) 都构成 config 漂移,+ // 走既有路径重启 daemon 拿到新 env / 新连接。+ const tokenFingerprint = createHash('sha256')+ .update(`${effectiveToken}|${bridge.bridgeInstanceId}`, 'utf8')+ .digest('hex')+ .slice(0, 12);const existing = await readRemoteConfig(host);- const block = renderManagedMcpBlock({- remotePort,- serverNames,- tokenFingerprint,- });+ // serverNames 为空时 block='':merge 只剥不建 — 清掉上一次注入留下的+ // 受管段 (不能早退, 否则 daemon 永远持旧 token env 与死配置,+ // codex-connector P2);本来就没注入过 → changed=false → no-op。+ const block = serverNames.length > 0+ ? renderManagedMcpBlock({+ remotePort,+ serverNames,+ tokenFingerprint,+ })+ : '';const { next, changed, strippedUserServers } = mergeManagedMcpBlock(existing, block, {serverNames,});@@ -536,14 +555,16 @@ async function doEnsureRemoteCodexMcpBridge(// 否则 config 已写入 (changed=false) + 旧 daemon 存活 (daemonRunning)// 的组合会让 daemon 永远持旧 env, 远端请求 401 且不自愈。pendingBootstrapHosts.add(host.id);- await bootstrapDaemon(host, token);+ await bootstrapDaemon(host, effectiveToken);// 防御:bootstrap 若覆盖了 config.toml (managed_install 行为未文档化),// 管理段丢失时补写一次并再次 bootstrap。最多两轮,避免无限循环。+ // 仅注入路径 (serverNames 非空):清理路径本来就要管理段不存在,+ // 不得把它当"丢失"补写回去。const after = await readRemoteConfig(host);- if (!after.includes(MANAGED_BEGIN)) {+ if (serverNames.length > 0 && !after.includes(MANAGED_BEGIN)) {log.warn('managed mcp block lost after bootstrap — rewriting once', { host: host.id });await writeRemoteConfig(host, next);- await bootstrapDaemon(host, token);+ await bootstrapDaemon(host, effectiveToken);}pendingBootstrapHosts.delete(host.id);log.info('remote codex daemon (re)bootstrapped with MCP bridge env', {