web-remote-control-auth-gate-fixture.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. import { once } from "node:events";
  2. import { readFile, writeFile } from "node:fs/promises";
  3. import { createServer } from "node:http";
  4. import { prepareWebRemoteControlSessionEventsFixture } from "./web-remote-control-session-events-fixture.js";
  5. /** 观测未登录门禁与远控401后的登录启动;不模拟认证成功。 */
  6. export async function prepareWebRemoteControlAuthGateFixture(options: {
  7. specs: string[];
  8. credentialsFile: string;
  9. settingsFile: string;
  10. workspacePath: string;
  11. webUrl?: string;
  12. }): Promise<(() => Promise<void>) | null> {
  13. if (
  14. options.specs.some(
  15. (spec) =>
  16. spec.endsWith("conversation-session-virtual-project-mobile.test.ts") ||
  17. spec.endsWith("conversation-session-project-new-order-mobile.test.ts") ||
  18. spec.endsWith("conversation-session-archive-management.test.ts") ||
  19. spec.endsWith("app-control-explicit-navigation.test.ts") ||
  20. spec.endsWith("app-control-cross-project-search.test.ts") ||
  21. spec.endsWith("app-control-session-lifecycle.test.ts") ||
  22. spec.endsWith("conversation-session-composer-settlement.test.ts") ||
  23. spec.endsWith("conversation-session-switch-stability.test.ts") ||
  24. spec.endsWith("conversation-session-new-task-missing-root-mobile.test.ts") ||
  25. spec.endsWith("conversation-session-draft-model-migration-mobile.test.ts") ||
  26. spec.endsWith("command-center-history-search.test.ts") ||
  27. spec.endsWith("conversation-session-web-remote-terminal.test.ts") ||
  28. spec.endsWith("conversation-session-web-remote-terminal-ssh.test.ts") ||
  29. spec.endsWith("conversation-session-archive-management.test.ts") ||
  30. spec.endsWith("conversation-session-runtime-restart.test.ts") ||
  31. spec.endsWith("conversation-session-fork-cold-start-membership.test.ts") ||
  32. spec.endsWith("conversation-session-background.test.ts") ||
  33. spec.endsWith("conversation-session-shared-cli.test.ts") ||
  34. spec.endsWith("conversation-session-queue-edit-freeze-mobile.test.ts") ||
  35. // 远程批量 runner 的 HOME 没有登录态;复用本地账号/relay,避免卡在配对链接门禁。
  36. spec.endsWith("conversation-session-r3-mobile.test.ts") ||
  37. spec.endsWith("conversation-session-r3-mobile-permission.test.ts") ||
  38. spec.endsWith("conversation-session-r3-mobile-startup-restore.test.ts") ||
  39. spec.endsWith("conversation-session-project-management.test.ts") ||
  40. spec.endsWith("conversation-session-r3-soak-dual.test.ts") ||
  41. spec.endsWith("conversation-session-web-remote-project-directory.test.ts") ||
  42. spec.endsWith("conversation-session-remote-draft-prewarm.test.ts") ||
  43. spec.endsWith("conversation-session-web-remote-recovery.test.ts") ||
  44. spec.endsWith("conversation-session-web-remote-unread.test.ts") ||
  45. spec.endsWith("conversation-session-web-remote-unread-ssh.test.ts") ||
  46. spec.endsWith("conversation-session-workspace-mcp-trust.test.ts") ||
  47. spec.endsWith("conversation-session-id-compatibility.test.ts") ||
  48. spec.endsWith("conversation-session-status-panel-inline-layout.test.ts") ||
  49. spec.endsWith("conversation-session-background-history-layout.test.ts") ||
  50. spec.endsWith("conversation-session-v4-queue.test.ts") ||
  51. spec.endsWith("conversation-session-v4-composer-toolbar.test.ts") ||
  52. spec.endsWith("conversation-session-highspeed-card.test.ts") ||
  53. spec.endsWith("conversation-session-gen-ui-context.test.ts") ||
  54. spec.endsWith("conversation-session-v4-session-action-locks.test.ts") ||
  55. spec.endsWith("conversation-session-assistant-block-order.test.ts") ||
  56. spec.endsWith("conversation-session-hooks-mobile.test.ts") ||
  57. // HK19:手机远控设置页的 Workspace Hook 信任行;配对两端需要同一测试登录态。
  58. spec.endsWith("conversation-session-hook-trust.test.ts") ||
  59. spec.endsWith("conversation-session-pdf-preview-mobile.test.ts") ||
  60. spec.endsWith("conversation-session-mcp-async-startup-wait.test.ts") ||
  61. // PLM-EXT-P3C:扩展发的消息在手机上也显示「来自插件」。
  62. spec.endsWith("plugin-extension-sessions-write.test.ts"),
  63. )
  64. )
  65. return prepareWebRemoteControlSessionEventsFixture({
  66. ...options,
  67. // Highspeed 准备阶段替换登录凭据;配对两端仍需映射到同一个测试用户。
  68. additionalRelayUsers: options.specs.some((spec) =>
  69. spec.endsWith("conversation-session-highspeed-card.test.ts"),
  70. )
  71. ? { "e2e-highspeed-zcode-jwt": "zcode-e2e-user" }
  72. : undefined,
  73. // 新回归使用独立端口;既有手机用例仍保留固定入口。
  74. webUrl:
  75. options.webUrl ??
  76. (options.specs.some(
  77. (spec) =>
  78. spec.endsWith("conversation-session-web-remote-terminal.test.ts") ||
  79. spec.endsWith("conversation-session-web-remote-terminal-ssh.test.ts") ||
  80. spec.endsWith("conversation-session-archive-management.test.ts") ||
  81. spec.endsWith("conversation-session-composer-settlement.test.ts") ||
  82. spec.endsWith("conversation-session-switch-stability.test.ts") ||
  83. spec.endsWith("conversation-session-runtime-restart.test.ts") ||
  84. spec.endsWith("conversation-session-fork-cold-start-membership.test.ts") ||
  85. spec.endsWith("conversation-session-background.test.ts") ||
  86. spec.endsWith("conversation-session-shared-cli.test.ts") ||
  87. spec.endsWith("conversation-session-queue-edit-freeze-mobile.test.ts") ||
  88. spec.endsWith("conversation-session-status-panel-inline-layout.test.ts") ||
  89. spec.endsWith("conversation-session-background-history-layout.test.ts") ||
  90. spec.endsWith("conversation-session-v4-queue.test.ts") ||
  91. spec.endsWith("conversation-session-v4-composer-toolbar.test.ts") ||
  92. spec.endsWith("conversation-session-highspeed-card.test.ts") ||
  93. spec.endsWith("conversation-session-r3-mobile-startup-restore.test.ts") ||
  94. spec.endsWith("conversation-session-project-management.test.ts") ||
  95. spec.endsWith("conversation-session-new-task-missing-root-mobile.test.ts") ||
  96. spec.endsWith("conversation-session-draft-model-migration-mobile.test.ts") ||
  97. spec.endsWith("conversation-session-v4-session-action-locks.test.ts") ||
  98. spec.endsWith("conversation-session-hooks-mobile.test.ts") ||
  99. spec.endsWith("conversation-session-hook-trust.test.ts") ||
  100. spec.endsWith("conversation-session-pdf-preview-mobile.test.ts") ||
  101. spec.endsWith("plugin-extension-sessions-write.test.ts"),
  102. )
  103. ? "http://127.0.0.1:0/remote/v4"
  104. : "http://127.0.0.1:5173/remote/v4"),
  105. });
  106. if (options.specs.some((spec) => spec.endsWith("web-remote-control-regional-login.test.ts")))
  107. return prepareWebRemoteControlSessionEventsFixture({
  108. ...options,
  109. regionalDesktop: true,
  110. webUrl: "http://127.0.0.1:0/remote/v4",
  111. });
  112. if (options.specs.some((spec) => spec.endsWith("mobile-event-push.test.ts")))
  113. return prepareWebRemoteControlSessionEventsFixture({ ...options, mobilePush: true });
  114. if (options.specs.some((spec) => spec.endsWith("web-remote-control-session-events.test.ts")))
  115. return prepareWebRemoteControlSessionEventsFixture(options);
  116. if (options.specs.some((spec) => spec.endsWith("web-remote-control-startup-restore.test.ts")))
  117. return prepareWebRemoteControlSessionEventsFixture({
  118. ...options,
  119. // 上次在另一个项目开启远控;重启只恢复激活的 workspacePath,该项目不在窗口里。
  120. lastEnabledWorkspacePath: `${options.workspacePath}-previous`,
  121. });
  122. if (!options.specs.some((spec) => spec.endsWith("web-remote-control-auth-gate.test.ts")))
  123. return null;
  124. const evidence = { remoteHttp: 0, wsUpgrades: 0, oauthProviders: [] as string[] };
  125. const server = createServer(async (request, response) => {
  126. const path = new URL(request.url ?? "/", "http://fixture").pathname;
  127. response.setHeader("content-type", "application/json");
  128. if (path === "/__e2e/status") {
  129. response.end(JSON.stringify(evidence));
  130. return;
  131. }
  132. // 场景接口要求数组;配置对象会让草稿组件调用 find 时崩溃,遮住真正的登录门禁。
  133. if (path === "/api/v1/client/scenes") {
  134. response.end(JSON.stringify({ code: 0, data: [] }));
  135. return;
  136. }
  137. if (path.startsWith("/api/v1/remote/")) {
  138. evidence.remoteHttp += 1;
  139. response.writeHead(401);
  140. response.end('{"code":401}');
  141. return;
  142. }
  143. if (path === "/api/v1/oauth/cli/init") {
  144. const chunks: Buffer[] = [];
  145. for await (const chunk of request) chunks.push(Buffer.from(chunk));
  146. const body = JSON.parse(Buffer.concat(chunks).toString("utf8")) as { provider: string };
  147. evidence.oauthProviders.push(body.provider);
  148. response.end(
  149. JSON.stringify({
  150. code: 0,
  151. data: {
  152. authorize_url: "https://example.com/authorize?state=remote-auth-gate",
  153. expires_at: Math.floor(Date.now() / 1000) + 300,
  154. flow_id: "remote-auth-gate",
  155. poll_interval_sec: 1,
  156. },
  157. }),
  158. );
  159. return;
  160. }
  161. if (path === "/api/v1/oauth/cli/poll/remote-auth-gate") {
  162. response.end('{"code":0,"data":{"status":"pending"}}');
  163. return;
  164. }
  165. response.end(
  166. JSON.stringify({
  167. code: 0,
  168. data: { configs: {}, builtinModels: [], config_version: "auth-gate" },
  169. }),
  170. );
  171. });
  172. server.on("upgrade", (_request, socket) => {
  173. evidence.wsUpgrades += 1;
  174. socket.destroy();
  175. });
  176. server.listen(0, "127.0.0.1");
  177. await once(server, "listening");
  178. const address = server.address();
  179. if (!address || typeof address === "string") throw new Error("缺少远控门禁 fixture 端口");
  180. const baseUrl = `http://127.0.0.1:${address.port}`;
  181. const envPatch = {
  182. // 缓存账号会触发独立业务 API;必须同样隔离,避免合成凭据收到线上401并提前登出。
  183. ZAI_BUSINESS_BASE_URL: baseUrl,
  184. ZCODE_E2E_REMOTE_AUTH_GATE_URL: baseUrl,
  185. ZCODE_BASE_URL: baseUrl,
  186. ZCODE_ENDPOINT_ORIGIN: baseUrl,
  187. ZCODE_TEST_BASE_URL: baseUrl,
  188. ZCODE_WEB_REMOTE_CONTROL_RELAY_WS_URL: `${baseUrl.replace("http:", "ws:")}/api/v1/remote/ws2`,
  189. ZCODE_WEB_REMOTE_CONTROL_URL: `${baseUrl}/remote/v4`,
  190. };
  191. const previous = Object.fromEntries(Object.keys(envPatch).map((key) => [key, process.env[key]]));
  192. Object.assign(process.env, envPatch);
  193. await writeFile(options.credentialsFile, "{}", { mode: 0o600 });
  194. const settings = JSON.parse(await readFile(options.settingsFile, "utf8"));
  195. await writeFile(
  196. options.settingsFile,
  197. JSON.stringify({
  198. ...settings,
  199. zcodeEndpointOrigin: baseUrl,
  200. webRemoteControlLastEnabledContext: { workspacePath: options.workspacePath },
  201. }),
  202. );
  203. return async () => {
  204. const closed = new Promise<void>((resolve, reject) =>
  205. server.close((error) => (error ? reject(error) : resolve())),
  206. );
  207. server.closeAllConnections();
  208. await closed;
  209. for (const [key, value] of Object.entries(previous)) {
  210. if (value === undefined) delete process.env[key];
  211. else process.env[key] = value;
  212. }
  213. };
  214. }