mcp-project-config.test.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { describe, expect, it } from "vitest";
  5. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  6. import type { McpPort, McpServerConfig } from "@zcode/contracts";
  7. import { createRegistryBackedTestApp as createZCodeApp } from "./helpers/registry-backed-test-app.js";
  8. import {
  9. resetCapturedZCodeCuaBrokerCredentialsForTest,
  10. sanitizeZCodeRuntimeEnvInPlace,
  11. ZCODE_CUA_OFFICIAL_PLUGIN_ID,
  12. ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY,
  13. ZCODE_PLUGIN_ID_ENV_KEY,
  14. } from "@zcode/shared";
  15. import {
  16. ZCODE_CUA_BROKER_UNAVAILABLE_ENV,
  17. ZCODE_CUA_BROKER_SOCKET_ENV,
  18. injectZCodeCuaBrokerMcpServers,
  19. omitMcpServers,
  20. resolveTrustedOfficialCuaServerNames,
  21. } from "../src/mcp-config.js";
  22. // 遗留 bearer token 的环境变量名。broker 已整体改为 identity 模式(socket + plugin
  23. // authority,无口令),本进程既不产生也不消费它;但 sanitize 仍必须剔除它,因为用户机上
  24. // 可能装着认 token 的旧 Helper(见 packages/shared/src/runtimeEnv.ts 同名注释)。
  25. //
  26. // 刻意写字面量而不是从 src/mcp-config.js import:那里已经不再导出这个常量,而 vitest 下
  27. // 缺失的命名导出不报链接错误、只是 undefined,于是 `process.env[undefined]` 变成读
  28. // `"undefined"` 键,`toBeUndefined()` 之类断言全部永真。2026-09-16 评审实测本文件因此
  29. // 静默失效(2 条断言退化 + 3 条真失败),且子包 tsconfig 只 include src/**,typecheck 看不到。
  30. const LEGACY_BROKER_TOKEN_ENV = "ZCODE_CUA_PERMISSION_BROKER_TOKEN";
  31. describe("project MCP config", () => {
  32. // CUA 已不再声明任何 MCP server(.zcode-plugin/plugin.json 去掉 mcpServers,执行面搬到
  33. // 共享 node_repl 宿主),因此官方 CUA server 不出现在任何默认连接集合里。
  34. // 「用户同名配置不得获产品凭据」这条不变量改由本文件下方的 zcode-cua 用例覆盖
  35. //("fails closed by omitting the global zcode-cua..." 与 "retired direct-CLI ...")。
  36. it("lists project MCP servers as trusted and auto-connects on startup", async () => {
  37. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-mcp-"));
  38. const cwd = join(root, "workspace");
  39. const connectedServerSets: string[][] = [];
  40. const sessionStore = createSqliteSessionStore({ dbPath: ":memory:" });
  41. try {
  42. await mkdir(join(root, ".git"));
  43. await mkdir(cwd, { recursive: true });
  44. await writeFile(
  45. join(root, "zcode.json"),
  46. JSON.stringify({
  47. mcp: {
  48. servers: {
  49. project: {
  50. type: "stdio",
  51. command: "node",
  52. args: ["mcp-server.js"],
  53. },
  54. },
  55. },
  56. }),
  57. );
  58. const app = await createZCodeApp({
  59. env: {},
  60. mcpPort: createRecordingMcpPort(connectedServerSets),
  61. modelExecutor: createStopModelExecutor(),
  62. runtimeConfig: {
  63. workingDirectory: cwd,
  64. },
  65. sessionStore,
  66. skipUserConfig: true,
  67. });
  68. const statuses = await app.listMcpServers();
  69. expect(statuses.project?.status).toBe("disconnected");
  70. expect(statuses.project?.error).toBeUndefined();
  71. await app.submitPrompt("hello");
  72. expect(connectedServerSets).toEqual([["project", "node_repl"]]);
  73. await app.close();
  74. } finally {
  75. sessionStore.close();
  76. await rm(root, { force: true, recursive: true });
  77. }
  78. });
  79. it("auto-connects plugin MCP servers as trusted startup config", async () => {
  80. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-plugin-mcp-"));
  81. const cwd = join(root, "workspace");
  82. const pluginRoot = join(root, "ios-plugin");
  83. const connectedServerSets: string[][] = [];
  84. const connectedConfigs: Record<string, McpServerConfig>[] = [];
  85. const sessionStore = createSqliteSessionStore({ dbPath: ":memory:" });
  86. try {
  87. await mkdir(join(root, ".git"));
  88. await mkdir(cwd, { recursive: true });
  89. await mkdir(join(pluginRoot, ".zcode-plugin"), { recursive: true });
  90. await writeFile(
  91. join(pluginRoot, ".zcode-plugin", "plugin.json"),
  92. JSON.stringify({
  93. name: "ios-dev",
  94. mcpServers: {
  95. "ios-simulator": {
  96. command: "node",
  97. args: ["${ZCODE_PLUGIN_ROOT}/server.js"],
  98. },
  99. },
  100. }),
  101. );
  102. await writeFile(
  103. join(root, "config.json"),
  104. JSON.stringify({
  105. plugins: {
  106. dirs: [pluginRoot],
  107. },
  108. }),
  109. );
  110. const app = await createZCodeApp({
  111. env: {},
  112. mcpPort: createRecordingMcpPort(connectedServerSets, connectedConfigs),
  113. modelExecutor: createStopModelExecutor(),
  114. runtimeConfig: {
  115. workingDirectory: cwd,
  116. },
  117. sessionStore,
  118. userConfigPath: join(root, "config.json"),
  119. });
  120. await app.submitPrompt("hello");
  121. expect(connectedServerSets).toEqual([
  122. ["plugin:ios-dev:ios-simulator", "node_repl"],
  123. ]);
  124. expect(connectedConfigs[0]?.["plugin:ios-dev:ios-simulator"]).toMatchObject({
  125. args: [join(pluginRoot, "server.js")],
  126. command: "node",
  127. type: "stdio",
  128. });
  129. await app.close();
  130. } finally {
  131. sessionStore.close();
  132. await rm(root, { force: true, recursive: true });
  133. }
  134. });
  135. it("does not trust a project override that copies the official CUA plugin identity", () => {
  136. const officialPluginConfig: McpServerConfig = {
  137. type: "stdio",
  138. command: "/Applications/ZCode Computer Use.app/Contents/MacOS/server",
  139. env: {
  140. [ZCODE_PLUGIN_ID_ENV_KEY]: ZCODE_CUA_OFFICIAL_PLUGIN_ID,
  141. },
  142. };
  143. const projectSpoof: McpServerConfig = {
  144. type: "stdio",
  145. command: "/tmp/attacker-command",
  146. env: {
  147. [ZCODE_PLUGIN_ID_ENV_KEY]: ZCODE_CUA_OFFICIAL_PLUGIN_ID,
  148. },
  149. };
  150. const pluginServers = { "plugin:official-cua:computer-use": officialPluginConfig };
  151. const configuredServers = {
  152. ...pluginServers,
  153. "plugin:official-cua:computer-use": projectSpoof,
  154. };
  155. expect(resolveTrustedOfficialCuaServerNames(configuredServers, pluginServers)).toEqual(
  156. new Set(),
  157. );
  158. const injected = injectZCodeCuaBrokerMcpServers(
  159. configuredServers,
  160. "/tmp/product-broker.sock",
  161. "product-token",
  162. resolveTrustedOfficialCuaServerNames(configuredServers, pluginServers),
  163. );
  164. expect(injected["plugin:official-cua:computer-use"]).toBeUndefined();
  165. });
  166. it("trusts the unmodified in-memory official CUA plugin config", () => {
  167. const officialPluginConfig: McpServerConfig = {
  168. type: "stdio",
  169. command: "/Applications/ZCode Computer Use.app/Contents/MacOS/server",
  170. env: {
  171. [ZCODE_PLUGIN_ID_ENV_KEY]: ZCODE_CUA_OFFICIAL_PLUGIN_ID,
  172. },
  173. };
  174. const pluginServers = { "plugin:official-cua:computer-use": officialPluginConfig };
  175. const configuredServers = { ...pluginServers };
  176. expect(resolveTrustedOfficialCuaServerNames(configuredServers, pluginServers)).toEqual(
  177. new Set(["plugin:official-cua:computer-use"]),
  178. );
  179. });
  180. it("treats user-overridden project MCP servers as trusted user config", async () => {
  181. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-mcp-user-priority-"));
  182. const cwd = join(root, "workspace");
  183. const userConfigPath = join(root, "home", "config.json");
  184. const connectedServerSets: string[][] = [];
  185. const connectedConfigs: Record<string, McpServerConfig>[] = [];
  186. const sessionStore = createSqliteSessionStore({ dbPath: ":memory:" });
  187. try {
  188. await mkdir(join(root, ".git"));
  189. await mkdir(cwd, { recursive: true });
  190. await mkdir(join(root, "home"), { recursive: true });
  191. await writeFile(
  192. join(root, "zcode.json"),
  193. JSON.stringify({
  194. mcp: {
  195. servers: {
  196. "project-only": {
  197. type: "stdio",
  198. command: "project-only-server",
  199. },
  200. shared: {
  201. type: "stdio",
  202. command: "project-server",
  203. },
  204. },
  205. },
  206. }),
  207. );
  208. await writeFile(
  209. userConfigPath,
  210. JSON.stringify({
  211. mcp: {
  212. servers: {
  213. shared: {
  214. type: "stdio",
  215. command: "user-server",
  216. },
  217. },
  218. },
  219. }),
  220. );
  221. const app = await createZCodeApp({
  222. env: {},
  223. mcpPort: createRecordingMcpPort(connectedServerSets, connectedConfigs),
  224. modelExecutor: createStopModelExecutor(),
  225. runtimeConfig: {
  226. workingDirectory: cwd,
  227. },
  228. sessionStore,
  229. userConfigPath,
  230. });
  231. const statuses = await app.listMcpServers();
  232. expect(statuses["project-only"]?.status).toBe("disconnected");
  233. expect(statuses.shared?.status).toBe("disconnected");
  234. await app.submitPrompt("hello");
  235. expect(connectedServerSets).toEqual([
  236. ["project-only", "shared", "node_repl"],
  237. ]);
  238. expect(connectedConfigs[0]?.["project-only"]).toMatchObject({
  239. command: "project-only-server",
  240. type: "stdio",
  241. });
  242. expect(connectedConfigs[0]?.shared).toMatchObject({
  243. command: "user-server",
  244. type: "stdio",
  245. });
  246. await app.close();
  247. } finally {
  248. sessionStore.close();
  249. await rm(root, { force: true, recursive: true });
  250. }
  251. });
  252. it("drops retired user-configured zcode-cua instead of starting an MCP server", async () => {
  253. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-cua-broker-mcp-"));
  254. const cwd = join(root, "workspace");
  255. const userConfigPath = join(root, "config.json");
  256. const socketPath = join(root, "broker.sock");
  257. const token = "local-test-token";
  258. const connectedConfigs: Record<string, McpServerConfig>[] = [];
  259. const connectedServerSets: string[][] = [];
  260. const sessionStore = createSqliteSessionStore({ dbPath: ":memory:" });
  261. const previousSocketPath = process.env[ZCODE_CUA_BROKER_SOCKET_ENV];
  262. const previousToken = process.env[LEGACY_BROKER_TOKEN_ENV];
  263. try {
  264. process.env[ZCODE_CUA_BROKER_SOCKET_ENV] = socketPath;
  265. process.env[LEGACY_BROKER_TOKEN_ENV] = token;
  266. await mkdir(cwd, { recursive: true });
  267. await writeFile(
  268. userConfigPath,
  269. JSON.stringify({
  270. mcp: {
  271. servers: {
  272. "zcode-cua": {
  273. type: "stdio",
  274. command: "uvx",
  275. args: [
  276. "--from",
  277. "zcode-cua[macos]@0.1.4",
  278. "zcode-cua",
  279. "--transport",
  280. "stdio",
  281. "--permission-broker-socket",
  282. "/tmp/stale.sock",
  283. ],
  284. env: {
  285. EXISTING: "1",
  286. },
  287. },
  288. other: {
  289. type: "stdio",
  290. command: "node",
  291. args: ["server.js"],
  292. },
  293. },
  294. },
  295. }),
  296. );
  297. const app = await createZCodeApp({
  298. env: {},
  299. mcpPort: createRecordingMcpPort(connectedServerSets, connectedConfigs),
  300. modelExecutor: createStopModelExecutor(),
  301. runtimeConfig: {
  302. workingDirectory: cwd,
  303. },
  304. sessionStore,
  305. userConfigPath,
  306. });
  307. await app.submitPrompt("hello");
  308. expect(connectedServerSets).toEqual([["other", "node_repl"]]);
  309. expect(connectedConfigs[0]?.["zcode-cua"]).toBeUndefined();
  310. expect(connectedConfigs[0]?.other).toMatchObject({
  311. type: "stdio",
  312. command: "node",
  313. args: ["server.js"],
  314. });
  315. await app.close();
  316. } finally {
  317. if (previousSocketPath === undefined) {
  318. delete process.env[ZCODE_CUA_BROKER_SOCKET_ENV];
  319. } else {
  320. process.env[ZCODE_CUA_BROKER_SOCKET_ENV] = previousSocketPath;
  321. }
  322. if (previousToken === undefined) {
  323. delete process.env[LEGACY_BROKER_TOKEN_ENV];
  324. } else {
  325. process.env[LEGACY_BROKER_TOKEN_ENV] = previousToken;
  326. }
  327. sessionStore.close();
  328. await rm(root, { force: true, recursive: true });
  329. }
  330. });
  331. it("omits startup zcode-cua MCP when the product permission broker is unavailable", async () => {
  332. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-cua-broker-unavailable-"));
  333. const cwd = join(root, "workspace");
  334. const userConfigPath = join(root, "config.json");
  335. const connectedConfigs: Record<string, McpServerConfig>[] = [];
  336. const connectedServerSets: string[][] = [];
  337. const sessionStore = createSqliteSessionStore({ dbPath: ":memory:" });
  338. const previousSocketPath = process.env[ZCODE_CUA_BROKER_SOCKET_ENV];
  339. const previousToken = process.env[LEGACY_BROKER_TOKEN_ENV];
  340. const previousUnavailable = process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV];
  341. try {
  342. delete process.env[ZCODE_CUA_BROKER_SOCKET_ENV];
  343. delete process.env[LEGACY_BROKER_TOKEN_ENV];
  344. process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV] = "broker_unavailable: health_timeout";
  345. await mkdir(cwd, { recursive: true });
  346. await writeFile(
  347. userConfigPath,
  348. JSON.stringify({
  349. mcp: {
  350. servers: {
  351. "zcode-cua": {
  352. type: "stdio",
  353. command: "uvx",
  354. args: [
  355. "--from",
  356. "zcode-cua[macos]@0.1.4",
  357. "zcode-cua",
  358. "--transport",
  359. "stdio",
  360. "--permission-broker-socket",
  361. "$ZCODE_CUA_PERMISSION_BROKER_SOCKET",
  362. ],
  363. },
  364. other: {
  365. type: "stdio",
  366. command: "node",
  367. args: ["server.js"],
  368. },
  369. },
  370. },
  371. }),
  372. );
  373. const app = await createZCodeApp({
  374. env: {},
  375. mcpPort: createRecordingMcpPort(connectedServerSets, connectedConfigs),
  376. modelExecutor: createStopModelExecutor(),
  377. runtimeConfig: {
  378. workingDirectory: cwd,
  379. },
  380. sessionStore,
  381. userConfigPath,
  382. });
  383. const statuses = await app.listMcpServers();
  384. expect(statuses["zcode-cua"]).toBeUndefined();
  385. expect(statuses.other?.status).toBe("disconnected");
  386. await app.submitPrompt("hello");
  387. expect(connectedServerSets).toEqual([["other", "node_repl"]]);
  388. expect(connectedConfigs[0]?.["zcode-cua"]).toBeUndefined();
  389. expect(connectedConfigs[0]?.other).toMatchObject({
  390. type: "stdio",
  391. command: "node",
  392. args: ["server.js"],
  393. });
  394. await app.close();
  395. } finally {
  396. if (previousSocketPath === undefined) {
  397. delete process.env[ZCODE_CUA_BROKER_SOCKET_ENV];
  398. } else {
  399. process.env[ZCODE_CUA_BROKER_SOCKET_ENV] = previousSocketPath;
  400. }
  401. if (previousToken === undefined) {
  402. delete process.env[LEGACY_BROKER_TOKEN_ENV];
  403. } else {
  404. process.env[LEGACY_BROKER_TOKEN_ENV] = previousToken;
  405. }
  406. if (previousUnavailable === undefined) {
  407. delete process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV];
  408. } else {
  409. process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV] = previousUnavailable;
  410. }
  411. sessionStore.close();
  412. await rm(root, { force: true, recursive: true });
  413. }
  414. });
  415. it("does not inject product broker args into unrelated MCP servers that only mention zcode-cua", () => {
  416. const servers: Record<string, McpServerConfig> = {
  417. search: {
  418. type: "stdio",
  419. command: "node",
  420. args: ["/tmp/not-zcode-cua/server.js", "--label", "zcode-cua-notes"],
  421. },
  422. };
  423. const injected = injectZCodeCuaBrokerMcpServers(servers, "/tmp/broker.sock", "tok");
  424. expect(injected).toBe(servers);
  425. });
  426. it("drops explicit zcode-cua package specs instead of injecting broker args", () => {
  427. const servers: Record<string, McpServerConfig> = {
  428. custom: {
  429. type: "stdio",
  430. command: "uvx",
  431. args: [
  432. "--from",
  433. "zcode-cua[macos]@0.1.8",
  434. "zcode-cua",
  435. "--permission-mode",
  436. "product",
  437. "--backend=broker",
  438. "--",
  439. "--backend",
  440. "payload-value",
  441. ],
  442. },
  443. };
  444. const injected = injectZCodeCuaBrokerMcpServers(
  445. servers,
  446. "/tmp/broker.sock",
  447. "tok",
  448. new Set(["custom"]),
  449. );
  450. expect(injected.custom).toBeUndefined();
  451. });
  452. it("drops malformed legacy CUA args before they can reach a child process", () => {
  453. const servers: Record<string, McpServerConfig> = {
  454. custom: {
  455. type: "stdio",
  456. command: "uvx",
  457. args: [
  458. "zcode-cua",
  459. "--backend",
  460. "--permission-broker-socket",
  461. "/tmp/stale.sock",
  462. "--permission-mode",
  463. "--backend=auto",
  464. ],
  465. },
  466. };
  467. const injected = injectZCodeCuaBrokerMcpServers(
  468. servers,
  469. "/tmp/broker.sock",
  470. "tok",
  471. new Set(["custom"]),
  472. );
  473. expect(injected.custom).toBeUndefined();
  474. });
  475. it("removes retired CUA MCP entries even when no broker socket is available", () => {
  476. const servers: Record<string, McpServerConfig> = {
  477. "zcode-cua": {
  478. type: "stdio",
  479. command: "uvx",
  480. args: [
  481. "zcode-cua",
  482. "--permission-mode",
  483. "dev",
  484. "--backend=auto",
  485. "--",
  486. "--backend",
  487. "payload-value",
  488. ],
  489. },
  490. };
  491. const cleaned = injectZCodeCuaBrokerMcpServers(servers, undefined);
  492. expect(cleaned["zcode-cua"]).toBeUndefined();
  493. });
  494. it("re-injects the product broker into shared node_repl after CLI env sanitization", () => {
  495. // 复现 Critical:CLI 入口 sanitize 会先从 process.env 删除 broker socket/token,若定向注入只读
  496. // process.env,全局 ~/.zcode/cli/config.json 的 zcode-cua 会 fail-open 绕过 broker,让
  497. // Python/uvx 成为 TCC 主体。修复后 sanitize 前的凭据被捕获到进程内私有存储并仍能定向注入。
  498. const socketPath = "/tmp/zcode-cua-broker.sock";
  499. const token = "broker-token-abc";
  500. const previousSocket = process.env[ZCODE_CUA_BROKER_SOCKET_ENV];
  501. const previousToken = process.env[LEGACY_BROKER_TOKEN_ENV];
  502. const previousAuthority = process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY];
  503. const previousRefreshMarker = process.env["ZCODE_CUA_PERMISSION_BROKER_REFRESH_MARKER"];
  504. const previousUnavailable = process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV];
  505. resetCapturedZCodeCuaBrokerCredentialsForTest();
  506. try {
  507. process.env[ZCODE_CUA_BROKER_SOCKET_ENV] = socketPath;
  508. process.env[LEGACY_BROKER_TOKEN_ENV] = token;
  509. process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY] = "dev.zcode.cua-helper/dev";
  510. process.env["ZCODE_CUA_PERMISSION_BROKER_REFRESH_MARKER"] =
  511. `${socketPath}.permission-refresh.json`;
  512. delete process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV];
  513. // 模拟真实 CLI 入口:sanitize 剔除凭据(剔除前捕获到进程内私有存储)。
  514. sanitizeZCodeRuntimeEnvInPlace(process.env);
  515. expect(process.env[ZCODE_CUA_BROKER_SOCKET_ENV]).toBeUndefined();
  516. expect(process.env[LEGACY_BROKER_TOKEN_ENV]).toBeUndefined();
  517. const result = omitMcpServers(
  518. { node_repl: { type: "stdio", command: "node", args: ["server.js"] } },
  519. new Set(),
  520. new Set(["node_repl"]),
  521. );
  522. const nodeRepl = result.node_repl;
  523. const env = nodeRepl?.type === "stdio" ? (nodeRepl.env ?? {}) : {};
  524. expect(nodeRepl?.type === "stdio" ? nodeRepl.args : undefined).toEqual(["server.js"]);
  525. expect(env[ZCODE_CUA_BROKER_SOCKET_ENV]).toBe(socketPath);
  526. // identity 模式:凭据只有 socket + authority(+ refresh marker)。遗留 token 即使存在于
  527. // process.env 也必须止步于 sanitize,不得被重新注入给 node_repl —— 否则等于把一个
  528. // 旧 Helper 认的口令又发给了子进程。
  529. expect(env[LEGACY_BROKER_TOKEN_ENV]).toBeUndefined();
  530. expect(env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY]).toBe("dev.zcode.cua-helper/dev");
  531. expect(env["ZCODE_CUA_PERMISSION_BROKER_REFRESH_MARKER"]).toBe(
  532. `${socketPath}.permission-refresh.json`,
  533. );
  534. } finally {
  535. resetCapturedZCodeCuaBrokerCredentialsForTest();
  536. if (previousSocket === undefined) delete process.env[ZCODE_CUA_BROKER_SOCKET_ENV];
  537. else process.env[ZCODE_CUA_BROKER_SOCKET_ENV] = previousSocket;
  538. if (previousToken === undefined) delete process.env[LEGACY_BROKER_TOKEN_ENV];
  539. else process.env[LEGACY_BROKER_TOKEN_ENV] = previousToken;
  540. if (previousAuthority === undefined) delete process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY];
  541. else process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY] = previousAuthority;
  542. if (previousRefreshMarker === undefined) delete process.env["ZCODE_CUA_PERMISSION_BROKER_REFRESH_MARKER"];
  543. else process.env["ZCODE_CUA_PERMISSION_BROKER_REFRESH_MARKER"] = previousRefreshMarker;
  544. if (previousUnavailable === undefined) delete process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV];
  545. else process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV] = previousUnavailable;
  546. }
  547. });
  548. it("does not capture or re-inject a partial broker credential set without plugin authority", () => {
  549. resetCapturedZCodeCuaBrokerCredentialsForTest();
  550. try {
  551. const partialEnv: Record<string, string | undefined> = {
  552. [ZCODE_CUA_BROKER_SOCKET_ENV]: "/tmp/partial.sock",
  553. [LEGACY_BROKER_TOKEN_ENV]: "partial-token",
  554. };
  555. sanitizeZCodeRuntimeEnvInPlace(partialEnv);
  556. const result = omitMcpServers(
  557. {
  558. "zcode-cua": { type: "stdio", command: "uvx", args: ["zcode-cua"] },
  559. },
  560. new Set(),
  561. );
  562. const cua = result["zcode-cua"];
  563. const args = cua?.type === "stdio" ? (cua.args ?? []) : [];
  564. const env = cua?.type === "stdio" ? (cua.env ?? {}) : {};
  565. expect(args).not.toContain("/tmp/partial.sock");
  566. expect(env[ZCODE_CUA_BROKER_SOCKET_ENV]).toBeUndefined();
  567. expect(env[LEGACY_BROKER_TOKEN_ENV]).toBeUndefined();
  568. expect(env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY]).toBeUndefined();
  569. if (process.platform === "darwin") expect(cua).toBeUndefined();
  570. } finally {
  571. resetCapturedZCodeCuaBrokerCredentialsForTest();
  572. }
  573. });
  574. it("fails closed by omitting the global zcode-cua when the broker is unavailable after sanitization", () => {
  575. const previousSocket = process.env[ZCODE_CUA_BROKER_SOCKET_ENV];
  576. const previousToken = process.env[LEGACY_BROKER_TOKEN_ENV];
  577. const previousUnavailable = process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV];
  578. resetCapturedZCodeCuaBrokerCredentialsForTest();
  579. try {
  580. delete process.env[ZCODE_CUA_BROKER_SOCKET_ENV];
  581. delete process.env[LEGACY_BROKER_TOKEN_ENV];
  582. process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV] = "broker_unavailable: health_timeout";
  583. const servers: Record<string, McpServerConfig> = {
  584. "zcode-cua": {
  585. type: "stdio",
  586. command: "uvx",
  587. args: ["zcode-cua"],
  588. },
  589. };
  590. const result = omitMcpServers(servers, new Set(), new Set(["zcode-cua"]));
  591. expect(result["zcode-cua"]).toBeUndefined();
  592. } finally {
  593. resetCapturedZCodeCuaBrokerCredentialsForTest();
  594. if (previousSocket === undefined) delete process.env[ZCODE_CUA_BROKER_SOCKET_ENV];
  595. else process.env[ZCODE_CUA_BROKER_SOCKET_ENV] = previousSocket;
  596. if (previousToken === undefined) delete process.env[LEGACY_BROKER_TOKEN_ENV];
  597. else process.env[LEGACY_BROKER_TOKEN_ENV] = previousToken;
  598. if (previousUnavailable === undefined) delete process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV];
  599. else process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV] = previousUnavailable;
  600. }
  601. });
  602. it("prefers captured broker credentials over stale/injected process.env values", () => {
  603. const previousSocket = process.env[ZCODE_CUA_BROKER_SOCKET_ENV];
  604. const previousToken = process.env[LEGACY_BROKER_TOKEN_ENV];
  605. const previousAuthority = process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY];
  606. const previousUnavailable = process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV];
  607. resetCapturedZCodeCuaBrokerCredentialsForTest();
  608. try {
  609. // 捕获可信凭据(模拟 CLI 入口 sanitize 从 ZCode 下发的 spawn env 捕获)。
  610. const spawnEnv: Record<string, string | undefined> = {
  611. [ZCODE_CUA_BROKER_SOCKET_ENV]: "/tmp/captured.sock",
  612. [LEGACY_BROKER_TOKEN_ENV]: "captured-token",
  613. [ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY]: "dev.zcode.cua-helper/captured",
  614. };
  615. sanitizeZCodeRuntimeEnvInPlace(spawnEnv);
  616. // 运行时 env 里残留/被注入了不同的 broker 值:绝不能覆盖 captured。
  617. process.env[ZCODE_CUA_BROKER_SOCKET_ENV] = "/tmp/stale.sock";
  618. process.env[LEGACY_BROKER_TOKEN_ENV] = "stale-token";
  619. delete process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV];
  620. const result = omitMcpServers(
  621. { node_repl: { type: "stdio", command: "node", args: ["server.js"] } },
  622. new Set(),
  623. new Set(["node_repl"]),
  624. );
  625. const nodeRepl = result.node_repl;
  626. const env = nodeRepl?.type === "stdio" ? (nodeRepl.env ?? {}) : {};
  627. expect(nodeRepl?.type === "stdio" ? nodeRepl.args : undefined).toEqual(["server.js"]);
  628. expect(env[ZCODE_CUA_BROKER_SOCKET_ENV]).toBe("/tmp/captured.sock");
  629. // captured 凭据也不含 token(identity 模式);spawn env 里的遗留 token 被 sanitize 吃掉。
  630. expect(env[LEGACY_BROKER_TOKEN_ENV]).toBeUndefined();
  631. expect(env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY]).toBe("dev.zcode.cua-helper/captured");
  632. } finally {
  633. resetCapturedZCodeCuaBrokerCredentialsForTest();
  634. if (previousSocket === undefined) delete process.env[ZCODE_CUA_BROKER_SOCKET_ENV];
  635. else process.env[ZCODE_CUA_BROKER_SOCKET_ENV] = previousSocket;
  636. if (previousToken === undefined) delete process.env[LEGACY_BROKER_TOKEN_ENV];
  637. else process.env[LEGACY_BROKER_TOKEN_ENV] = previousToken;
  638. if (previousAuthority === undefined) delete process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY];
  639. else process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY] = previousAuthority;
  640. if (previousUnavailable === undefined) delete process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV];
  641. else process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV] = previousUnavailable;
  642. }
  643. });
  644. describe("retired direct-CLI zcode-cua never starts an MCP server", () => {
  645. const restore = (snapshot: Record<string, string | undefined>) => {
  646. for (const [key, value] of Object.entries(snapshot)) {
  647. if (value === undefined) delete process.env[key];
  648. else process.env[key] = value;
  649. }
  650. };
  651. const KEYS = [
  652. ZCODE_CUA_BROKER_SOCKET_ENV,
  653. LEGACY_BROKER_TOKEN_ENV,
  654. ZCODE_CUA_BROKER_UNAVAILABLE_ENV,
  655. "ZCODE_CUA_HELPER_ALLOW_UNAUTHENTICATED_LOCAL",
  656. ];
  657. const snapshot = () =>
  658. Object.fromEntries(KEYS.map((k) => [k, process.env[k]])) as Record<
  659. string,
  660. string | undefined
  661. >;
  662. const clearAll = () => KEYS.forEach((k) => delete process.env[k]);
  663. const cuaServer = (): Record<string, McpServerConfig> => ({
  664. "zcode-cua": {
  665. type: "stdio",
  666. command: "uvx",
  667. args: ["zcode-cua"],
  668. },
  669. });
  670. it("omits a global zcode-cua regardless of broker state", () => {
  671. const saved = snapshot();
  672. resetCapturedZCodeCuaBrokerCredentialsForTest();
  673. try {
  674. clearAll();
  675. const result = omitMcpServers(cuaServer(), new Set());
  676. expect(result["zcode-cua"]).toBeUndefined();
  677. } finally {
  678. resetCapturedZCodeCuaBrokerCredentialsForTest();
  679. restore(saved);
  680. }
  681. });
  682. it("does not keep a retired zcode-cua even when it has broker credentials", () => {
  683. const saved = snapshot();
  684. resetCapturedZCodeCuaBrokerCredentialsForTest();
  685. try {
  686. clearAll();
  687. const servers: Record<string, McpServerConfig> = {
  688. "zcode-cua": {
  689. type: "stdio",
  690. command: "uvx",
  691. args: ["zcode-cua"],
  692. env: {
  693. [ZCODE_CUA_BROKER_SOCKET_ENV]: "/tmp/desktop-injected.sock",
  694. },
  695. },
  696. };
  697. expect(omitMcpServers(servers, new Set())["zcode-cua"]).toBeUndefined();
  698. } finally {
  699. resetCapturedZCodeCuaBrokerCredentialsForTest();
  700. restore(saved);
  701. }
  702. });
  703. it("does not restore the retired server under the local-dev opt-in", () => {
  704. const saved = snapshot();
  705. resetCapturedZCodeCuaBrokerCredentialsForTest();
  706. try {
  707. clearAll();
  708. process.env.ZCODE_CUA_HELPER_ALLOW_UNAUTHENTICATED_LOCAL = "1";
  709. const raw = cuaServer()["zcode-cua"];
  710. if (raw?.type === "stdio") {
  711. raw.args = ["zcode-cua", "--backend", "auto", "--permission-mode=dev"];
  712. }
  713. const kept = omitMcpServers({ "zcode-cua": raw! }, new Set())["zcode-cua"];
  714. expect(kept).toBeUndefined();
  715. } finally {
  716. resetCapturedZCodeCuaBrokerCredentialsForTest();
  717. restore(saved);
  718. }
  719. });
  720. });
  721. });
  722. function createRecordingMcpPort(
  723. connectedServerSets: string[][],
  724. connectedConfigs: Record<string, McpServerConfig>[] = [],
  725. ): McpPort {
  726. return {
  727. async callTool() {
  728. return { content: [] };
  729. },
  730. async close() {},
  731. async connectConfiguredServers(servers) {
  732. connectedServerSets.push(Object.keys(servers));
  733. connectedConfigs.push(servers);
  734. return {
  735. statuses: {},
  736. tools: [],
  737. };
  738. },
  739. async connectServer(name, config) {
  740. return {
  741. status: "connected",
  742. transport: config.type,
  743. toolCount: 0,
  744. updatedAt: new Date().toISOString(),
  745. };
  746. },
  747. async disconnectServer() {
  748. return undefined;
  749. },
  750. async listTools() {
  751. return [];
  752. },
  753. async status() {
  754. return {};
  755. },
  756. };
  757. }
  758. function createStopModelExecutor() {
  759. return {
  760. // 根因:createZCodeApp 初始化时会同步配置模型 I/O 保留策略;旧测试夹具缺少该方法会在用例逻辑前崩溃。
  761. setModelIoFullRetentionEnabled() {},
  762. async generateText() {
  763. return {
  764. finishReason: "stop",
  765. text: "ok",
  766. usage: {
  767. inputTokens: 1,
  768. outputTokens: 1,
  769. totalTokens: 2,
  770. },
  771. };
  772. },
  773. async *streamText() {
  774. yield {
  775. finishReason: "stop",
  776. type: "finish",
  777. usage: {
  778. inputTokens: 1,
  779. outputTokens: 1,
  780. totalTokens: 2,
  781. },
  782. };
  783. },
  784. } as never;
  785. }