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

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