oauth-completion-race.test.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. import { createDecipheriv, createHash } from "node:crypto";
  2. import { readFile, readdir } from "node:fs/promises";
  3. import { join } from "node:path";
  4. import { PlatformChannels } from "@zcode/shared";
  5. import {
  6. TID_OAUTH_LOGIN_BUTTON,
  7. TID_OAUTH_ERROR,
  8. TID_OAUTH_CANCEL,
  9. TID_OAUTH_COPY_LOGIN_LINK,
  10. TID_LOGIN_TRIGGER,
  11. TID_LOGIN_MENU_ITEM,
  12. } from "@zcode/shared/test-ids";
  13. import {
  14. clearAppData,
  15. clickTestIdByDom,
  16. getE2EAppDataPaths,
  17. waitForTestIdByDom,
  18. } from "#e2e/helpers/desktop-app";
  19. describe("OAuth 双路径完成竞态", () => {
  20. after(async () => {
  21. await browser.electron.restoreAllMocks();
  22. await clearAppData();
  23. });
  24. it("AUTH-07: 浏览器唤起兑换失败后使用已到达的 polling 结果,保留归因", async function () {
  25. this.timeout(120_000);
  26. const baseUrl = process.env.ZCODE_E2E_OAUTH_RACE_URL;
  27. if (!baseUrl) throw new Error("缺少 OAuth race HTTP fixture");
  28. const openExternal = await browser.electron.mock("shell", "openExternal");
  29. await openExternal.mockResolvedValue(undefined);
  30. await browser.waitUntil(
  31. async () =>
  32. browser.execute(
  33. (button, trigger) =>
  34. Boolean(
  35. document.querySelector(
  36. `[data-testid="${button}"], [data-testid="${trigger}"], [data-testid="onboarding-page"]`,
  37. ),
  38. ),
  39. TID_OAUTH_LOGIN_BUTTON,
  40. TID_LOGIN_TRIGGER,
  41. ),
  42. { timeout: 60_000 },
  43. );
  44. // 新用户引导覆盖登录面板,使用正常 Escape 交互关闭,不修改产品状态。
  45. await browser.keys("Escape");
  46. const hasButton = await browser.execute(
  47. (id) => Boolean(document.querySelector(`[data-testid="${id}"]`)),
  48. TID_OAUTH_LOGIN_BUTTON,
  49. );
  50. if (!hasButton) {
  51. // Radix 菜单依赖 pointerdown;原生 WebDriver click 会派发完整指针事件。
  52. const triggers = await browser.$$(`[data-testid="${TID_LOGIN_TRIGGER}"]`);
  53. for (const trigger of triggers) {
  54. if (await trigger.isDisplayed()) {
  55. await trigger.click();
  56. break;
  57. }
  58. }
  59. await clickTestIdByDom(TID_LOGIN_MENU_ITEM);
  60. }
  61. await waitForTestIdByDom(TID_OAUTH_LOGIN_BUTTON);
  62. const originalProvider = (await readCredentials())["oauth:active_provider"];
  63. await clickTestIdByDom(TID_OAUTH_LOGIN_BUTTON);
  64. await browser.waitUntil(
  65. async () => {
  66. await openExternal.update();
  67. return openExternal.mock.calls.length > 0;
  68. },
  69. {
  70. timeout: 20_000,
  71. },
  72. );
  73. const authorizationUrl = openExternal.mock.calls[0]?.[0];
  74. expect(authorizationUrl).toContain(
  75. "https://example.com/authorize?state=e2e-race&channel_id=desktop-launch",
  76. );
  77. await clickTestIdByDom(TID_OAUTH_COPY_LOGIN_LINK);
  78. await browser.waitUntil(
  79. async () =>
  80. (await browser.electron.execute((electron) => electron.clipboard.readText())) ===
  81. authorizationUrl,
  82. { timeout: 10_000, timeoutMsg: "等待态复制登录链接失败" },
  83. );
  84. // 先验证兑换等待期间取消:Host 返回 null,Root 不应把正常取消当作失败或登录成功。
  85. await browser.electron.execute((electron, channel) => {
  86. electron.BrowserWindow.getAllWindows()[0]!.webContents.send(
  87. channel,
  88. "zcode://oauth/callback?state=e2e-race&authCode=cancelled",
  89. );
  90. }, PlatformChannels.OAuthCallback);
  91. await browser.waitUntil(
  92. async () => {
  93. const status = (await (await fetch(`${baseUrl}/__e2e/status`)).json()) as {
  94. tokenRequests: number;
  95. };
  96. return status.tokenRequests === 1;
  97. },
  98. { timeout: 20_000 },
  99. );
  100. await clickTestIdByDom(TID_OAUTH_CANCEL);
  101. await waitForTestIdByDom(TID_OAUTH_LOGIN_BUTTON);
  102. await fetch(`${baseUrl}/__e2e/complete-token`, { method: "POST" });
  103. // 等待真实 RPC 回调完成后再发起下一次登录,避免新登录掩盖取消的 UI 结果。
  104. const logDir = await browser.electron.execute(() => process.env.ZCODE_E2E_RUNTIME_LOG_DIR);
  105. if (!logDir) throw new Error("缺少 E2E 日志目录");
  106. await browser.waitUntil(
  107. async () => {
  108. const files = (await readdir(logDir)).filter((file) => file.endsWith(".log"));
  109. const logs = await Promise.all(files.map((file) => readFile(join(logDir, file), "utf8")));
  110. return logs.some((log) => log.includes("oauth.handleCallback OK"));
  111. },
  112. { timeout: 10_000 },
  113. );
  114. await browser.executeAsync((done) => {
  115. requestAnimationFrame(() => requestAnimationFrame(() => done()));
  116. });
  117. const cancelledCredentials = await readCredentials();
  118. expect(cancelledCredentials["oauth:active_provider"]).toBe(originalProvider);
  119. expect(cancelledCredentials["oauth:bigmodel:access_token"]).toBeUndefined();
  120. expect(await browser.$(`[data-testid="${TID_OAUTH_ERROR}"]`).isExisting()).toBe(false);
  121. await fetch(`${baseUrl}/__e2e/enable-poll`, { method: "POST" });
  122. await clickTestIdByDom(TID_OAUTH_LOGIN_BUTTON);
  123. await browser.waitUntil(
  124. async () => {
  125. await openExternal.update();
  126. return openExternal.mock.calls.length > 1;
  127. },
  128. { timeout: 20_000 },
  129. );
  130. // 真实 preload → Root → Host;只有浏览器外部打开被拦截,登录服务不 mock。
  131. await browser.electron.execute((electron, channel) => {
  132. electron.BrowserWindow.getAllWindows()[0]!.webContents.send(
  133. channel,
  134. "zcode://oauth/callback?state=e2e-race&authCode=e2e-code&channel_id=desktop&utm_source=website&utm_campaign=race",
  135. );
  136. }, PlatformChannels.OAuthCallback);
  137. await browser.waitUntil(
  138. async () => {
  139. const status = (await (await fetch(`${baseUrl}/__e2e/status`)).json()) as {
  140. readyResponses: number;
  141. };
  142. return status.readyResponses > 0;
  143. },
  144. { timeout: 20_000, timeoutMsg: "兑换挂起期间没有收到 polling ready" },
  145. );
  146. await fetch(`${baseUrl}/__e2e/fail-token`, { method: "POST" });
  147. await browser.waitUntil(
  148. async () => (await readCredentials())["oauth:active_provider"] === "bigmodel",
  149. { timeout: 20_000, timeoutMsg: "回调失败导致 polling 登录未完成" },
  150. );
  151. await browser.waitUntil(
  152. async () =>
  153. browser.execute(
  154. (id) => !document.querySelector(`[data-testid="${id}"]`),
  155. TID_OAUTH_LOGIN_BUTTON,
  156. ),
  157. { timeout: 20_000, timeoutMsg: "登录成功后未离开登录面板" },
  158. );
  159. expect(
  160. await browser.execute(
  161. (id) => Boolean(document.querySelector(`[data-testid="${id}"]`)),
  162. TID_OAUTH_ERROR,
  163. TID_OAUTH_CANCEL,
  164. ),
  165. ).toBe(false);
  166. const credentials = await readCredentials();
  167. expect(credentials["oauth:bigmodel:access_token"]).toBe("e2e-race-business");
  168. expect(JSON.parse(credentials["oauth:login_attribution"]!)).toEqual({
  169. channel_id: "desktop",
  170. utm_source: "website",
  171. utm_campaign: "race",
  172. });
  173. // polling 已成功后,迟到回调只更新归因,不能再次兑换授权码。
  174. await browser.electron.execute((electron, channel) => {
  175. electron.BrowserWindow.getAllWindows()[0]!.webContents.send(
  176. channel,
  177. "zcode://oauth/callback?state=e2e-race&authCode=late&channel_id=desktop&utm_source=website&utm_campaign=late",
  178. );
  179. }, PlatformChannels.OAuthCallback);
  180. await browser.waitUntil(
  181. async () =>
  182. JSON.parse((await readCredentials())["oauth:login_attribution"] ?? "{}").utm_campaign ===
  183. "late",
  184. { timeout: 10_000 },
  185. );
  186. const status = (await (await fetch(`${baseUrl}/__e2e/status`)).json()) as {
  187. tokenRequests: number;
  188. };
  189. expect(status.tokenRequests).toBe(1);
  190. });
  191. });
  192. async function readCredentials(): Promise<Record<string, string>> {
  193. const stored = JSON.parse(await readFile(getE2EAppDataPaths().credentialsFile, "utf8")) as Record<
  194. string,
  195. string
  196. >;
  197. // Host 正常加密落盘;这里只用 case 专属合成密钥读取隔离目录,不能把密文当登录值断言。
  198. const key = createHash("sha256").update("oauth-completion-race-fixture").digest();
  199. return Object.fromEntries(
  200. Object.entries(stored).map(([name, value]) => {
  201. if (!value.startsWith("enc:v1:")) return [name, value];
  202. const [iv, tag, data] = value.slice("enc:v1:".length).split(".");
  203. const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(iv!, "base64url"));
  204. decipher.setAuthTag(Buffer.from(tag!, "base64url"));
  205. return [
  206. name,
  207. Buffer.concat([
  208. decipher.update(Buffer.from(data!, "base64url")),
  209. decipher.final(),
  210. ]).toString("utf8"),
  211. ];
  212. }),
  213. );
  214. }