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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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 { WebSocket } from "ws";
  5. import { acquireFileLock } from "@zcode/shared/node";
  6. import { type WebRemoteControlStatus } from "@zcode/shared";
  7. import {
  8. TID_CONFIRM_DIALOG_CONFIRM,
  9. TID_LOGIN_TRIGGER,
  10. TID_LOGOUT_BUTTON,
  11. } from "@zcode/shared/test-ids";
  12. import { getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  13. async function remoteStatus() {
  14. const serialized = await browser.execute(async () => {
  15. const bridge = (
  16. window as Window & { zcode?: { getWebRemoteControlStatus(): Promise<{ status: string }> } }
  17. ).zcode;
  18. if (!bridge) throw new Error("缺少 preload 远控接口");
  19. // WebDriver 把返回对象的 error 字段当成协议错误;序列化后再在测试端还原真实状态。
  20. return JSON.stringify(await bridge.getWebRemoteControlStatus());
  21. });
  22. return JSON.parse(serialized) as WebRemoteControlStatus;
  23. }
  24. describe("桌面 OAuth 凭据完成事件", () => {
  25. it("AUTH-08: 新设备身份保存失败终止启动并清理设备,恢复设置后可手动重启", async function () {
  26. this.timeout(120_000);
  27. const origin = process.env.ZCODE_E2E_REMOTE_AUTH_GATE_URL;
  28. const artifacts = process.env.ZCODE_E2E_ARTIFACT_DIR;
  29. if (!origin || !artifacts) throw new Error("缺少会话事件 fixture");
  30. const openDialog = async () => {
  31. await browser.waitUntil(
  32. async () => {
  33. if (await $('[data-testid="onboarding-page"]').isDisplayed())
  34. await browser.keys("Escape");
  35. for (const trigger of await $$(
  36. 'button[aria-label="Mobile remote control"], button[aria-label="移动端远程控制"]',
  37. )) {
  38. if (await trigger.isDisplayed()) {
  39. await trigger.click();
  40. return true;
  41. }
  42. }
  43. return false;
  44. },
  45. { timeout: 60_000, timeoutMsg: "未出现远控入口" },
  46. );
  47. };
  48. const devices = async () => {
  49. const response = await fetch(`${origin}/api/v1/remote/device`, {
  50. headers: { Authorization: "Bearer mock-token" },
  51. });
  52. return (await response.json()).data as Array<{ device_sid: string; online: boolean }>;
  53. };
  54. await browser.waitUntil(
  55. async () => {
  56. if (await $('[data-testid="onboarding-page"]').isDisplayed()) await browser.keys("Escape");
  57. return $(`[data-testid="${TID_LOGIN_TRIGGER}"]`).isExisting();
  58. },
  59. { timeout: 60_000 },
  60. );
  61. await browser.waitUntil(async () => (await remoteStatus()).status === "running", {
  62. timeout: 40_000,
  63. });
  64. await openDialog();
  65. const stop = $('[data-testid="web-remote-control-connection-card"] button');
  66. await stop.waitForEnabled({ timeout: 10_000 });
  67. await stop.click();
  68. await browser.waitUntil(async () => (await remoteStatus()).status === "idle");
  69. await browser.waitUntil(async () => (await devices()).every((device) => !device.online));
  70. for (const device of await devices()) {
  71. const deleted = await fetch(`${origin}/api/v1/remote/device/delete`, {
  72. method: "POST",
  73. headers: { Authorization: "Bearer mock-token", "Content-Type": "application/json" },
  74. body: JSON.stringify({ device_sid: device.device_sid }),
  75. });
  76. expect((await deleted.json()).code).toBe(0);
  77. }
  78. const before = await devices();
  79. const { appDataDir } = getE2EAppDataPaths();
  80. if (!appDataDir.includes(".e2e-home-")) throw new Error("设置写入故障必须限制在隔离 HOME");
  81. const settingsFile = join(appDataDir, "setting.json");
  82. const settingsMode = (await stat(settingsFile)).mode & 0o777;
  83. const directoryMode = (await stat(appDataDir)).mode & 0o777;
  84. try {
  85. // 保留 endpoint/旧 SID 的真实读取,只禁止设置原子写入,确保新身份保存确实失败。
  86. await chmod(settingsFile, 0o444);
  87. await chmod(appDataDir, 0o555);
  88. await openDialog();
  89. await browser.waitUntil(async () => (await remoteStatus()).status === "error", {
  90. timeout: 5000,
  91. timeoutMsg: "身份保存失败未及时终止远控启动",
  92. });
  93. await browser.waitUntil(
  94. async () =>
  95. (await $('[data-testid="web-remote-control-connection-card"]').getText()).includes(
  96. "relay-unavailable",
  97. ),
  98. { timeout: 5000 },
  99. );
  100. expect(await $('[data-testid="web-remote-control-scan-card"] img').isExisting()).toBe(false);
  101. expect(await devices()).toEqual(before);
  102. await browser.pause(2500);
  103. expect(await devices()).toEqual(before);
  104. await browser.saveScreenshot(join(artifacts, "remote-device-save-failure.png"));
  105. await writeFile(
  106. join(artifacts, "remote-device-save-failure.json"),
  107. JSON.stringify({ status: await remoteStatus(), before, after: await devices() }, null, 2),
  108. );
  109. } finally {
  110. await chmod(appDataDir, directoryMode);
  111. await chmod(settingsFile, settingsMode);
  112. await browser.keys("Escape");
  113. }
  114. await openDialog();
  115. await browser.waitUntil(async () => (await remoteStatus()).status === "running", {
  116. timeout: 10_000,
  117. timeoutMsg: "恢复设置后手动开启远控未成功",
  118. });
  119. await browser.keys("Escape");
  120. });
  121. it("AUTH-08: 登出后设置失败仍关闭已配对远控,且不依赖 UI 用户清空或重启", async function () {
  122. this.timeout(120_000);
  123. const origin = process.env.ZCODE_E2E_REMOTE_AUTH_GATE_URL;
  124. const artifacts = process.env.ZCODE_E2E_ARTIFACT_DIR;
  125. if (!origin || !artifacts) throw new Error("缺少会话事件 fixture");
  126. await browser.waitUntil(
  127. async () => {
  128. if (await $('[data-testid="onboarding-page"]').isDisplayed()) await browser.keys("Escape");
  129. return $(`[data-testid="${TID_LOGIN_TRIGGER}"]`).isExisting();
  130. },
  131. { timeout: 60_000, timeoutMsg: "启动后未进入已登录工作区" },
  132. );
  133. await browser.waitUntil(async () => (await remoteStatus()).status === "running", {
  134. timeout: 40_000,
  135. });
  136. const headers = { Authorization: "Bearer mock-token", "Content-Type": "application/json" };
  137. const devices = await (await fetch(`${origin}/api/v1/remote/device`, { headers })).json();
  138. const sid = devices.data.find((device: { online: boolean }) => device.online)?.device_sid;
  139. expect(typeof sid).toBe("string");
  140. const token = await (
  141. await fetch(`${origin}/api/v1/remote/token`, {
  142. method: "POST",
  143. headers,
  144. body: JSON.stringify({ role: "terminal" }),
  145. })
  146. ).json();
  147. const terminal = new WebSocket(
  148. `${origin.replace("http:", "ws:")}/api/v1/remote/ws2?token=${token.data.token}`,
  149. );
  150. const opened = once(terminal, "open");
  151. const messages: Array<{ type: string; pair_status?: string }> = [];
  152. terminal.on("message", (raw) => messages.push(JSON.parse(raw.toString())));
  153. const { appDataDir, credentialsFile } = getE2EAppDataPaths();
  154. const settingsFile = join(appDataDir, "setting.json");
  155. let releaseSettingsLock: (() => Promise<void>) | undefined;
  156. // E2E 日志按 worker 隔离;从 Main 获取实际目录,不能读取普通用户配置目录。
  157. const logs = await browser.electron.execute(() => process.env.ZCODE_E2E_RUNTIME_LOG_DIR);
  158. if (!logs) throw new Error("缺少 worker 运行时日志目录");
  159. const readRuntimeLog = async () => {
  160. const names = (await readdir(logs)).filter((name) => name.endsWith(".log")).sort();
  161. return (await Promise.all(names.map((name) => readFile(join(logs, name), "utf8")))).join(
  162. "\n",
  163. );
  164. };
  165. const relaunch = await browser.electron.mock("app", "relaunch");
  166. await relaunch.mockResolvedValue(undefined);
  167. const quit = await browser.electron.mock("app", "quit");
  168. await quit.mockResolvedValue(undefined);
  169. try {
  170. await opened;
  171. terminal.send(JSON.stringify({ type: "auth_init", device_sid: sid }));
  172. await browser.waitUntil(
  173. async () =>
  174. messages.some(
  175. (message) => message.type === "auth_ack" && message.pair_status === "matched",
  176. ),
  177. { timeout: 10_000 },
  178. );
  179. await $(`[data-testid="${TID_LOGIN_TRIGGER}"]`).click();
  180. await $(`[data-testid="${TID_LOGOUT_BUTTON}"]`).click();
  181. const confirm = $(`[data-testid="${TID_CONFIRM_DIALOG_CONFIRM}"]`);
  182. await confirm.waitForDisplayed();
  183. // 登出前会先读设置;把文件改成目录会在 oauth.logout 前失败,未覆盖凭据事件。
  184. // 只占用设置写锁,保留有效正文与独立凭据锁,让故障发生在凭据清理后的设置写入。
  185. const logBeforeFailure = await readRuntimeLog();
  186. releaseSettingsLock = await acquireFileLock(settingsFile, [25, 50, 100], 100, 8_000);
  187. await confirm.click();
  188. await browser.waitUntil(
  189. async () => {
  190. const credentials = JSON.parse(await readFile(credentialsFile, "utf8"));
  191. return !("zcodejwttoken" in credentials);
  192. },
  193. { timeout: 15_000 },
  194. );
  195. await browser.waitUntil(async () => (await remoteStatus()).status === "auth-required", {
  196. timeout: 10_000,
  197. });
  198. await browser.waitUntil(async () => terminal.readyState === WebSocket.CLOSED, {
  199. timeout: 10_000,
  200. });
  201. // 等待真实写入拒绝的日志,不能把“仍在等待写锁”当作失败证据就提前放锁。
  202. await browser.waitUntil(
  203. async () =>
  204. (await readRuntimeLog()).slice(logBeforeFailure.length).includes("setting.update FAIL"),
  205. { timeout: 15_000, timeoutMsg: "凭据清理后未观察到设置写锁失败" },
  206. );
  207. await relaunch.update();
  208. await quit.update();
  209. expect(relaunch.mock.calls.length).toBe(0);
  210. expect(quit.mock.calls.length).toBe(0);
  211. expect(await $(`[data-testid="${TID_LOGIN_TRIGGER}"]`).getText()).toContain("ZCode E2E");
  212. await writeFile(
  213. join(artifacts, "remote-logout-settings-failure.json"),
  214. JSON.stringify(
  215. {
  216. credentialCleared: true,
  217. settingsWriteRejected: true,
  218. status: await remoteStatus(),
  219. terminalClosed: true,
  220. relaunchCalls: relaunch.mock.calls.length,
  221. },
  222. null,
  223. 2,
  224. ),
  225. );
  226. } finally {
  227. terminal.terminate();
  228. await releaseSettingsLock?.();
  229. await browser.electron.restoreAllMocks();
  230. }
  231. });
  232. });