endpoint.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. /* 官方插件命令进程的代理端点(技术方案 5.8):CLI 不持有凭证,端点按 session token 认出会话、
  2. * 只放行 Sites 接口、向 host 现取身份头后转发给 zcode-server。这里用真实的 UDS 和一个本地
  3. * 假 zcode-server 验证转发细节,凭证解析由 host 侧测试覆盖。 */
  4. import { stat } from "node:fs/promises";
  5. import { createServer, request, type IncomingHttpHeaders, type Server } from "node:http";
  6. import { dirname } from "node:path";
  7. import { afterEach, assert, describe, expect, it, vi } from "vitest";
  8. import {
  9. ZCODE_OFFICIAL_ENDPOINT_ENV_KEY,
  10. ZCODE_OFFICIAL_ENDPOINT_TOKEN_ENV_KEY,
  11. } from "@zcode/shared";
  12. import type { ExecutionPort, ExecutionRequest } from "@zcode/contracts";
  13. import {
  14. supportsBackgroundTaskWaiter,
  15. supportsBashBackgroundLifecycle,
  16. type BackgroundTaskWaiterExecutionPort,
  17. type BashBackgroundLifecycleExecutionPort,
  18. } from "@zcode/core";
  19. import {
  20. createOfficialCommandEndpoint,
  21. withOfficialCommandEnv,
  22. type OfficialCommandEndpoint,
  23. } from "../../src/official-command-endpoint/index.js";
  24. import { createOfficialCommandAuthHeadersPort } from "../../src/zcode-protocol/official-mcp-auth-port.js";
  25. const IDENTITY = { Authorization: "Bearer zcode-jwt", "X-Bigmodel-Authorization": "Bearer maas" };
  26. const WORKSPACE_A = { workspacePath: "/w/a" };
  27. const WORKSPACE_B = { workspacePath: "/w/b", workspaceIdentity: "remote:b" };
  28. type Seen = { method: string; url: string; headers: IncomingHttpHeaders; body: Buffer };
  29. async function startUpstream(
  30. reply: (seen: Seen) => { status: number; body: string } = () => ({
  31. status: 200,
  32. body: JSON.stringify({ code: 0, msg: "success", data: { ok: true }, logid: "l" }),
  33. }),
  34. ): Promise<{ origin: string; seen: Seen[]; server: Server }> {
  35. const seen: Seen[] = [];
  36. const server = createServer((req, res) => {
  37. const chunks: Buffer[] = [];
  38. req.on("data", (chunk: Buffer) => chunks.push(chunk));
  39. req.on("end", () => {
  40. const entry = {
  41. body: Buffer.concat(chunks),
  42. headers: req.headers,
  43. method: req.method ?? "",
  44. url: req.url ?? "",
  45. };
  46. seen.push(entry);
  47. const { status, body } = reply(entry);
  48. res.writeHead(status, { "content-type": "application/json", "set-cookie": "a=b" }).end(body);
  49. });
  50. });
  51. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  52. const address = server.address() as { port: number };
  53. return { origin: `http://127.0.0.1:${address.port}`, seen, server };
  54. }
  55. function call(
  56. env: Record<string, string>,
  57. path: string,
  58. init: {
  59. method?: string;
  60. headers?: Record<string, string>;
  61. body?: Buffer | string;
  62. token?: string;
  63. } = {},
  64. ): Promise<{ status: number; headers: IncomingHttpHeaders; body: string }> {
  65. return new Promise((resolve, reject) => {
  66. const body = init.body;
  67. const req = request(
  68. {
  69. socketPath: env[ZCODE_OFFICIAL_ENDPOINT_ENV_KEY],
  70. path,
  71. method: init.method ?? "GET",
  72. headers: {
  73. Authorization: `Bearer ${init.token ?? env[ZCODE_OFFICIAL_ENDPOINT_TOKEN_ENV_KEY]}`,
  74. ...(body !== undefined ? { "Content-Length": String(Buffer.byteLength(body)) } : {}),
  75. ...init.headers,
  76. },
  77. },
  78. (res) => {
  79. const chunks: Buffer[] = [];
  80. res.on("data", (chunk: Buffer) => chunks.push(chunk));
  81. res.on("end", () =>
  82. resolve({
  83. body: Buffer.concat(chunks).toString(),
  84. headers: res.headers,
  85. status: res.statusCode ?? 0,
  86. }),
  87. );
  88. },
  89. );
  90. req.on("error", reject);
  91. req.end(body);
  92. });
  93. }
  94. describe("official command endpoint", () => {
  95. const cleanups: Array<() => Promise<void>> = [];
  96. afterEach(async () => {
  97. while (cleanups.length > 0) await cleanups.pop()!();
  98. });
  99. async function setup(
  100. options: {
  101. reply?: Parameters<typeof startUpstream>[0];
  102. resolveHeaders?: ReturnType<typeof vi.fn>;
  103. origin?: string;
  104. } = {},
  105. ) {
  106. const upstream = await startUpstream(options.reply);
  107. cleanups.push(() => new Promise((resolve) => upstream.server.close(() => resolve())));
  108. const resolveHeaders =
  109. options.resolveHeaders ?? vi.fn(async () => ({ ok: true as const, headers: IDENTITY }));
  110. const endpoint: OfficialCommandEndpoint = createOfficialCommandEndpoint({
  111. appVersion: "3.16.0",
  112. fetch: globalThis.fetch,
  113. resolveHeaders,
  114. resolveZCodeApiOrigin: () => options.origin ?? upstream.origin,
  115. });
  116. cleanups.push(() => endpoint.close());
  117. return { endpoint, resolveHeaders, upstream };
  118. }
  119. it("gives each session its own token on one private socket", async () => {
  120. const { endpoint } = await setup();
  121. const a = await endpoint.envForSession("session-a", WORKSPACE_A);
  122. const again = await endpoint.envForSession("session-a", WORKSPACE_A);
  123. const b = await endpoint.envForSession("session-b", WORKSPACE_B);
  124. expect(again).toEqual(a);
  125. expect(b[ZCODE_OFFICIAL_ENDPOINT_ENV_KEY]).toBe(a[ZCODE_OFFICIAL_ENDPOINT_ENV_KEY]);
  126. expect(b[ZCODE_OFFICIAL_ENDPOINT_TOKEN_ENV_KEY]).not.toBe(
  127. a[ZCODE_OFFICIAL_ENDPOINT_TOKEN_ENV_KEY],
  128. );
  129. if (process.platform !== "win32") {
  130. const dir = await stat(dirname(a[ZCODE_OFFICIAL_ENDPOINT_ENV_KEY]!));
  131. expect(dir.mode & 0o077).toBe(0);
  132. }
  133. });
  134. it("asks for identity with the workspace of the session that owns the token", async () => {
  135. const { endpoint, resolveHeaders } = await setup();
  136. const a = await endpoint.envForSession("session-a", WORKSPACE_A);
  137. const b = await endpoint.envForSession("session-b", WORKSPACE_B);
  138. expect((await call(b, "/api/v1/sites/usage")).status).toBe(200);
  139. expect((await call(a, "/api/v1/sites/usage")).status).toBe(200);
  140. expect(resolveHeaders.mock.calls.map(([input]) => input.workspace)).toEqual([
  141. WORKSPACE_B,
  142. WORKSPACE_A,
  143. ]);
  144. });
  145. it("rejects unknown tokens and paths outside the allowed prefix without asking for identity", async () => {
  146. const { endpoint, resolveHeaders, upstream } = await setup();
  147. const env = await endpoint.envForSession("session-a", WORKSPACE_A);
  148. const badToken = await call(env, "/api/v1/sites", { token: "forged" });
  149. expect(badToken.status).toBe(403);
  150. expect(badToken.headers["x-zcode-official-endpoint-error"]).toBe("invalid");
  151. for (const path of ["/api/v1/users/me", "/api/v1/sitesx", "/api/v1/sites/../mcp/usage", "/"]) {
  152. const res = await call(env, path);
  153. expect(res.status, path).toBe(403);
  154. expect(JSON.parse(res.body).code).toBe(2007);
  155. }
  156. expect(resolveHeaders).not.toHaveBeenCalled();
  157. expect(upstream.seen).toHaveLength(0);
  158. });
  159. it("replaces client credentials with the official identity and streams the body", async () => {
  160. const { endpoint, resolveHeaders, upstream } = await setup();
  161. const env = await endpoint.envForSession("session-a", WORKSPACE_A);
  162. const pkg = Buffer.alloc(3 * 1024 * 1024, 7);
  163. const res = await call(env, "/api/v1/sites/1/deployments/2/package?x=1", {
  164. body: pkg,
  165. headers: {
  166. "Content-Type": "application/gzip",
  167. Cookie: "c=d",
  168. "X-Bigmodel-Authorization": "Bearer forged",
  169. "X-ZCode-App-Version": "0.0.1",
  170. "X-Zcode-Plan": "max",
  171. },
  172. method: "PUT",
  173. });
  174. expect(res.status).toBe(200);
  175. expect(JSON.parse(res.body)).toMatchObject({ code: 0, data: { ok: true } });
  176. expect(res.headers["set-cookie"]).toBeUndefined();
  177. expect(resolveHeaders).toHaveBeenCalledWith(
  178. expect.objectContaining({ pluginId: "zcode-site", targetOrigin: upstream.origin }),
  179. );
  180. const [seen] = upstream.seen;
  181. expect(seen!.method).toBe("PUT");
  182. expect(seen!.url).toBe("/api/v1/sites/1/deployments/2/package?x=1");
  183. expect(seen!.headers.authorization).toBe("Bearer zcode-jwt");
  184. expect(seen!.headers["x-bigmodel-authorization"]).toBe("Bearer maas");
  185. expect(seen!.headers["x-zcode-app-version"]).toBe("3.16.0");
  186. expect(seen!.headers["content-type"]).toBe("application/gzip");
  187. expect(seen!.headers["content-length"]).toBe(String(pkg.length));
  188. expect(seen!.headers["transfer-encoding"]).toBeUndefined();
  189. expect(seen!.headers.cookie).toBeUndefined();
  190. expect(seen!.headers["x-zcode-plan"]).toBeUndefined();
  191. expect(seen!.body.equals(pkg)).toBe(true);
  192. });
  193. it("answers 401 without identity and 2007 for other identity failures", async () => {
  194. const resolveHeaders = vi
  195. .fn()
  196. .mockResolvedValueOnce({ ok: false, reason: "official_auth_unavailable" })
  197. .mockResolvedValueOnce({ ok: false, reason: "official_mcp_origin_untrusted" })
  198. .mockRejectedValueOnce(new Error("host gone"));
  199. const { endpoint, upstream } = await setup({ resolveHeaders });
  200. const env = await endpoint.envForSession("session-a", WORKSPACE_A);
  201. const signedOut = await call(env, "/api/v1/sites/usage");
  202. expect(signedOut.status).toBe(401);
  203. expect(signedOut.body).toBe("");
  204. const untrusted = await call(env, "/api/v1/sites/usage");
  205. expect(untrusted.status).toBe(502);
  206. expect(JSON.parse(untrusted.body).code).toBe(2007);
  207. expect((await call(env, "/api/v1/sites/usage")).status).toBe(401);
  208. expect(upstream.seen).toHaveLength(0);
  209. });
  210. it("marks an unreachable zcode-server as a network error", async () => {
  211. const { endpoint } = await setup({ origin: "http://127.0.0.1:1" });
  212. const env = await endpoint.envForSession("session-a", WORKSPACE_A);
  213. const res = await call(env, "/api/v1/sites/usage");
  214. expect(res.status).toBe(502);
  215. expect(res.headers["x-zcode-official-endpoint-error"]).toBe("network");
  216. });
  217. it("reports every deployment request to the observer of the token's session, whatever the result", async () => {
  218. const { endpoint } = await setup({
  219. reply: (seen) =>
  220. seen.url === "/api/v1/sites/busy/deployments"
  221. ? { status: 409, body: JSON.stringify({ code: 3610, msg: "busy", data: null }) }
  222. : { status: 200, body: JSON.stringify({ code: 0, msg: "success", data: {} }) },
  223. });
  224. const observerA = { onSiteDeploymentRequested: vi.fn() };
  225. const observerB = { onSiteDeploymentRequested: vi.fn() };
  226. const a = await endpoint.envForSession("session-a", WORKSPACE_A, observerA);
  227. await endpoint.envForSession("session-b", WORKSPACE_B, observerB);
  228. await call(a, "/api/v1/sites/s-1/deployments", { body: "{}", method: "POST" });
  229. const busy = await call(a, "/api/v1/sites/busy/deployments", { body: "{}", method: "POST" });
  230. expect(busy.status).toBe(409);
  231. expect(observerA.onSiteDeploymentRequested).toHaveBeenCalledTimes(2);
  232. expect(observerB.onSiteDeploymentRequested).not.toHaveBeenCalled();
  233. });
  234. it("does not report other Sites calls", async () => {
  235. const { endpoint, upstream } = await setup();
  236. const observer = { onSiteDeploymentRequested: vi.fn() };
  237. const env = await endpoint.envForSession("session-a", WORKSPACE_A, observer);
  238. await call(env, "/api/v1/sites/s-1/deployments");
  239. await call(env, "/api/v1/sites/s-1/deployments/d-1/package", { body: "x", method: "PUT" });
  240. await call(env, "/api/v1/sites", { body: "{}", method: "POST" });
  241. expect(upstream.seen).toHaveLength(3);
  242. expect(observer.onSiteDeploymentRequested).not.toHaveBeenCalled();
  243. });
  244. it("stops serving and removes the socket on close", async () => {
  245. const { endpoint } = await setup();
  246. const env = await endpoint.envForSession("session-a", WORKSPACE_A);
  247. await endpoint.close();
  248. await expect(call(env, "/api/v1/sites/usage")).rejects.toThrow();
  249. expect(await endpoint.envForSession("session-a", WORKSPACE_A)).toEqual({});
  250. if (process.platform !== "win32") {
  251. await expect(stat(dirname(env[ZCODE_OFFICIAL_ENDPOINT_ENV_KEY]!))).rejects.toThrow();
  252. }
  253. });
  254. });
  255. describe("withOfficialCommandEnv", () => {
  256. function fakePort() {
  257. const run = vi.fn(async (_request: ExecutionRequest) => ({}) as never);
  258. const start = vi.fn(async (_request: ExecutionRequest) => ({}) as never);
  259. const getBackgroundTask = vi.fn(async () => undefined);
  260. return { getBackgroundTask, run, start } satisfies ExecutionPort;
  261. }
  262. const request = (env?: ExecutionRequest["env"]): ExecutionRequest =>
  263. ({ command: { mode: "shell", command: "true" }, ...(env ? { env } : {}) }) as ExecutionRequest;
  264. it("adds the session endpoint env to foreground and background runs", async () => {
  265. const port = fakePort();
  266. const wrapped = withOfficialCommandEnv(port, async () => ({ ZCODE_OFFICIAL_ENDPOINT: "/s" }));
  267. await wrapped.run(request({ set: { A: "1", ZCODE_OFFICIAL_ENDPOINT: "/forged" } }));
  268. await wrapped.start!(request());
  269. await wrapped.run(request({ base: "empty" }));
  270. expect(port.run.mock.calls[0]![0].env).toEqual({
  271. set: { A: "1", ZCODE_OFFICIAL_ENDPOINT: "/s" },
  272. });
  273. expect(port.start.mock.calls[0]![0].env).toEqual({ set: { ZCODE_OFFICIAL_ENDPOINT: "/s" } });
  274. expect(port.run.mock.calls[1]![0].env).toEqual({ base: "empty" });
  275. expect(wrapped.getBackgroundTask).toBeDefined();
  276. expect(wrapped.cancelBackgroundTask).toBeUndefined();
  277. expect(supportsBashBackgroundLifecycle(wrapped)).toBe(false);
  278. expect(supportsBackgroundTaskWaiter(wrapped)).toBe(false);
  279. });
  280. const lifecycleModes = ["explicit", "auto_on_timeout"] as const;
  281. const backgroundOutcome = {
  282. kind: "backgrounded" as const,
  283. task: { taskId: "task-1", status: "running" as const, startedAt: new Date(0) },
  284. };
  285. it.each(lifecycleModes)(
  286. "preserves the %s Bash lifecycle and injects the session env",
  287. async (mode) => {
  288. const runBash = vi
  289. .fn<BashBackgroundLifecycleExecutionPort["runBashWithBackgroundLifecycle"]>()
  290. .mockResolvedValue(backgroundOutcome);
  291. const port = Object.freeze({ ...fakePort(), runBashWithBackgroundLifecycle: runBash });
  292. const endpointEnv = {
  293. ZCODE_OFFICIAL_ENDPOINT: "/session",
  294. ZCODE_OFFICIAL_ENDPOINT_TOKEN: "token",
  295. };
  296. const resolveEnv = vi.fn(async () => endpointEnv);
  297. const wrapped = withOfficialCommandEnv(port, resolveEnv);
  298. const originalRequest = request({ set: { A: "1", ZCODE_OFFICIAL_ENDPOINT: "/forged" } });
  299. const lifecycle = { mode };
  300. const options = { signal: new AbortController().signal, onEvent: vi.fn() };
  301. assert(
  302. supportsBashBackgroundLifecycle(wrapped),
  303. "environment wrapper lost the Bash lifecycle",
  304. );
  305. const result = await wrapped.runBashWithBackgroundLifecycle(
  306. originalRequest,
  307. lifecycle,
  308. options,
  309. );
  310. expect(result).toBe(backgroundOutcome);
  311. expect(runBash).toHaveBeenCalledTimes(1);
  312. expect(runBash.mock.contexts[0]).toBe(port);
  313. const [forwardedRequest, forwardedLifecycle, forwardedOptions] = runBash.mock.calls[0]!;
  314. expect(forwardedRequest).toEqual({
  315. ...originalRequest,
  316. env: { set: { A: "1", ...endpointEnv } },
  317. });
  318. expect(forwardedLifecycle).toBe(lifecycle);
  319. expect(forwardedOptions).toBe(options);
  320. expect(originalRequest.env?.set?.ZCODE_OFFICIAL_ENDPOINT).toBe("/forged");
  321. expect(resolveEnv).toHaveBeenCalledTimes(1);
  322. expect(port.run).not.toHaveBeenCalled();
  323. expect(port.start).not.toHaveBeenCalled();
  324. },
  325. );
  326. it.each(lifecycleModes)(
  327. "preserves a clean environment for the %s Bash lifecycle",
  328. async (mode) => {
  329. const runBash = vi
  330. .fn<BashBackgroundLifecycleExecutionPort["runBashWithBackgroundLifecycle"]>()
  331. .mockResolvedValue(backgroundOutcome);
  332. const resolveEnv = vi.fn(async () => ({ ZCODE_OFFICIAL_ENDPOINT: "/session" }));
  333. const port = { ...fakePort(), runBashWithBackgroundLifecycle: runBash };
  334. const wrapped = withOfficialCommandEnv(port, resolveEnv);
  335. const originalRequest = request({ base: "empty" });
  336. assert(supportsBashBackgroundLifecycle(wrapped));
  337. await wrapped.runBashWithBackgroundLifecycle(originalRequest, { mode });
  338. expect(runBash.mock.calls[0]![0]).toBe(originalRequest);
  339. expect(resolveEnv).not.toHaveBeenCalled();
  340. },
  341. );
  342. it("preserves lifecycle errors when the endpoint env is unavailable", async () => {
  343. const failure = new Error("execution failed");
  344. const runBash = vi
  345. .fn<BashBackgroundLifecycleExecutionPort["runBashWithBackgroundLifecycle"]>()
  346. .mockRejectedValue(failure);
  347. const resolveEnv = vi.fn().mockRejectedValue(new Error("listen failed"));
  348. const warn = vi.fn();
  349. const port = { ...fakePort(), runBashWithBackgroundLifecycle: runBash };
  350. const wrapped = withOfficialCommandEnv(port, resolveEnv, { warn });
  351. const originalRequest = request();
  352. assert(supportsBashBackgroundLifecycle(wrapped));
  353. await expect(
  354. wrapped.runBashWithBackgroundLifecycle(originalRequest, { mode: "explicit" }),
  355. ).rejects.toBe(failure);
  356. expect(runBash.mock.calls[0]![0]).toBe(originalRequest);
  357. expect(warn).toHaveBeenCalledTimes(1);
  358. });
  359. it("preserves the background task waiter so tracking does not fall back to polling", async () => {
  360. const snapshot = {
  361. taskId: "task-1",
  362. status: "completed" as const,
  363. startedAt: new Date(0),
  364. };
  365. const waitForBackgroundTask = vi
  366. .fn<BackgroundTaskWaiterExecutionPort["waitForBackgroundTask"]>()
  367. .mockResolvedValue(snapshot);
  368. const port = Object.freeze({ ...fakePort(), waitForBackgroundTask });
  369. const wrapped = withOfficialCommandEnv(port, async () => ({
  370. ZCODE_OFFICIAL_ENDPOINT: "/session",
  371. }));
  372. const options = { signal: new AbortController().signal };
  373. assert(supportsBackgroundTaskWaiter(wrapped), "environment wrapper lost the background waiter");
  374. const result = await wrapped.waitForBackgroundTask("task-1", options);
  375. expect(result).toBe(snapshot);
  376. expect(waitForBackgroundTask).toHaveBeenCalledTimes(1);
  377. expect(waitForBackgroundTask.mock.contexts[0]).toBe(port);
  378. expect(waitForBackgroundTask.mock.calls[0]).toEqual(["task-1", options]);
  379. });
  380. it("still runs the command when the endpoint is unavailable", async () => {
  381. const port = fakePort();
  382. const warn = vi.fn();
  383. const wrapped = withOfficialCommandEnv(
  384. port,
  385. async () => {
  386. throw new Error("listen failed");
  387. },
  388. { warn },
  389. );
  390. await wrapped.run(request());
  391. expect(port.run.mock.calls[0]![0].env).toBeUndefined();
  392. expect(warn).toHaveBeenCalled();
  393. });
  394. // 回归:包装层曾只转发 run/start,丢掉 Bash 后台生命周期能力,Desktop 注入端点 env 后
  395. // run_in_background 的 Bash 全部报 "ExecutionPort does not support the Bash background lifecycle"。
  396. it("keeps the Bash background lifecycle and adds the endpoint env to it", async () => {
  397. const runBashWithBackgroundLifecycle = vi.fn(
  398. async (_request: ExecutionRequest, _lifecycle: { mode: string }) => ({}) as never,
  399. );
  400. const port = { ...fakePort(), runBashWithBackgroundLifecycle };
  401. const wrapped = withOfficialCommandEnv(port, async () => ({ ZCODE_OFFICIAL_ENDPOINT: "/s" }));
  402. const lifecycle = (wrapped as Partial<typeof port>).runBashWithBackgroundLifecycle;
  403. expect(lifecycle).toBeTypeOf("function");
  404. await lifecycle!(request(), { mode: "explicit" });
  405. expect(runBashWithBackgroundLifecycle.mock.calls[0]![0].env).toEqual({
  406. set: { ZCODE_OFFICIAL_ENDPOINT: "/s" },
  407. });
  408. expect(runBashWithBackgroundLifecycle.mock.calls[0]![1]).toEqual({ mode: "explicit" });
  409. const plain = withOfficialCommandEnv(fakePort(), async () => ({}));
  410. expect("runBashWithBackgroundLifecycle" in plain).toBe(false);
  411. });
  412. });
  413. describe("createOfficialCommandAuthHeadersPort", () => {
  414. const ask = (workspace: { workspacePath: string; workspaceIdentity?: string } = WORKSPACE_A) => ({
  415. pluginId: "zcode-site",
  416. targetOrigin: "https://zcode.test",
  417. workspace,
  418. });
  419. it("asks for plugin-command identity with the session workspace and without an mcpKey", async () => {
  420. const requestClient = vi.fn(async () => ({ ok: true as const, headers: IDENTITY }));
  421. const port = createOfficialCommandAuthHeadersPort({
  422. resolveContext: () => ({ requestClient }) as never,
  423. });
  424. await expect(port.resolveHeaders(ask())).resolves.toEqual({ ok: true, headers: IDENTITY });
  425. await port.resolveHeaders(ask(WORKSPACE_B));
  426. const params = (requestClient.mock.calls as unknown as [string, Record<string, unknown>][]).map(
  427. ([, value]) => value,
  428. );
  429. expect(params[0]).toMatchObject({
  430. consumer: "plugin-command",
  431. pluginId: "zcode-site",
  432. targetOrigin: "https://zcode.test",
  433. workspace: { workspaceKey: "/w/a", workspacePath: "/w/a" },
  434. });
  435. expect(params[0]).not.toHaveProperty("mcpKey");
  436. expect(params[1]).toMatchObject({
  437. workspace: { workspaceIdentity: "remote:b", workspaceKey: "remote:b", workspacePath: "/w/b" },
  438. });
  439. });
  440. it("is unavailable before the protocol server is ready or when the host fails", async () => {
  441. const before = createOfficialCommandAuthHeadersPort({ resolveContext: () => undefined });
  442. await expect(before.resolveHeaders(ask())).resolves.toEqual({
  443. ok: false,
  444. reason: "official_auth_unavailable",
  445. });
  446. const warn = vi.fn();
  447. const failing = createOfficialCommandAuthHeadersPort({
  448. logger: { warn },
  449. resolveContext: () =>
  450. ({
  451. requestClient: vi
  452. .fn()
  453. .mockRejectedValue(new Error("Request workspace is not owned by this CLI")),
  454. }) as never,
  455. });
  456. await expect(failing.resolveHeaders(ask())).resolves.toEqual({
  457. ok: false,
  458. reason: "official_auth_unavailable",
  459. });
  460. expect(warn).toHaveBeenCalledWith(
  461. expect.any(String),
  462. expect.objectContaining({
  463. error: "Request workspace is not owned by this CLI",
  464. event: "zcode_protocol.official_command_endpoint.auth_request_failed",
  465. workspaceKey: "/w/a",
  466. }),
  467. );
  468. });
  469. });