project-location-decrypt-recovery.test.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import { readFile, writeFile } from "node:fs/promises";
  2. import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
  3. import { TID_LOGIN_TRIGGER, TID_TASK_SETTINGS_BUTTON } from "@zcode/shared/test-ids";
  4. import { clearAppData, clickTestIdByDom, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  5. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  6. import { skipOccupationOnboardingIfPresent } from "#e2e/helpers/occupation-onboarding";
  7. interface Status {
  8. locationRequests: number;
  9. tokenRequests: number;
  10. loginCompletions: number;
  11. tokenAttempts: number;
  12. keyCreateRequests: number;
  13. tokenPaths: string[];
  14. }
  15. const readCredentials = async () =>
  16. JSON.parse(await readFile(getE2EAppDataPaths().credentialsFile, "utf8")) as Record<
  17. string,
  18. string
  19. >;
  20. async function assertLoggedIn(before: Record<string, string>) {
  21. await skipOccupationOnboardingIfPresent();
  22. await browser.waitUntil(
  23. async () => {
  24. const label = await browser
  25. .$(`[data-testid="${TID_LOGIN_TRIGGER}"]`)
  26. .getAttribute("aria-label");
  27. return label?.includes("Fixture User") === true;
  28. },
  29. { timeout: 30000, timeoutMsg: "有效登录头像没有保留" },
  30. );
  31. const after = await readCredentials();
  32. for (const [key, value] of Object.entries(before)) {
  33. if (key.startsWith("oauth:") || key === "zcodejwttoken" || key === "bot:e2e:credential")
  34. expect(after[key]).toBe(value);
  35. }
  36. const expired = await browser.execute(() =>
  37. /登录已过期|Your session has expired/u.test(
  38. document.querySelector('[data-slot="alert-dialog-title"]')?.textContent ?? "",
  39. ),
  40. );
  41. expect(expired).toBe(false);
  42. }
  43. describe("项目位置缓存局部恢复", () => {
  44. after(async () => {
  45. await browser.electron.restoreAllMocks();
  46. await clearAppData();
  47. });
  48. it("自动重建坏位置;503 保留登录;服务恢复后通过设置刷新成功", async function () {
  49. this.timeout(180_000);
  50. const baseUrl = process.env.ZCODE_E2E_ACCESS_TOKEN_401_URL;
  51. if (!baseUrl) throw new Error("缺少项目位置恢复 fixture");
  52. const status = async () => (await (await fetch(`${baseUrl}/__e2e/status`)).json()) as Status;
  53. const before = await readCredentials();
  54. await browser.waitUntil(async () => (await status()).tokenRequests > 0, {
  55. timeout: 30000,
  56. timeoutMsg: "坏缓存没有自动重建并签发 Token",
  57. });
  58. await assertLoggedIn(before);
  59. const healthy = await readCredentials();
  60. const locationKey = Object.keys(healthy).find((key) =>
  61. key.startsWith("project-key-location:v1:"),
  62. );
  63. expect(locationKey).toBeDefined();
  64. expect(healthy[locationKey!]).toMatch(/^enc:v2:/);
  65. expect(healthy[locationKey!]).not.toBe("enc:v1:broken-project-location");
  66. expect((await status()).loginCompletions).toBe(0);
  67. // 故障夹具只在旧进程完全退出后改写,避免与产品持久化发生测试自身的竞态。
  68. const previousRequests = (await status()).locationRequests;
  69. await fetch(`${baseUrl}/__e2e/location-unavailable`);
  70. await reloadElectronSessionPreservingBrowserProfile(browser, {
  71. afterElectronProcessExit: async () => {
  72. const raw = await readCredentials();
  73. raw[locationKey!] = "enc:v1:broken-project-location";
  74. await writeFile(getE2EAppDataPaths().credentialsFile, JSON.stringify(raw));
  75. },
  76. });
  77. await browser.waitUntil(async () => (await status()).locationRequests > previousRequests, {
  78. timeout: 30000,
  79. timeoutMsg: "未覆盖到位置重建 503 路径",
  80. });
  81. await assertLoggedIn(healthy);
  82. const relaunch = await browser.electron.mock("app", "relaunch");
  83. await relaunch.mockResolvedValue(undefined);
  84. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  85. await clickTestIdByDom("settings-section-nav-modelProvider");
  86. const previousTokens = (await status()).tokenRequests;
  87. await fetch(`${baseUrl}/__e2e/location-available`);
  88. await browser.waitUntil(
  89. async () =>
  90. browser.execute(() => {
  91. const button = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
  92. (el) => !el.disabled && /刷新|refresh/iu.test(el.getAttribute("aria-label") ?? ""),
  93. );
  94. if (!button) return false;
  95. button.click();
  96. return true;
  97. }),
  98. { timeout: 30000, timeoutMsg: "模型供应商设置没有可操作的刷新按钮" },
  99. );
  100. await browser.waitUntil(async () => (await status()).tokenRequests > previousTokens, {
  101. timeout: 30000,
  102. timeoutMsg: "服务恢复后正常刷新没有完成换证",
  103. });
  104. await assertLoggedIn(healthy);
  105. expect((await status()).loginCompletions).toBe(0);
  106. await relaunch.update();
  107. expect(relaunch.mock.calls).toHaveLength(0);
  108. await clickTestIdByDom(
  109. `model-provider-nav-item-preset:${BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan}`,
  110. );
  111. await browser.waitUntil(
  112. async () =>
  113. browser.execute(
  114. () =>
  115. document.body.innerText.includes("CODING PRO") &&
  116. Array.from(document.querySelectorAll("button")).some((el) =>
  117. /Unlink|断开|解除|解绑/u.test(el.textContent?.trim() ?? ""),
  118. ),
  119. ),
  120. { timeout: 30000, timeoutMsg: "恢复后没有显示已连接套餐及解绑入口" },
  121. );
  122. console.info("PROJECT_LOCATION_RECOVERY", {
  123. ...(await status()),
  124. oauthPreserved: true,
  125. networkFailurePreservedLogin: true,
  126. });
  127. await browser.saveScreenshot(
  128. `${process.env.ZCODE_E2E_ARTIFACT_DIR}/project-location-recovered.png`,
  129. );
  130. });
  131. it("已保存 Key ID 的冷缓存签发 503 后自动恢复且不重新登录", async function () {
  132. this.timeout(90000);
  133. const baseUrl = process.env.ZCODE_E2E_ACCESS_TOKEN_401_URL!;
  134. const status = async () => (await (await fetch(`${baseUrl}/__e2e/status`)).json()) as Status;
  135. const before = await readCredentials();
  136. const initial = await status();
  137. await fetch(`${baseUrl}/__e2e/token-retry-once`);
  138. await reloadElectronSessionPreservingBrowserProfile(browser);
  139. await browser.waitUntil(async () => (await status()).tokenAttempts >= 2, {
  140. timeout: 30000,
  141. timeoutMsg: "冷缓存首次 503 后没有自动再次签发",
  142. });
  143. await assertLoggedIn(before);
  144. const result = await status();
  145. expect(result.tokenAttempts).toBe(2);
  146. expect(new Set(result.tokenPaths).size).toBe(1);
  147. expect(result.keyCreateRequests).toBe(initial.keyCreateRequests);
  148. expect(result.loginCompletions).toBe(0);
  149. const settingsVisible = await browser.execute(() =>
  150. Boolean(document.querySelector('[data-testid="settings-section-nav-modelProvider"]')),
  151. );
  152. if (!settingsVisible) await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  153. await clickTestIdByDom("settings-section-nav-modelProvider");
  154. await clickTestIdByDom(
  155. `model-provider-nav-item-preset:${BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan}`,
  156. );
  157. await browser.waitUntil(
  158. async () => browser.execute(() => /CODING PRO/.test(document.body.innerText)),
  159. {
  160. timeout: 30000,
  161. timeoutMsg: "自动恢复后没有显示已连接套餐",
  162. },
  163. );
  164. await writeFile(
  165. `${process.env.ZCODE_E2E_ARTIFACT_DIR}/pat-cold-retry.json`,
  166. JSON.stringify(result, null, 2),
  167. );
  168. await browser.saveScreenshot(`${process.env.ZCODE_E2E_ARTIFACT_DIR}/pat-cold-retry.png`);
  169. });
  170. });