web-remote-control-session-events.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. import { chmod, readFile, readdir, stat, writeFile } from "node:fs/promises";
  2. import { once } from "node:events";
  3. import { join } from "node:path";
  4. import { isIsolatedE2EHomeDir } from "#e2e/helpers/e2e-runtime-paths";
  5. import { WebSocket } from "ws";
  6. import { acquireFileLock } from "@zcode/shared/node";
  7. import { type WebRemoteControlStatus } from "@zcode/shared";
  8. import {
  9. TID_CONFIRM_DIALOG_CONFIRM,
  10. TID_LOGIN_TRIGGER,
  11. TID_LOGOUT_BUTTON,
  12. } from "@zcode/shared/test-ids";
  13. import {
  14. DEFAULT_WORKSPACE,
  15. seedSettings,
  16. getE2EAppDataPaths,
  17. waitForTestIdByDom,
  18. } from "#e2e/helpers/desktop-app";
  19. async function remoteStatus() {
  20. const serialized = await browser.execute(async () => {
  21. const bridge = (
  22. window as Window & { zcode?: { getWebRemoteControlStatus(): Promise<{ status: string }> } }
  23. ).zcode;
  24. if (!bridge) throw new Error("缺少 preload 远控接口");
  25. // WebDriver 把返回对象的 error 字段当成协议错误;序列化后再在测试端还原真实状态。
  26. return JSON.stringify(await bridge.getWebRemoteControlStatus());
  27. });
  28. return JSON.parse(serialized) as WebRemoteControlStatus;
  29. }
  30. describe("桌面 OAuth 凭据完成事件", () => {
  31. it("AUTH-08: 新设备身份保存失败终止启动并清理设备,恢复设置后可手动重启", async function () {
  32. this.timeout(120_000);
  33. const origin = process.env.ZCODE_E2E_REMOTE_AUTH_GATE_URL;
  34. const artifacts = process.env.ZCODE_E2E_ARTIFACT_DIR;
  35. if (!origin || !artifacts) throw new Error("缺少会话事件 fixture");
  36. const openDialog = async () => {
  37. await browser.waitUntil(
  38. async () => {
  39. if (await $('[data-testid="onboarding-page"]').isDisplayed())
  40. await browser.keys("Escape");
  41. for (const trigger of await $$(
  42. 'button[aria-label="Mobile remote control"], button[aria-label="移动端远程控制"]',
  43. )) {
  44. if (await trigger.isDisplayed()) {
  45. await trigger.click();
  46. return true;
  47. }
  48. }
  49. return false;
  50. },
  51. { timeout: 60_000, timeoutMsg: "未出现远控入口" },
  52. );
  53. };
  54. const devices = async () => {
  55. const response = await fetch(`${origin}/api/v1/remote/device`, {
  56. headers: { Authorization: "Bearer mock-token" },
  57. });
  58. return (await response.json()).data as Array<{ device_sid: string; online: boolean }>;
  59. };
  60. await browser.waitUntil(
  61. async () => {
  62. if (await $('[data-testid="onboarding-page"]').isDisplayed()) await browser.keys("Escape");
  63. return $(`[data-testid="${TID_LOGIN_TRIGGER}"]`).isExisting();
  64. },
  65. { timeout: 60_000 },
  66. );
  67. await browser.waitUntil(async () => (await remoteStatus()).status === "running", {
  68. timeout: 40_000,
  69. });
  70. await openDialog();
  71. const stop = $('[data-testid="web-remote-control-connection-card"] button');
  72. await stop.waitForEnabled({ timeout: 10_000 });
  73. await stop.click();
  74. await browser.waitUntil(async () => (await remoteStatus()).status === "idle");
  75. await browser.waitUntil(async () => (await devices()).every((device) => !device.online));
  76. for (const device of await devices()) {
  77. const deleted = await fetch(`${origin}/api/v1/remote/device/delete`, {
  78. method: "POST",
  79. headers: { Authorization: "Bearer mock-token", "Content-Type": "application/json" },
  80. body: JSON.stringify({ device_sid: device.device_sid }),
  81. });
  82. expect((await deleted.json()).code).toBe(0);
  83. }
  84. const before = await devices();
  85. const { appDataDir } = getE2EAppDataPaths();
  86. // 修复原因:子串 `.e2e-home-` 拒绝 Windows CI 默认的 `.e2e-home`,又会放行 `.e2e-home-` 开头的误配目录;
  87. // 改为按路径段判断,与共享隔离 HOME 守卫一致。
  88. if (!isIsolatedE2EHomeDir(appDataDir)) throw new Error("设置写入故障必须限制在隔离 HOME");
  89. const settingsFile = join(appDataDir, "setting.json");
  90. const settingsMode = (await stat(settingsFile)).mode & 0o777;
  91. const directoryMode = (await stat(appDataDir)).mode & 0o777;
  92. try {
  93. // 保留 endpoint/旧 SID 的真实读取,只禁止设置原子写入,确保新身份保存确实失败。
  94. await chmod(settingsFile, 0o444);
  95. await chmod(appDataDir, 0o555);
  96. await openDialog();
  97. await browser.waitUntil(async () => (await remoteStatus()).status === "error", {
  98. timeout: 5000,
  99. timeoutMsg: "身份保存失败未及时终止远控启动",
  100. });
  101. await browser.waitUntil(
  102. async () =>
  103. (await $('[data-testid="web-remote-control-connection-card"]').getText()).includes(
  104. "relay-unavailable",
  105. ),
  106. { timeout: 5000 },
  107. );
  108. expect(await $('[data-testid="web-remote-control-scan-card"] img').isExisting()).toBe(false);
  109. expect(await devices()).toEqual(before);
  110. await browser.pause(2500);
  111. expect(await devices()).toEqual(before);
  112. await browser.saveScreenshot(join(artifacts, "remote-device-save-failure.png"));
  113. await writeFile(
  114. join(artifacts, "remote-device-save-failure.json"),
  115. JSON.stringify({ status: await remoteStatus(), before, after: await devices() }, null, 2),
  116. );
  117. } finally {
  118. await chmod(appDataDir, directoryMode);
  119. await chmod(settingsFile, settingsMode);
  120. await browser.keys("Escape");
  121. }
  122. await openDialog();
  123. await browser.waitUntil(async () => (await remoteStatus()).status === "running", {
  124. timeout: 10_000,
  125. timeoutMsg: "恢复设置后手动开启远控未成功",
  126. });
  127. await browser.keys("Escape");
  128. });
  129. it("AUTH-08: 登出后设置失败仍关闭已配对远控,且不依赖 UI 用户清空或重启", async function () {
  130. this.timeout(120_000);
  131. const origin = process.env.ZCODE_E2E_REMOTE_AUTH_GATE_URL;
  132. const artifacts = process.env.ZCODE_E2E_ARTIFACT_DIR;
  133. if (!origin || !artifacts) throw new Error("缺少会话事件 fixture");
  134. await browser.waitUntil(
  135. async () => {
  136. if (await $('[data-testid="onboarding-page"]').isDisplayed()) await browser.keys("Escape");
  137. return $(`[data-testid="${TID_LOGIN_TRIGGER}"]`).isExisting();
  138. },
  139. { timeout: 60_000, timeoutMsg: "启动后未进入已登录工作区" },
  140. );
  141. await browser.waitUntil(async () => (await remoteStatus()).status === "running", {
  142. timeout: 40_000,
  143. });
  144. const headers = { Authorization: "Bearer mock-token", "Content-Type": "application/json" };
  145. const devices = await (await fetch(`${origin}/api/v1/remote/device`, { headers })).json();
  146. const sid = devices.data.find((device: { online: boolean }) => device.online)?.device_sid;
  147. expect(typeof sid).toBe("string");
  148. const token = await (
  149. await fetch(`${origin}/api/v1/remote/token`, {
  150. method: "POST",
  151. headers,
  152. body: JSON.stringify({ role: "terminal" }),
  153. })
  154. ).json();
  155. const terminal = new WebSocket(
  156. `${origin.replace("http:", "ws:")}/api/v1/remote/ws2?token=${token.data.token}`,
  157. );
  158. const opened = once(terminal, "open");
  159. const messages: Array<{ type: string; pair_status?: string }> = [];
  160. terminal.on("message", (raw) => messages.push(JSON.parse(raw.toString())));
  161. const { appDataDir, credentialsFile } = getE2EAppDataPaths();
  162. const settingsFile = join(appDataDir, "setting.json");
  163. let releaseSettingsLock: (() => Promise<void>) | undefined;
  164. // E2E 日志按 worker 隔离;从 Main 获取实际目录,不能读取普通用户配置目录。
  165. const logs = await browser.electron.execute(() => process.env.ZCODE_E2E_RUNTIME_LOG_DIR);
  166. if (!logs) throw new Error("缺少 worker 运行时日志目录");
  167. const readRuntimeLog = async () => {
  168. const names = (await readdir(logs)).filter((name) => name.endsWith(".log")).sort();
  169. return (await Promise.all(names.map((name) => readFile(join(logs, name), "utf8")))).join(
  170. "\n",
  171. );
  172. };
  173. const relaunch = await browser.electron.mock("app", "relaunch");
  174. await relaunch.mockResolvedValue(undefined);
  175. const quit = await browser.electron.mock("app", "quit");
  176. await quit.mockResolvedValue(undefined);
  177. try {
  178. await opened;
  179. terminal.send(JSON.stringify({ type: "auth_init", device_sid: sid }));
  180. await browser.waitUntil(
  181. async () =>
  182. messages.some(
  183. (message) => message.type === "auth_ack" && message.pair_status === "matched",
  184. ),
  185. { timeout: 10_000 },
  186. );
  187. await $(`[data-testid="${TID_LOGIN_TRIGGER}"]`).click();
  188. await $(`[data-testid="${TID_LOGOUT_BUTTON}"]`).click();
  189. const confirm = $(`[data-testid="${TID_CONFIRM_DIALOG_CONFIRM}"]`);
  190. await confirm.waitForDisplayed();
  191. // 登出前会先读设置;把文件改成目录会在 oauth.logout 前失败,未覆盖凭据事件。
  192. // 只占用设置写锁,保留有效正文与独立凭据锁,让故障发生在凭据清理后的设置写入。
  193. const logBeforeFailure = await readRuntimeLog();
  194. releaseSettingsLock = await acquireFileLock(settingsFile, [25, 50, 100], 100, 8_000);
  195. await confirm.click();
  196. await browser.waitUntil(
  197. async () => {
  198. const credentials = JSON.parse(await readFile(credentialsFile, "utf8"));
  199. return !("zcodejwttoken" in credentials);
  200. },
  201. { timeout: 15_000 },
  202. );
  203. await browser.waitUntil(async () => (await remoteStatus()).status === "auth-required", {
  204. timeout: 10_000,
  205. });
  206. await browser.waitUntil(async () => terminal.readyState === WebSocket.CLOSED, {
  207. timeout: 10_000,
  208. });
  209. // 等待真实写入拒绝的日志,不能把“仍在等待写锁”当作失败证据就提前放锁。
  210. await browser.waitUntil(
  211. async () =>
  212. (await readRuntimeLog()).slice(logBeforeFailure.length).includes("setting.update FAIL"),
  213. { timeout: 15_000, timeoutMsg: "凭据清理后未观察到设置写锁失败" },
  214. );
  215. await relaunch.update();
  216. await quit.update();
  217. expect(relaunch.mock.calls.length).toBe(0);
  218. expect(quit.mock.calls.length).toBe(0);
  219. expect(await $(`[data-testid="${TID_LOGIN_TRIGGER}"]`).getText()).toContain("ZCode E2E");
  220. await writeFile(
  221. join(artifacts, "remote-logout-settings-failure.json"),
  222. JSON.stringify(
  223. {
  224. credentialCleared: true,
  225. settingsWriteRejected: true,
  226. status: await remoteStatus(),
  227. terminalClosed: true,
  228. relaunchCalls: relaunch.mock.calls.length,
  229. },
  230. null,
  231. 2,
  232. ),
  233. );
  234. } finally {
  235. terminal.terminate();
  236. await releaseSettingsLock?.();
  237. await browser.electron.restoreAllMocks();
  238. }
  239. });
  240. it("AUTH-CN-REMOTE: 中国区主身份可配对,补关联不断开,退出关闭连接", async function () {
  241. this.timeout(90_000);
  242. const origin = process.env.ZCODE_E2E_REMOTE_AUTH_GATE_URL;
  243. if (!origin) throw new Error("缺少会话事件 fixture");
  244. const { credentialsFile } = getE2EAppDataPaths();
  245. await writeFile(
  246. credentialsFile,
  247. JSON.stringify({
  248. "oauth:active_provider": "zai_cn",
  249. "oauth:session_revision": "cn-remote-before-profile",
  250. "oauth:zai_cn:access_token": "cn-upstream-not-relay",
  251. "oauth:zai_cn:user_info": JSON.stringify({
  252. user_id: "zcode-e2e-user",
  253. name: "ZCode E2E",
  254. }),
  255. "oauth:linked_bigmodel": JSON.stringify({
  256. userId: "zcode-e2e-user",
  257. customerId: "associated-customer",
  258. accessToken: "linked-before",
  259. }),
  260. zcodejwttoken: "mock-token",
  261. }),
  262. "utf8",
  263. );
  264. await seedSettings({
  265. webRemoteControlLastEnabledContext: { workspacePath: DEFAULT_WORKSPACE },
  266. });
  267. await browser.reloadSession();
  268. await browser.waitUntil(async () => (await remoteStatus()).status === "running", {
  269. timeout: 15_000,
  270. timeoutMsg: "中国区主身份没有启动远控",
  271. });
  272. const headers = { Authorization: "Bearer mock-token", "Content-Type": "application/json" };
  273. const devices = async () =>
  274. (await (await fetch(`${origin}/api/v1/remote/device`, { headers })).json()).data as Array<{
  275. device_sid: string;
  276. online: boolean;
  277. }>;
  278. const sid = (await devices()).find((device) => device.online)?.device_sid;
  279. expect(typeof sid).toBe("string");
  280. const issued = await (
  281. await fetch(`${origin}/api/v1/remote/token`, {
  282. method: "POST",
  283. headers,
  284. body: JSON.stringify({ role: "terminal" }),
  285. })
  286. ).json();
  287. const terminal = new WebSocket(
  288. `${origin.replace("http:", "ws:")}/api/v1/remote/ws2?token=${issued.data.token}`,
  289. );
  290. const messages: Array<{ type: string; pair_status?: string }> = [];
  291. terminal.on("message", (raw) => messages.push(JSON.parse(raw.toString())));
  292. try {
  293. await once(terminal, "open");
  294. terminal.send(JSON.stringify({ type: "auth_init", device_sid: sid }));
  295. await browser.waitUntil(
  296. async () =>
  297. messages.some(
  298. (message) => message.type === "auth_ack" && message.pair_status === "matched",
  299. ),
  300. { timeout: 10_000 },
  301. );
  302. await browser.waitUntil(async () => (await remoteStatus()).status === "active", {
  303. timeout: 10_000,
  304. });
  305. await waitForTestIdByDom(TID_LOGIN_TRIGGER);
  306. await browser.execute((id) => {
  307. const element = document.querySelector(`[data-testid="${id}"]`)!;
  308. let fiber = (element as any)[
  309. Object.keys(element).find((key) => key.startsWith("__reactFiber"))!
  310. ];
  311. while (fiber) {
  312. const value = fiber.memoizedProps?.value;
  313. const services = value?.oauthService ? value : fiber.memoizedProps?.services;
  314. if (services?.oauthService) {
  315. (window as any).__cnRemoteServices = services;
  316. return;
  317. }
  318. fiber = fiber.return;
  319. }
  320. throw new Error("Missing OAuth accessor");
  321. }, TID_LOGIN_TRIGGER);
  322. await fetch(`${origin}/__e2e/linked-profile`, { method: "POST" });
  323. const availability = await browser.execute(async () =>
  324. (window as any).__cnRemoteServices.oauthService.refreshAccountProfile(),
  325. );
  326. expect(availability.loginProvider).toBe("zai_cn");
  327. expect(availability.sessionRevision).not.toBe("cn-remote-before-profile");
  328. expect((await remoteStatus()).status).toBe("active");
  329. expect(terminal.readyState).toBe(WebSocket.OPEN);
  330. expect((await devices()).find((device) => device.online)?.device_sid).toBe(sid);
  331. await browser.execute(async () =>
  332. (window as any).__cnRemoteServices.oauthService.logoutAll(),
  333. );
  334. await browser.waitUntil(async () => (await remoteStatus()).status === "auth-required", {
  335. timeout: 10_000,
  336. });
  337. await browser.waitUntil(async () => terminal.readyState === WebSocket.CLOSED, {
  338. timeout: 10_000,
  339. });
  340. } finally {
  341. terminal.terminate();
  342. await browser.execute(() => {
  343. delete (window as any).__cnRemoteServices;
  344. });
  345. }
  346. });
  347. });