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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import { readFile } from "node:fs/promises";
  2. import { TID_OAUTH_LOGIN_BUTTON, TID_LOGIN_USE_API_KEY_BUTTON } from "@zcode/shared/test-ids";
  3. import { clearAppData, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  4. const OAUTH_CREDENTIAL_KEYS = [
  5. "oauth:active_provider",
  6. "oauth:zai:access_token",
  7. "oauth:zai:user_info",
  8. "zcodejwttoken",
  9. ] as const;
  10. describe("ZCode JWT 401 自动退出", () => {
  11. after(async () => {
  12. await browser.electron.restoreAllMocks();
  13. await clearAppData();
  14. });
  15. it("运行中共享 JWT 收到普通 401 后清理凭据并进入登录入口", async function () {
  16. this.timeout(120_000);
  17. const baseUrl = process.env.ZCODE_E2E_ACCESS_TOKEN_401_URL;
  18. if (!baseUrl) throw new Error("缺少隔离共享 JWT HTTP fixture");
  19. // 旧用例 mock main net.fetch,不能证明 Host transport。先确认真实 Host 使用共享 JWT。
  20. await browser.waitUntil(
  21. async () => {
  22. const status = (await (await fetch(`${baseUrl}/__e2e/status`)).json()) as {
  23. businessRequestCount: number;
  24. };
  25. return status.businessRequestCount > 0;
  26. },
  27. { timeout: 30000, timeoutMsg: "Host 没有使用共享 JWT 请求余额接口" },
  28. );
  29. const relaunchMock = await browser.electron.mock("app", "relaunch");
  30. await relaunchMock.mockResolvedValue(undefined);
  31. const quitMock = await browser.electron.mock("app", "quit");
  32. await quitMock.mockResolvedValue(undefined);
  33. await fetch(`${baseUrl}/__e2e/reject?status=401`, { method: "POST" });
  34. await waitForExpiredLoginAlert();
  35. await waitForOAuthCredentialsCleanup();
  36. await clickExpiredLoginAlertAction();
  37. await browser.waitUntil(
  38. async () =>
  39. browser.execute(
  40. (ids) =>
  41. ids.some((id) => {
  42. const element = document.querySelector<HTMLElement>(`[data-testid="${id}"]`);
  43. return element !== null && element.getBoundingClientRect().height > 0;
  44. }),
  45. [TID_OAUTH_LOGIN_BUTTON, TID_LOGIN_USE_API_KEY_BUTTON],
  46. ),
  47. { timeout: 10000, timeoutMsg: "确认后没有进入 Welcome 登录入口" },
  48. );
  49. expect(relaunchMock.mock.calls).toHaveLength(0);
  50. expect(quitMock.mock.calls).toHaveLength(0);
  51. const credentials = JSON.parse(await readFile(getE2EAppDataPaths().credentialsFile, "utf8"));
  52. expect(credentials["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. }