regional-login.mjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. // 独立浏览器验收;所有账号、OAuth和业务接口均为本地合成响应,不访问真实授权。
  2. import assert from "node:assert/strict";
  3. import { mkdir, writeFile } from "node:fs/promises";
  4. import { resolve } from "node:path";
  5. import { chromium } from "playwright-core";
  6. import { setup, assertEventually } from "./remote-login-v2.helpers.mjs";
  7. const origin = process.env.REMOTE_LOGIN_E2E_ORIGIN || "http://127.0.0.1:5178";
  8. const artifacts = resolve(".tmp/regional-login-e2e");
  9. await mkdir(artifacts, { recursive: true });
  10. const browser = await chromium.launch({ channel: "chrome", headless: true });
  11. const results = [];
  12. async function fixture(options = {}) {
  13. const h = await setup(browser, options);
  14. const flows = [];
  15. await h.context.route("**/api/v1/oauth/cli/init", async (route) => {
  16. const provider = route.request().postDataJSON().provider;
  17. const flow = {
  18. provider,
  19. token: route.request().headers().authorization,
  20. ready: false,
  21. id: String(flows.length),
  22. };
  23. assert.match(flow.token, /^Bearer [a-f0-9]{64}$/);
  24. flows.push(flow);
  25. await route.fulfill({
  26. json: {
  27. code: 0,
  28. data: {
  29. flow_id: flow.id,
  30. authorize_url: `https://auth.example.com/authorize?state=${flow.id}&redirect_uri=https%3A%2F%2Fauth.example.com%2Fserver-callback`,
  31. expires_at: Date.now() / 1000 + 60,
  32. poll_interval_sec: 1,
  33. },
  34. },
  35. });
  36. });
  37. await h.context.route("https://auth.example.com/**", (route) =>
  38. route.fulfill({ contentType: "text/html", body: "<p>Local synthetic authorization</p>" }),
  39. );
  40. await h.context.route("**/api/v1/oauth/cli/poll/*", async (route) => {
  41. const flow = flows.find((item) => route.request().url().endsWith(`/${item.id}`));
  42. assert.ok(flow);
  43. assert.equal(route.request().headers().authorization, flow.token);
  44. await route.fulfill({
  45. json: {
  46. code: 0,
  47. data: flow.ready
  48. ? {
  49. status: "ready",
  50. token: "e2e-jwt",
  51. user: {
  52. user_id: "e2e-user",
  53. name: "E2E",
  54. id: "wrong-upstream",
  55. username: "Wrong",
  56. displayName: "Wrong",
  57. },
  58. zai: { access_token: "current-global-business" },
  59. bigmodel: { access_token: "must-not-persist-linked", customer_id: "linked-customer" },
  60. }
  61. : { status: "pending" },
  62. },
  63. });
  64. });
  65. await h.context.route("**/api/v1/shares/*/preview", (route) =>
  66. route.fulfill({ status: 404, json: { code: 3211, msg: "not_found" } }),
  67. );
  68. return { ...h, flows };
  69. }
  70. try {
  71. for (const surface of process.env.REGIONAL_BOUNDARIES_ONLY ? [] : ["remote", "share"])
  72. for (const provider of ["zai_cn", "zai"])
  73. for (const width of [390, 1024])
  74. for (const theme of ["zai-light", "zai-dark"]) {
  75. const locale = provider === "zai_cn" ? "zh-CN" : "en-US";
  76. const h = await fixture({ width, theme, locale });
  77. const path =
  78. surface === "remote"
  79. ? "/remote/v4?app_version=3.16.3"
  80. : `${provider === "zai_cn" ? "/cn" : ""}/share/E2E_REGIONAL`;
  81. const name = `${surface}-${provider}-${width}-${theme}`;
  82. try {
  83. await h.page.goto(`${origin}${path}`);
  84. const action = h.page.getByTestId("regional-login-submit");
  85. await action.waitFor({ timeout: 5000 });
  86. assert.equal(await action.count(), 1);
  87. await h.page.getByTestId(`regional-login-${provider}`).click();
  88. const popupPromise = h.context.waitForEvent("page");
  89. await action.click();
  90. const popup = await popupPromise;
  91. await popup.waitForURL("https://auth.example.com/**");
  92. assert.equal(
  93. new URL(popup.url()).searchParams.get("redirect_uri"),
  94. "https://auth.example.com/server-callback",
  95. );
  96. assert.equal(h.page.url(), `${origin}${path}`);
  97. assert.equal(h.flows.length, 1);
  98. assert.equal(h.flows[0].provider, provider);
  99. h.flows[0].ready = true;
  100. await h.page
  101. .getByRole("heading", {
  102. name:
  103. surface === "remote"
  104. ? locale === "zh-CN"
  105. ? "选择电脑"
  106. : "Choose a computer"
  107. : locale === "zh-CN"
  108. ? "找不到分享内容"
  109. : "Share not found",
  110. exact: true,
  111. })
  112. .waitFor();
  113. const session = await h.page.evaluate(() =>
  114. JSON.parse(localStorage.getItem("oauth:browser_session")),
  115. );
  116. assert.equal(session.provider, provider);
  117. assert.equal(session.userInfo.id, "e2e-user");
  118. assert.equal(session.zcodeJwtToken, "e2e-jwt");
  119. assert.equal(
  120. session.businessAccessToken,
  121. provider === "zai" ? "current-global-business" : undefined,
  122. );
  123. assert.equal(
  124. await h.page.evaluate(() =>
  125. JSON.stringify(localStorage).includes("must-not-persist"),
  126. ),
  127. false,
  128. );
  129. assert.deepEqual(h.errors, []);
  130. await h.page.screenshot({ path: resolve(artifacts, `${name}.png`), fullPage: true });
  131. results.push({ name, result: "passed" });
  132. } finally {
  133. await h.context.close();
  134. }
  135. }
  136. // 在真实页面与同源标签中覆盖提交边界;只使用合成身份。
  137. for (const scenario of process.env.REGIONAL_SCENARIO
  138. ? [process.env.REGIONAL_SCENARIO]
  139. : [
  140. "cancel",
  141. "foreign-subject",
  142. "superseded",
  143. "legacy-callback",
  144. "no-locks-logout",
  145. "same-jwt-revision",
  146. ]) {
  147. const h = await fixture();
  148. try {
  149. await h.page.goto(`${origin}/remote/v4`);
  150. await h.page.getByTestId("regional-login-submit").waitFor();
  151. if (scenario === "same-jwt-revision") {
  152. let releaseOld;
  153. let requestCount = 0;
  154. let oldSettled = false;
  155. const held = new Promise((resolve) => {
  156. releaseOld = resolve;
  157. });
  158. await h.context.route("**/api/v1/remote/device", async (route) => {
  159. requestCount++;
  160. const current = requestCount;
  161. if (current === 1) await held;
  162. await route
  163. .fulfill({
  164. json: {
  165. code: 0,
  166. msg: "",
  167. data: [
  168. {
  169. device_sid: current === 1 ? "old-device" : "new-device",
  170. device_mid: "new-mid",
  171. online: true,
  172. created_at: 1,
  173. meta: { name: current === 1 ? "OLD RESULT" : "NEW RESULT" },
  174. },
  175. ],
  176. },
  177. })
  178. .catch(() => {});
  179. if (current === 1) oldSettled = true;
  180. });
  181. const other = await h.context.newPage();
  182. await other.goto(`${origin}/share/E2E_REGIONAL`);
  183. await other.evaluate(() =>
  184. localStorage.setItem(
  185. "oauth:browser_session",
  186. JSON.stringify({
  187. version: 1,
  188. provider: "zai_cn",
  189. userInfo: { id: "same-user", username: "Old", displayName: "Old" },
  190. zcodeJwtToken: "e2e-jwt",
  191. revision: "before",
  192. }),
  193. ),
  194. );
  195. await assertEventually(() => requestCount === 1);
  196. await other.evaluate(() =>
  197. localStorage.setItem(
  198. "oauth:browser_session",
  199. JSON.stringify({
  200. version: 1,
  201. provider: "zai_cn",
  202. userInfo: { id: "same-user", username: "New", displayName: "New" },
  203. zcodeJwtToken: "e2e-jwt",
  204. revision: "after",
  205. }),
  206. ),
  207. );
  208. await h.page.getByText("NEW RESULT", { exact: true }).waitFor();
  209. releaseOld();
  210. await assertEventually(() => oldSettled);
  211. await h.page.evaluate(
  212. () =>
  213. new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))),
  214. );
  215. assert.ok(requestCount >= 2);
  216. assert.equal(await h.page.getByText("OLD RESULT", { exact: true }).count(), 0);
  217. } else if (scenario === "legacy-callback") {
  218. const result = await h.page.evaluate(async () => {
  219. const { WebAuthService } = await import("/src/auth/webAuthService.ts");
  220. const { BrowserOAuthCredentialRepo } =
  221. await import("/src/auth/browserOAuthCredentialRepo.ts");
  222. const repo = new BrowserOAuthCredentialRepo();
  223. let authorization;
  224. const auth = new WebAuthService({
  225. repo,
  226. runtime: {
  227. createNonce: () => "legacy-attempt",
  228. getCurrentHref: () => location.href,
  229. getCurrentOrigin: () => location.origin,
  230. assign: (url) => {
  231. authorization = url;
  232. },
  233. replace: () => {},
  234. },
  235. });
  236. await auth.startLogin({ provider: "bigmodel" });
  237. const state = new URL(authorization).searchParams.get("state");
  238. const expected = await repo.beginLoginAttempt("new-attempt");
  239. await repo.commitPrimarySession(
  240. {
  241. provider: "zai_cn",
  242. userInfo: { id: "new-user", username: "New", displayName: "New" },
  243. zcodeJwtToken: "e2e-jwt",
  244. revision: "new-attempt",
  245. },
  246. expected,
  247. "new-attempt",
  248. );
  249. let rejected = false;
  250. try {
  251. await auth.handleCallback(
  252. `${location.origin}/remote/v4?authCode=old&state=${encodeURIComponent(state)}`,
  253. );
  254. } catch {
  255. rejected = true;
  256. }
  257. return { rejected, id: repo.loadCachedSession()?.id };
  258. });
  259. assert.deepEqual(result, { rejected: true, id: "new-user" });
  260. } else if (scenario === "no-locks-logout") {
  261. const result = await h.page.evaluate(async () => {
  262. const { BrowserOAuthCredentialRepo } =
  263. await import("/src/auth/browserOAuthCredentialRepo.ts");
  264. localStorage.setItem("oauth:active_provider", "zai");
  265. localStorage.setItem("zcodejwttoken", "old-jwt");
  266. localStorage.setItem("oauth:zai:access_token", "old-access");
  267. localStorage.setItem(
  268. "oauth:zai:user_info",
  269. JSON.stringify({ user_id: "old-user", name: "Old" }),
  270. );
  271. Object.defineProperty(navigator, "locks", { value: undefined, configurable: true });
  272. Object.defineProperty(crypto, "randomUUID", { value: undefined, configurable: true });
  273. const repo = new BrowserOAuthCredentialRepo();
  274. const before = repo.loadCachedSession()?.id;
  275. await repo.clearSession();
  276. await repo.finishLoginAttempt("missing");
  277. return { before, after: repo.loadCachedSession() };
  278. });
  279. assert.deepEqual(result, { before: "old-user", after: null });
  280. } else {
  281. if (scenario === "foreign-subject")
  282. await h.context.route("**/api/v1/oauth/cli/poll/*", (route) =>
  283. route.fulfill({
  284. json: {
  285. code: 0,
  286. data: h.flows[0]?.ready
  287. ? {
  288. status: "ready",
  289. token: "e2e-jwt",
  290. user: { id: "upstream", username: "Bad", displayName: "Bad" },
  291. }
  292. : { status: "pending" },
  293. },
  294. }),
  295. );
  296. const popupPromise = h.context.waitForEvent("page");
  297. await h.page.getByTestId("regional-login-submit").click();
  298. const popup = await popupPromise;
  299. await popup.waitForURL("https://auth.example.com/**");
  300. if (scenario === "cancel") {
  301. await h.page.getByTestId("regional-login-cancel").click();
  302. h.flows[0].ready = true;
  303. await h.page.waitForFunction(
  304. () => localStorage.getItem("oauth:browser_login_attempt") === null,
  305. );
  306. assert.equal(
  307. await h.page.evaluate(() => localStorage.getItem("oauth:browser_session")),
  308. null,
  309. );
  310. } else if (scenario === "superseded") {
  311. const other = await h.context.newPage();
  312. await other.goto(`${origin}/remote/v4`);
  313. await other.evaluate(() => {
  314. localStorage.setItem(
  315. "oauth:browser_session",
  316. JSON.stringify({
  317. version: 1,
  318. provider: "zai_cn",
  319. userInfo: { id: "new-user", username: "New", displayName: "New" },
  320. zcodeJwtToken: "e2e-jwt",
  321. revision: "newer",
  322. }),
  323. );
  324. });
  325. h.flows[0].ready = true;
  326. await h.page.getByTestId("regional-login-submit").waitFor({ state: "visible" });
  327. await h.page.waitForFunction(
  328. () => localStorage.getItem("oauth:browser_login_attempt") === null,
  329. );
  330. assert.equal(
  331. await h.page.evaluate(
  332. () => JSON.parse(localStorage.getItem("oauth:browser_session")).revision,
  333. ),
  334. "newer",
  335. );
  336. } else {
  337. h.flows[0].ready = true;
  338. await h.page.getByRole("alert").waitFor();
  339. assert.equal(
  340. await h.page.evaluate(() => localStorage.getItem("oauth:browser_session")),
  341. null,
  342. );
  343. }
  344. }
  345. results.push({ name: scenario, result: "passed" });
  346. } catch (error) {
  347. await h.page.screenshot({ path: resolve(artifacts, `${scenario}-failed.png`) });
  348. await writeFile(
  349. resolve(artifacts, `${scenario}-failed.txt`),
  350. await h.page.locator("body").innerText(),
  351. );
  352. throw error;
  353. } finally {
  354. await h.context.close();
  355. }
  356. }
  357. await writeFile(resolve(artifacts, "results.json"), JSON.stringify(results, null, 2));
  358. } finally {
  359. await browser.close();
  360. }