jwt-401-auto-logout.test.ts 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import { readE2ECredentialValue } from "#e2e/helpers/desktop-app";
  2. import { readFile } from "node:fs/promises";
  3. import { TID_OAUTH_LOGIN_BUTTON, TID_LOGIN_USE_API_KEY_BUTTON } from "@zcode/shared/test-ids";
  4. import { clearAppData, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  5. const OAUTH_CREDENTIAL_KEYS = [
  6. "oauth:active_provider",
  7. "oauth:zai:access_token",
  8. "oauth:zai:user_info",
  9. "zcodejwttoken",
  10. ] as const;
  11. describe("ZCode JWT 401 自动退出", () => {
  12. after(async () => {
  13. await browser.electron.restoreAllMocks();
  14. await clearAppData();
  15. });
  16. it("运行中共享 JWT 收到普通 401 后清理凭据并进入登录入口", async function () {
  17. this.timeout(120_000);
  18. const baseUrl = process.env.ZCODE_E2E_ACCESS_TOKEN_401_URL;
  19. if (!baseUrl) throw new Error("缺少隔离共享 JWT HTTP fixture");
  20. // 旧用例 mock main net.fetch,不能证明 Host transport。先确认真实 Host 使用共享 JWT。
  21. await browser.waitUntil(
  22. async () => {
  23. const status = (await (await fetch(`${baseUrl}/__e2e/status`)).json()) as {
  24. businessRequestCount: number;
  25. };
  26. return status.businessRequestCount > 0;
  27. },
  28. { timeout: 30000, timeoutMsg: "Host 没有使用共享 JWT 请求余额接口" },
  29. );
  30. const relaunchMock = await browser.electron.mock("app", "relaunch");
  31. await relaunchMock.mockResolvedValue(undefined);
  32. const quitMock = await browser.electron.mock("app", "quit");
  33. await quitMock.mockResolvedValue(undefined);
  34. await fetch(`${baseUrl}/__e2e/reject?status=401`, { method: "POST" });
  35. await waitForExpiredLoginAlert();
  36. await waitForOAuthCredentialsCleanup();
  37. await clickExpiredLoginAlertAction();
  38. await browser.waitUntil(
  39. async () =>
  40. browser.execute(
  41. (ids) =>
  42. ids.some((id) => {
  43. const element = document.querySelector<HTMLElement>(`[data-testid="${id}"]`);
  44. return element !== null && element.getBoundingClientRect().height > 0;
  45. }),
  46. [TID_OAUTH_LOGIN_BUTTON, TID_LOGIN_USE_API_KEY_BUTTON],
  47. ),
  48. { timeout: 10000, timeoutMsg: "确认后没有进入 Welcome 登录入口" },
  49. );
  50. expect(relaunchMock.mock.calls).toHaveLength(0);
  51. expect(quitMock.mock.calls).toHaveLength(0);
  52. expect(await readE2ECredentialValue("bot:e2e:credential")).toBe("e2e-independent-bot-token");
  53. });
  54. });
  55. async function waitForExpiredLoginAlert(): Promise<void> {
  56. await browser.waitUntil(
  57. async () =>
  58. (await browser.execute(() => {
  59. const content = document.querySelector<HTMLElement>('[data-slot="alert-dialog-content"]');
  60. return /登录已过期|Your session has expired/u.test(
  61. content?.querySelector<HTMLElement>('[data-slot="alert-dialog-title"]')?.textContent ??
  62. "",
  63. );
  64. })) as boolean,
  65. {
  66. timeout: 30000,
  67. timeoutMsg: "运行中收到 401 后没有出现登录失效提示",
  68. },
  69. );
  70. }
  71. async function clickExpiredLoginAlertAction(): Promise<void> {
  72. await browser.execute(() => {
  73. const button = document.querySelector<HTMLButtonElement>(
  74. '[data-slot="alert-dialog-content"] button',
  75. );
  76. if (!button) {
  77. throw new Error("登录失效提示缺少确认按钮");
  78. }
  79. button.click();
  80. });
  81. }
  82. async function waitForOAuthCredentialsCleanup(): Promise<void> {
  83. await browser.waitUntil(
  84. async () => {
  85. try {
  86. const credentials = JSON.parse(
  87. await readFile(getE2EAppDataPaths().credentialsFile, "utf-8"),
  88. ) as Record<string, string>;
  89. return OAUTH_CREDENTIAL_KEYS.every((key) => !(key in credentials));
  90. } catch {
  91. return false;
  92. }
  93. },
  94. {
  95. timeout: 10000,
  96. timeoutMsg: "401 后确认提示出现前 OAuth/JWT 凭据没有清理",
  97. },
  98. );
  99. }