oauth-credential-recovery.test.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. import { readFile } from "node:fs/promises";
  2. import {
  3. BIGMODEL_PROVIDER_ID,
  4. TID_LOGIN_TRIGGER,
  5. TID_OAUTH_ERROR,
  6. TID_OAUTH_LOGIN_BUTTON,
  7. testId,
  8. ZAI_PROVIDER_ID,
  9. } from "@zcode/shared";
  10. import {
  11. clearAppData,
  12. clickTestIdByDom,
  13. getE2EAppDataPaths,
  14. waitForTestIdByDom,
  15. } from "./helpers/desktop-app.js";
  16. const OAUTH_CREDENTIAL_KEYS = [
  17. "oauth:active_provider",
  18. `oauth:${ZAI_PROVIDER_ID}:access_token`,
  19. `oauth:${ZAI_PROVIDER_ID}:refresh_token`,
  20. `oauth:${ZAI_PROVIDER_ID}:user_info`,
  21. `oauth:${BIGMODEL_PROVIDER_ID}:access_token`,
  22. `oauth:${BIGMODEL_PROVIDER_ID}:refresh_token`,
  23. `oauth:${BIGMODEL_PROVIDER_ID}:user_info`,
  24. "zcodejwttoken",
  25. ] as const;
  26. describe("OAuth 凭据损坏恢复", () => {
  27. after(async () => {
  28. await browser.electron.restoreAllMocks();
  29. await clearAppData();
  30. });
  31. it("冷启动遇到无法解密的 OAuth 凭据时仍展示登录渠道并清理损坏登录态", async () => {
  32. await ensureOAuthLoginPanelOpen();
  33. await waitForTestIdByDom(testId(TID_OAUTH_LOGIN_BUTTON, ZAI_PROVIDER_ID), {
  34. timeout: 20000,
  35. timeoutMsg: "损坏 OAuth 凭据恢复后没有展示 Z.ai 登录入口",
  36. });
  37. await waitForTestIdByDom(TID_OAUTH_LOGIN_BUTTON, {
  38. timeout: 20000,
  39. timeoutMsg: "损坏 OAuth 凭据恢复后没有展示 BigModel 登录入口",
  40. });
  41. await expectBigModelLoginButton();
  42. await expectNoOAuthErrorAlert();
  43. await waitForCorruptOAuthCredentialsCleanup();
  44. });
  45. });
  46. async function expectBigModelLoginButton() {
  47. const buttonText = (await browser.execute((testId) => {
  48. return (
  49. document.querySelector<HTMLElement>(`[data-testid="${testId}"]`)?.textContent?.trim() ?? ""
  50. );
  51. }, TID_OAUTH_LOGIN_BUTTON)) as string;
  52. expect(buttonText).toContain("BigModel");
  53. }
  54. async function expectNoOAuthErrorAlert() {
  55. const errorText = (await browser.execute((testId) => {
  56. return (
  57. document.querySelector<HTMLElement>(`[data-testid="${testId}"]`)?.textContent?.trim() ?? null
  58. );
  59. }, TID_OAUTH_ERROR)) as string | null;
  60. expect(errorText).toBeNull();
  61. }
  62. async function waitForCorruptOAuthCredentialsCleanup() {
  63. try {
  64. await browser.waitUntil(
  65. async () => {
  66. const credentials = await readCredentials();
  67. return OAUTH_CREDENTIAL_KEYS.every((key) => !(key in credentials));
  68. },
  69. {
  70. timeout: 10000,
  71. timeoutMsg: "损坏 OAuth 凭据没有被清理",
  72. },
  73. );
  74. } catch (error) {
  75. const credentials = await readCredentials().catch(() => null);
  76. const keys = credentials ? Object.keys(credentials).sort().join(", ") : "<missing>";
  77. throw new Error(`损坏 OAuth 凭据没有被清理,当前凭据 key: ${keys}`, {
  78. cause: error,
  79. });
  80. }
  81. }
  82. async function ensureOAuthLoginPanelOpen() {
  83. const zaiLoginButtonId = testId(TID_OAUTH_LOGIN_BUTTON, ZAI_PROVIDER_ID);
  84. try {
  85. await browser.waitUntil(
  86. async () => {
  87. const state = await readLoginEntryState(zaiLoginButtonId);
  88. return state.hasZaiLoginButton || state.hasLoginTrigger;
  89. },
  90. {
  91. timeout: 60000,
  92. timeoutMsg: "启动后没有出现 OAuth 登录面板或手动登录入口",
  93. },
  94. );
  95. } catch (error) {
  96. throw new Error(
  97. await buildLoginEntryTimeoutMessage("启动后没有出现 OAuth 登录面板或手动登录入口"),
  98. {
  99. cause: error,
  100. },
  101. );
  102. }
  103. const state = await readLoginEntryState(zaiLoginButtonId);
  104. if (state.hasZaiLoginButton) {
  105. return;
  106. }
  107. // Bugfix: OAuth 凭据恢复 spec 只要求用户重新登录入口可用;当启动期已有可用
  108. // workspace shell 时,登录面板需要从 sidebar 手动打开,不能把“未自动弹 WelcomeScreen”
  109. // 误判为恢复失败。
  110. await clickTestIdByDom(TID_LOGIN_TRIGGER, {
  111. timeout: 20000,
  112. timeoutMsg: "损坏 OAuth 凭据恢复后没有可点击的手动登录入口",
  113. });
  114. }
  115. async function readLoginEntryState(zaiLoginButtonId: string): Promise<{
  116. hasLoginTrigger: boolean;
  117. hasZaiLoginButton: boolean;
  118. }> {
  119. return (await browser.execute(
  120. (loginTriggerId, currentZaiLoginButtonId) => {
  121. return {
  122. hasLoginTrigger: Boolean(document.querySelector(`[data-testid="${loginTriggerId}"]`)),
  123. hasZaiLoginButton: Boolean(
  124. document.querySelector(`[data-testid="${currentZaiLoginButtonId}"]`),
  125. ),
  126. };
  127. },
  128. TID_LOGIN_TRIGGER,
  129. zaiLoginButtonId,
  130. )) as {
  131. hasLoginTrigger: boolean;
  132. hasZaiLoginButton: boolean;
  133. };
  134. }
  135. async function buildLoginEntryTimeoutMessage(prefix: string) {
  136. const snapshot = await readOAuthRecoveryDomSnapshot().catch((error) => ({
  137. error: error instanceof Error ? error.message : String(error),
  138. }));
  139. return `${prefix}: ${JSON.stringify(snapshot)}`;
  140. }
  141. async function readOAuthRecoveryDomSnapshot() {
  142. return browser.execute(() => {
  143. const testIds = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]"))
  144. .map((element) => element.dataset.testid ?? "")
  145. .filter(Boolean)
  146. .slice(0, 40);
  147. return {
  148. testIds,
  149. title: document.title,
  150. text: document.body.textContent?.replace(/\s+/g, " ").trim().slice(0, 600) ?? "",
  151. url: window.location.href,
  152. };
  153. });
  154. }
  155. async function readCredentials(): Promise<Record<string, string>> {
  156. const { credentialsFile } = getE2EAppDataPaths();
  157. return JSON.parse(await readFile(credentialsFile, "utf-8")) as Record<string, string>;
  158. }