oauth-credential-recovery.test.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. import { readFile, writeFile } from "node:fs/promises";
  2. import { readE2ECredentialValue } from "#e2e/helpers/desktop-app";
  3. import { BIGMODEL_PROVIDER_ID, ZAI_PROVIDER_ID } from "@zcode/shared";
  4. import {
  5. TID_LOGIN_REGION_SWITCH,
  6. TID_LOGIN_TRIGGER,
  7. TID_LOGIN_MENU_ITEM,
  8. TID_LOGIN_USE_API_KEY_BUTTON,
  9. TID_LOGIN_API_KEY_SKIP_BUTTON,
  10. TID_OAUTH_ERROR,
  11. TID_OAUTH_LOGIN_BUTTON,
  12. } from "@zcode/shared/test-ids";
  13. import {
  14. clearAppData,
  15. clickTestIdByDom,
  16. getE2EAppDataPaths,
  17. waitForTestIdByDom,
  18. } from "#e2e/helpers/desktop-app";
  19. const OAUTH_CREDENTIAL_KEYS = [
  20. "oauth:active_provider",
  21. `oauth:${ZAI_PROVIDER_ID}:access_token`,
  22. `oauth:${ZAI_PROVIDER_ID}:refresh_token`,
  23. `oauth:${ZAI_PROVIDER_ID}:user_info`,
  24. `oauth:${BIGMODEL_PROVIDER_ID}:access_token`,
  25. `oauth:${BIGMODEL_PROVIDER_ID}:refresh_token`,
  26. `oauth:${BIGMODEL_PROVIDER_ID}:user_info`,
  27. "zcodejwttoken",
  28. ] as const;
  29. describe("OAuth 凭据损坏恢复", () => {
  30. after(async () => {
  31. await browser.electron.restoreAllMocks();
  32. await clearAppData();
  33. });
  34. it("冷启动遇到无法解密的 OAuth 凭据时仍展示登录渠道并清理损坏登录态", async () => {
  35. await ensureOAuthLoginPanelOpen();
  36. await waitForTestIdByDom(TID_OAUTH_LOGIN_BUTTON, {
  37. timeout: 20000,
  38. timeoutMsg: "损坏 OAuth 凭据恢复后没有展示登录入口",
  39. });
  40. await waitForTestIdByDom(TID_LOGIN_REGION_SWITCH, {
  41. timeout: 20000,
  42. timeoutMsg: "损坏 OAuth 凭据恢复后没有展示中国/全球切换入口",
  43. });
  44. await expectNoOAuthErrorAlert();
  45. await waitForCorruptOAuthCredentialsCleanup();
  46. expect(await readE2ECredentialValue("bot:e2e:credential")).toBe("e2e-independent-bot-token");
  47. });
  48. for (const [label, contents] of [
  49. ["非法 JSON", '{"oauth:active_provider":'],
  50. ["值类型不符", '{"oauth:active_provider":42}'],
  51. ] as const) {
  52. it(`凭据库${label}时保留渠道且不改写原文件`, async () => {
  53. const { credentialsFile } = getE2EAppDataPaths();
  54. const original = await readFile(credentialsFile, "utf-8");
  55. try {
  56. await clickTestIdByDom(TID_LOGIN_USE_API_KEY_BUTTON);
  57. await clickTestIdByDom(TID_LOGIN_API_KEY_SKIP_BUTTON);
  58. await browser.waitUntil(async () =>
  59. browser.execute(() =>
  60. Boolean(
  61. document.querySelector(
  62. '[data-testid="onboarding-page"], [data-testid="login-trigger"]',
  63. ),
  64. ),
  65. ),
  66. );
  67. if (await browser.$('[data-testid="onboarding-page"]').isExisting()) {
  68. await browser.keys("Escape");
  69. }
  70. await waitForTestIdByDom(TID_LOGIN_TRIGGER);
  71. await writeFile(credentialsFile, contents, "utf-8");
  72. await ensureOAuthLoginPanelOpen();
  73. // 登录入口已收敛;凭据库损坏时仍需展示单按钮及区域切换,不依赖旧 provider 后缀。
  74. await waitForTestIdByDom(TID_OAUTH_LOGIN_BUTTON, {
  75. timeout: 10000,
  76. timeoutMsg: "凭据库读取失败后丢失登录渠道",
  77. });
  78. await waitForTestIdByDom(TID_LOGIN_REGION_SWITCH);
  79. await expectNoOAuthErrorAlert();
  80. expect(await readFile(credentialsFile, "utf-8")).toBe(contents);
  81. } finally {
  82. await writeFile(credentialsFile, original, "utf-8");
  83. }
  84. });
  85. }
  86. });
  87. async function expectNoOAuthErrorAlert() {
  88. const errorText = (await browser.execute((testId) => {
  89. return (
  90. document.querySelector<HTMLElement>(`[data-testid="${testId}"]`)?.textContent?.trim() ?? null
  91. );
  92. }, TID_OAUTH_ERROR)) as string | null;
  93. expect(errorText).toBeNull();
  94. }
  95. async function waitForCorruptOAuthCredentialsCleanup() {
  96. try {
  97. await browser.waitUntil(
  98. async () => {
  99. const credentials = await readCredentials();
  100. return OAUTH_CREDENTIAL_KEYS.every((key) => !(key in credentials));
  101. },
  102. {
  103. timeout: 10000,
  104. timeoutMsg: "损坏 OAuth 凭据没有被清理",
  105. },
  106. );
  107. } catch (error) {
  108. const credentials = await readCredentials().catch(() => null);
  109. const keys = credentials ? Object.keys(credentials).sort().join(", ") : "<missing>";
  110. throw new Error(`损坏 OAuth 凭据没有被清理,当前凭据 key: ${keys}`, {
  111. cause: error,
  112. });
  113. }
  114. }
  115. async function ensureOAuthLoginPanelOpen() {
  116. const loginButtonId = TID_OAUTH_LOGIN_BUTTON;
  117. try {
  118. await browser.waitUntil(
  119. async () => {
  120. const state = await readLoginEntryState(loginButtonId);
  121. return state.hasLoginButton || state.hasLoginTrigger;
  122. },
  123. {
  124. timeout: 60000,
  125. timeoutMsg: "启动后没有出现 OAuth 登录面板或手动登录入口",
  126. },
  127. );
  128. } catch (error) {
  129. throw new Error(
  130. await buildLoginEntryTimeoutMessage("启动后没有出现 OAuth 登录面板或手动登录入口"),
  131. {
  132. cause: error,
  133. },
  134. );
  135. }
  136. const state = await readLoginEntryState(loginButtonId);
  137. if (state.hasLoginButton) {
  138. return;
  139. }
  140. // Bugfix: OAuth 凭据恢复 spec 只要求用户重新登录入口可用;当启动期已有可用
  141. // workspace shell 时,登录面板需要从 sidebar 手动打开,不能把“未自动弹 WelcomeScreen”
  142. // 误判为恢复失败。
  143. await waitForTestIdByDom(TID_LOGIN_TRIGGER, {
  144. timeout: 20000,
  145. timeoutMsg: "损坏 OAuth 凭据恢复后没有可点击的手动登录入口",
  146. });
  147. await browser.$(`[data-testid="${TID_LOGIN_TRIGGER}"]`).click();
  148. await browser.waitUntil(async () =>
  149. browser.execute(
  150. (menu, button) =>
  151. Boolean(document.querySelector(`[data-testid="${menu}"], [data-testid="${button}"]`)),
  152. TID_LOGIN_MENU_ITEM,
  153. loginButtonId,
  154. ),
  155. );
  156. const menuItem = await browser.$(`[data-testid="${TID_LOGIN_MENU_ITEM}"]`);
  157. if (await menuItem.isExisting()) await clickTestIdByDom(TID_LOGIN_MENU_ITEM);
  158. }
  159. async function readLoginEntryState(loginButtonId: string): Promise<{
  160. hasLoginTrigger: boolean;
  161. hasLoginButton: boolean;
  162. }> {
  163. return (await browser.execute(
  164. (loginTriggerId, currentLoginButtonId) => {
  165. return {
  166. hasLoginTrigger: Boolean(document.querySelector(`[data-testid="${loginTriggerId}"]`)),
  167. hasLoginButton: Boolean(document.querySelector(`[data-testid="${currentLoginButtonId}"]`)),
  168. };
  169. },
  170. TID_LOGIN_TRIGGER,
  171. loginButtonId,
  172. )) as {
  173. hasLoginTrigger: boolean;
  174. hasLoginButton: boolean;
  175. };
  176. }
  177. async function buildLoginEntryTimeoutMessage(prefix: string) {
  178. const snapshot = await readOAuthRecoveryDomSnapshot().catch((error) => ({
  179. error: error instanceof Error ? error.message : String(error),
  180. }));
  181. return `${prefix}: ${JSON.stringify(snapshot)}`;
  182. }
  183. async function readOAuthRecoveryDomSnapshot() {
  184. return browser.execute(() => {
  185. const testIds = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]"))
  186. .map((element) => element.dataset.testid ?? "")
  187. .filter(Boolean)
  188. .slice(0, 40);
  189. return {
  190. testIds,
  191. title: document.title,
  192. text: document.body.textContent?.replace(/\s+/g, " ").trim().slice(0, 600) ?? "",
  193. url: window.location.href,
  194. };
  195. });
  196. }
  197. async function readCredentials(): Promise<Record<string, string>> {
  198. const { credentialsFile } = getE2EAppDataPaths();
  199. return JSON.parse(await readFile(credentialsFile, "utf-8")) as Record<string, string>;
  200. }