access-token-401-auto-logout.test.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. import { readE2ECredentialValue } from "#e2e/helpers/desktop-app";
  2. import { readFile } from "node:fs/promises";
  3. import { PlatformChannels } from "@zcode/shared";
  4. import {
  5. TID_OAUTH_LOGIN_BUTTON,
  6. TID_LOGIN_USE_API_KEY_BUTTON,
  7. TID_WORKSPACE_HEADER,
  8. } from "@zcode/shared/test-ids";
  9. import { clearAppData, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  10. import { dismissOccupationOnboarding } from "#e2e/helpers/occupation-onboarding";
  11. const responseStatus = process.env.ZCODE_E2E_AUTH_EXPIRY_HTTP_STATUS === "200" ? 200 : 401;
  12. const emptyRejection = process.env.ZCODE_E2E_AUTH_EXPIRY_RESPONSE_KIND === "empty";
  13. const provider = process.env.ZCODE_E2E_AUTH_EXPIRY_PROVIDER === "zai" ? "zai" : "bigmodel";
  14. const preserveSession = process.env.ZCODE_E2E_AUTH_VALIDATION_HEADER === "1";
  15. describe("用户资料 access token 登录过期", () => {
  16. after(async () => {
  17. await browser.electron.restoreAllMocks();
  18. await clearAppData();
  19. });
  20. it(`AUTH-06: ${preserveSession ? "ZAI 有效身份遇到业务异常仍保留登录" : `${provider} HTTP ${responseStatus} ${emptyRejection ? "空正文" : "业务401"} 后清理并进入登录入口`}`, async () => {
  21. const baseUrl = process.env.ZCODE_E2E_ACCESS_TOKEN_401_URL;
  22. if (!baseUrl) throw new Error("缺少隔离 userinfo HTTP fixture");
  23. if (preserveSession) {
  24. await browser.waitUntil(
  25. async () => {
  26. const status = (await (await fetch(`${baseUrl}/__e2e/status`)).json()) as {
  27. ordinaryBusinessRequestCount: number;
  28. rawIdentityRequestCount: number;
  29. rejectedIdentityHeaderCount: number;
  30. };
  31. return (
  32. status.rejectedIdentityHeaderCount > 0 ||
  33. (status.ordinaryBusinessRequestCount > 0 && status.rawIdentityRequestCount > 0)
  34. );
  35. },
  36. { timeout: 30_000, timeoutMsg: "Host 没有完成异常业务请求与裸 token 身份核验" },
  37. );
  38. await dismissOccupationOnboarding();
  39. // 等待启动进入工作区,避免只观察首次核验、漏掉后续 PAT 资料读取造成的误退出。
  40. await browser
  41. .$(`[data-testid="${TID_WORKSPACE_HEADER}"]`)
  42. .waitForDisplayed({ timeout: 10_000 });
  43. const status = (await (await fetch(`${baseUrl}/__e2e/status`)).json()) as {
  44. rejectedIdentityHeaderCount: number;
  45. };
  46. expect(status.rejectedIdentityHeaderCount).toBe(0);
  47. const credentials = await readCredentials();
  48. expect(await readE2ECredentialValue("oauth:active_provider")).toBe("zai");
  49. for (const key of ["oauth:zai:access_token", "oauth:zai:user_info", "zcodejwttoken"])
  50. expect(credentials[key]).toBeDefined();
  51. expect(await readE2ECredentialValue("bot:e2e:credential")).toBe("e2e-independent-bot-token");
  52. expect(await expiredAlertCount()).toBe(0);
  53. return;
  54. }
  55. await browser.waitUntil(
  56. async () => {
  57. const response = await fetch(`${baseUrl}/__e2e/status`);
  58. const status = (await response.json()) as { businessRequestCount: number };
  59. return status.businessRequestCount > 0;
  60. },
  61. { timeout: 30_000, timeoutMsg: "Host 没有使用业务 access token 请求 userinfo" },
  62. );
  63. expect(await readE2ECredentialValue("oauth:active_provider")).toBe(provider);
  64. expect(await expiredAlertCount()).toBe(0);
  65. await fetch(
  66. `${baseUrl}/__e2e/reject?status=${responseStatus}&empty=${emptyRejection ? "1" : "0"}`,
  67. { method: "POST" },
  68. );
  69. const fixtureStatus = (await (await fetch(`${baseUrl}/__e2e/status`)).json()) as {
  70. rejectionStatus: number;
  71. rejected: boolean;
  72. };
  73. expect(fixtureStatus.rejectionStatus).toBe(responseStatus);
  74. expect(fixtureStatus.rejected).toBe(true);
  75. await browser.waitUntil(async () => (await expiredAlertCount()) === 1, {
  76. timeout: 30_000,
  77. timeoutMsg: `业务 access token HTTP ${responseStatus} + 业务 401 后没有出现原登录过期弹窗`,
  78. });
  79. await browser.waitUntil(
  80. async () => {
  81. const credentials = await readCredentials();
  82. return [
  83. "oauth:active_provider",
  84. `oauth:${provider}:access_token`,
  85. `oauth:${provider}:refresh_token`,
  86. `oauth:${provider}:user_info`,
  87. "zcodejwttoken",
  88. ].every((key) => !(key in credentials));
  89. },
  90. { timeout: 10_000, timeoutMsg: "弹窗确认前没有完成原 OAuth 清理" },
  91. );
  92. expect(await readE2ECredentialValue("bot:e2e:credential")).toBe("e2e-independent-bot-token");
  93. // 修复后应直接重新登录;记录 IPC 确认不会绕回旧的重启流程。
  94. await browser.electron.execute((electron, channel) => {
  95. const state = globalThis as typeof globalThis & { __oauth401Commands?: string[] };
  96. state.__oauth401Commands = [];
  97. electron.ipcMain.removeHandler(channel);
  98. electron.ipcMain.handle(channel, (_event, command: string) => {
  99. state.__oauth401Commands?.push(command);
  100. });
  101. }, PlatformChannels.ExecuteDesktopCommand);
  102. await browser.execute(() => {
  103. const button = document.querySelector<HTMLButtonElement>(
  104. '[data-slot="alert-dialog-content"] button',
  105. );
  106. if (!button) throw new Error("缺少登录过期确认按钮");
  107. button.click();
  108. });
  109. await browser.waitUntil(
  110. async () =>
  111. browser.execute(
  112. (ids) =>
  113. ids.some((id) => {
  114. const element = document.querySelector<HTMLElement>(`[data-testid="${id}"]`);
  115. return element !== null && element.getBoundingClientRect().height > 0;
  116. }),
  117. [TID_OAUTH_LOGIN_BUTTON, TID_LOGIN_USE_API_KEY_BUTTON],
  118. ),
  119. { timeout: 10_000, timeoutMsg: "确认后没有进入 Welcome 登录入口" },
  120. );
  121. const commands = await browser.electron.execute(
  122. () =>
  123. (globalThis as typeof globalThis & { __oauth401Commands?: string[] }).__oauth401Commands ??
  124. [],
  125. );
  126. expect(commands).toEqual([]);
  127. });
  128. });
  129. async function readCredentials(): Promise<Record<string, string>> {
  130. return JSON.parse(await readFile(getE2EAppDataPaths().credentialsFile, "utf8"));
  131. }
  132. async function expiredAlertCount(): Promise<number> {
  133. return browser.execute(
  134. () =>
  135. Array.from(document.querySelectorAll('[data-slot="alert-dialog-title"]')).filter((element) =>
  136. /登录已过期|Your session has expired/u.test(element.textContent ?? ""),
  137. ).length,
  138. );
  139. }