regional-login.mjs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. // 生产分享页是独立入口 packages/web-share;该入口没有远控页与 /src/auth 模块,只跑分享相关用例。
  9. const webShareEntry = process.env.REGIONAL_ENTRY === "web-share";
  10. const SHARE_PATH = "/cn/share/E2E_REGIONAL";
  11. const artifacts = resolve(".tmp/regional-login-e2e");
  12. await mkdir(artifacts, { recursive: true });
  13. const browser = await chromium.launch({ channel: "chrome", headless: true });
  14. const results = [];
  15. async function fixture({ clockOffsetMs = 0, holdInit, noPopup = false, ...options } = {}) {
  16. const h = await setup(browser, options);
  17. // 模拟 App 内置浏览器:window.open 不可用。同页跳转不应依赖它。
  18. if (noPopup) await h.context.addInitScript(() => (window.open = () => null));
  19. const openedPages = [];
  20. h.context.on("page", (page) => openedPages.push(page));
  21. // 只前移页面 Date.now,模拟手机或电脑时钟快于服务端;服务端 server_time 与 expires_at 不变。
  22. if (clockOffsetMs)
  23. await h.context.addInitScript((offset) => {
  24. const now = Date.now;
  25. Date.now = () => now() + offset;
  26. }, clockOffsetMs);
  27. const flows = [];
  28. await h.context.route("**/api/v1/oauth/cli/init", async (route) => {
  29. const provider = route.request().postDataJSON().provider;
  30. const flow = {
  31. provider,
  32. token: route.request().headers().authorization,
  33. ready: false,
  34. id: String(flows.length),
  35. };
  36. assert.match(flow.token, /^Bearer [a-f0-9]{64}$/);
  37. flows.push(flow);
  38. if (holdInit) await holdInit;
  39. // 服务端时间取 Node 侧真实时钟;clock-skew 只前移页面 Date.now。
  40. const serverTime = Math.floor(Date.now() / 1000);
  41. await route.fulfill({
  42. json: {
  43. code: 0,
  44. data: {
  45. flow_id: flow.id,
  46. authorize_url: `https://auth.example.com/authorize?state=${flow.id}&redirect_uri=https%3A%2F%2Fauth.example.com%2Fserver-callback`,
  47. expires_at: serverTime + 60,
  48. server_time: serverTime,
  49. poll_interval_sec: 1,
  50. },
  51. },
  52. });
  53. });
  54. await h.context.route("https://auth.example.com/**", (route) =>
  55. route.fulfill({ contentType: "text/html", body: "<p>Local synthetic authorization</p>" }),
  56. );
  57. // 合成后端:与官网中转页一样由同源 callback 转交授权码,收到后 flow 才 ready。
  58. const callbacks = [];
  59. await h.context.route("**/api/v1/oauth/cli/callback/*", async (route) => {
  60. const url = new URL(route.request().url());
  61. const flow = flows.find((item) => item.id === url.searchParams.get("state"));
  62. callbacks.push({
  63. provider: url.pathname.split("/").pop(),
  64. code: url.searchParams.get("code"),
  65. state: url.searchParams.get("state"),
  66. });
  67. if (flow && url.searchParams.get("code") === `code-${flow.id}`) flow.ready = true;
  68. await route.fulfill({ contentType: "text/html", body: "<title>授权成功</title>" });
  69. });
  70. await h.context.route("**/api/v1/oauth/cli/poll/*", async (route) => {
  71. const flow = flows.find((item) => route.request().url().endsWith(`/${item.id}`));
  72. assert.ok(flow);
  73. assert.equal(route.request().headers().authorization, flow.token);
  74. await route.fulfill({
  75. json: {
  76. code: 0,
  77. data: flow.ready
  78. ? {
  79. status: "ready",
  80. token: "e2e-jwt",
  81. user: {
  82. user_id: "e2e-user",
  83. name: "E2E",
  84. id: "wrong-upstream",
  85. username: "Wrong",
  86. displayName: "Wrong",
  87. },
  88. zai: { access_token: "current-global-business" },
  89. bigmodel: { access_token: "must-not-persist-linked", customer_id: "linked-customer" },
  90. }
  91. : { status: "pending" },
  92. },
  93. });
  94. });
  95. await h.context.route("**/api/v1/shares/*/preview", (route) =>
  96. route.fulfill({ status: 404, json: { code: 3211, msg: "not_found" } }),
  97. );
  98. return { ...h, flows, callbacks, openedPages };
  99. }
  100. /** 当前页跳到合成授权站,返回授权 URL 中的 Web 回调地址。不应打开新页面。 */
  101. async function clickAuthorize(h) {
  102. await h.page.getByTestId("regional-login-submit").click();
  103. await h.page.waitForURL("https://auth.example.com/**");
  104. assert.equal(h.openedPages.length, 0, "区域登录不应打开新页面");
  105. const authorize = new URL(h.page.url());
  106. assert.equal(authorize.searchParams.get("state"), h.flows.at(-1).id);
  107. return new URL(authorize.searchParams.get("redirect_uri"));
  108. }
  109. /** 模拟授权站带 code/state(或 error/state)跳回:回调地址换成本地 origin,在指定页面打开。 */
  110. async function returnFromAuthorize(page, redirect, flow, { code = `code-${flow.id}`, error } = {}) {
  111. const callback = new URL(`${origin}${redirect.pathname}${redirect.search}`);
  112. if (error) callback.searchParams.set("error", error);
  113. else callback.searchParams.set("code", code);
  114. callback.searchParams.set("state", flow.id);
  115. await page.goto(callback.toString());
  116. }
  117. async function readSession(page) {
  118. return page.evaluate(() => JSON.parse(localStorage.getItem("oauth:browser_session")));
  119. }
  120. try {
  121. for (const surface of process.env.REGIONAL_BOUNDARIES_ONLY
  122. ? []
  123. : webShareEntry
  124. ? ["share"]
  125. : ["remote", "share"])
  126. for (const provider of ["zai_cn", "zai"])
  127. for (const width of [390, 1024])
  128. for (const theme of ["zai-light", "zai-dark"]) {
  129. const locale = provider === "zai_cn" ? "zh-CN" : "en-US";
  130. const h = await fixture({ width, theme, locale });
  131. const path =
  132. surface === "remote"
  133. ? "/remote/v4?app_version=3.16.3"
  134. : `${provider === "zai_cn" ? "/cn" : ""}/share/E2E_REGIONAL`;
  135. const name = `${surface}-${provider}-${width}-${theme}`;
  136. try {
  137. await h.page.goto(`${origin}${path}`);
  138. const action = h.page.getByTestId("regional-login-submit");
  139. await action.waitFor({ timeout: 5000 });
  140. assert.equal(await action.count(), 1);
  141. await h.page.getByTestId(`regional-login-${provider}`).click();
  142. const redirect = await clickAuthorize(h);
  143. // 远控回调保留扫码参数,让网关按 app_version 加载同一版本;分享使用独立回调地址。
  144. assert.equal(
  145. `${redirect.pathname}${redirect.search}`,
  146. surface === "remote" ? "/remote/v4?app_version=3.16.3" : "/cn/share/callback",
  147. );
  148. assert.equal(h.flows.length, 1);
  149. assert.equal(h.flows[0].provider, provider);
  150. await returnFromAuthorize(h.page, redirect, h.flows[0]);
  151. await h.page
  152. .getByRole("heading", {
  153. name:
  154. surface === "remote"
  155. ? locale === "zh-CN"
  156. ? "选择电脑"
  157. : "Choose a computer"
  158. : locale === "zh-CN"
  159. ? "找不到分享内容"
  160. : "Share not found",
  161. exact: true,
  162. })
  163. .waitFor();
  164. assert.deepEqual(h.callbacks, [
  165. { provider, code: `code-${h.flows[0].id}`, state: h.flows[0].id },
  166. ]);
  167. // 回到发起页原地址;授权参数不留在地址栏。
  168. assert.equal(h.page.url(), `${origin}${path}`);
  169. const session = await readSession(h.page);
  170. assert.equal(session.provider, provider);
  171. assert.equal(session.userInfo.id, "e2e-user");
  172. assert.equal(session.zcodeJwtToken, "e2e-jwt");
  173. assert.equal(
  174. session.businessAccessToken,
  175. provider === "zai" ? "current-global-business" : undefined,
  176. );
  177. assert.equal(
  178. await h.page.evaluate(() =>
  179. JSON.stringify(localStorage).includes("must-not-persist"),
  180. ),
  181. false,
  182. );
  183. assert.deepEqual(h.errors, []);
  184. await h.page.screenshot({ path: resolve(artifacts, `${name}.png`), fullPage: true });
  185. results.push({ name, result: "passed" });
  186. } finally {
  187. await h.context.close();
  188. }
  189. }
  190. // 在真实页面与同源标签中覆盖提交边界;只使用合成身份。
  191. for (const scenario of process.env.REGIONAL_SCENARIO
  192. ? [process.env.REGIONAL_SCENARIO]
  193. : webShareEntry
  194. ? ["share-cancel", "share-retry"]
  195. : [
  196. "cancel",
  197. "foreign-subject",
  198. "superseded",
  199. "legacy-callback",
  200. "no-locks-logout",
  201. "same-jwt-revision",
  202. "clock-skew",
  203. "no-popup",
  204. "other-tab-callback",
  205. "unknown-state",
  206. "expired-retry",
  207. "share-cancel",
  208. "share-retry",
  209. ]) {
  210. let releaseInit;
  211. const holdInit =
  212. scenario === "cancel" || scenario === "share-cancel"
  213. ? new Promise((resolve) => {
  214. releaseInit = resolve;
  215. })
  216. : undefined;
  217. const h = await fixture({
  218. ...(scenario === "clock-skew" ? { clockOffsetMs: 394_000 } : {}),
  219. ...(scenario === "no-popup" ? { noPopup: true } : {}),
  220. ...(holdInit ? { holdInit } : {}),
  221. });
  222. try {
  223. const startPath = scenario.startsWith("share-") ? SHARE_PATH : "/remote/v4";
  224. await h.page.goto(`${origin}${startPath}`);
  225. await h.page.getByTestId("regional-login-submit").waitFor();
  226. if (scenario === "same-jwt-revision") {
  227. let releaseOld;
  228. let requestCount = 0;
  229. let oldSettled = false;
  230. const held = new Promise((resolve) => {
  231. releaseOld = resolve;
  232. });
  233. await h.context.route("**/api/v1/remote/device", async (route) => {
  234. requestCount++;
  235. const current = requestCount;
  236. if (current === 1) await held;
  237. await route
  238. .fulfill({
  239. json: {
  240. code: 0,
  241. msg: "",
  242. data: [
  243. {
  244. device_sid: current === 1 ? "old-device" : "new-device",
  245. device_mid: "new-mid",
  246. online: true,
  247. created_at: 1,
  248. meta: { name: current === 1 ? "OLD RESULT" : "NEW RESULT" },
  249. },
  250. ],
  251. },
  252. })
  253. .catch(() => {});
  254. if (current === 1) oldSettled = true;
  255. });
  256. const other = await h.context.newPage();
  257. await other.goto(`${origin}/share/E2E_REGIONAL`);
  258. await other.evaluate(() =>
  259. localStorage.setItem(
  260. "oauth:browser_session",
  261. JSON.stringify({
  262. version: 1,
  263. provider: "zai_cn",
  264. userInfo: { id: "same-user", username: "Old", displayName: "Old" },
  265. zcodeJwtToken: "e2e-jwt",
  266. revision: "before",
  267. }),
  268. ),
  269. );
  270. await assertEventually(() => requestCount === 1);
  271. await other.evaluate(() =>
  272. localStorage.setItem(
  273. "oauth:browser_session",
  274. JSON.stringify({
  275. version: 1,
  276. provider: "zai_cn",
  277. userInfo: { id: "same-user", username: "New", displayName: "New" },
  278. zcodeJwtToken: "e2e-jwt",
  279. revision: "after",
  280. }),
  281. ),
  282. );
  283. await h.page.getByText("NEW RESULT", { exact: true }).waitFor();
  284. releaseOld();
  285. await assertEventually(() => oldSettled);
  286. await h.page.evaluate(
  287. () =>
  288. new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))),
  289. );
  290. assert.ok(requestCount >= 2);
  291. assert.equal(await h.page.getByText("OLD RESULT", { exact: true }).count(), 0);
  292. } else if (scenario === "legacy-callback") {
  293. const result = await h.page.evaluate(async () => {
  294. const { WebAuthService } = await import("/src/auth/webAuthService.ts");
  295. const { BrowserOAuthCredentialRepo } =
  296. await import("/src/auth/browserOAuthCredentialRepo.ts");
  297. const repo = new BrowserOAuthCredentialRepo();
  298. let authorization;
  299. const auth = new WebAuthService({
  300. repo,
  301. runtime: {
  302. createNonce: () => "legacy-attempt",
  303. getCurrentHref: () => location.href,
  304. getCurrentOrigin: () => location.origin,
  305. assign: (url) => {
  306. authorization = url;
  307. },
  308. replace: () => {},
  309. },
  310. });
  311. await auth.startLogin({ provider: "bigmodel" });
  312. const state = new URL(authorization).searchParams.get("state");
  313. const expected = await repo.beginLoginAttempt("new-attempt");
  314. await repo.commitPrimarySession(
  315. {
  316. provider: "zai_cn",
  317. userInfo: { id: "new-user", username: "New", displayName: "New" },
  318. zcodeJwtToken: "e2e-jwt",
  319. revision: "new-attempt",
  320. },
  321. expected,
  322. "new-attempt",
  323. );
  324. let rejected = false;
  325. try {
  326. await auth.handleCallback(
  327. `${location.origin}/remote/v4?authCode=old&state=${encodeURIComponent(state)}`,
  328. );
  329. } catch {
  330. rejected = true;
  331. }
  332. return { rejected, id: repo.loadCachedSession()?.id };
  333. });
  334. assert.deepEqual(result, { rejected: true, id: "new-user" });
  335. } else if (scenario === "no-locks-logout") {
  336. const result = await h.page.evaluate(async () => {
  337. const { BrowserOAuthCredentialRepo } =
  338. await import("/src/auth/browserOAuthCredentialRepo.ts");
  339. localStorage.setItem("oauth:active_provider", "zai");
  340. localStorage.setItem("zcodejwttoken", "old-jwt");
  341. localStorage.setItem("oauth:zai:access_token", "old-access");
  342. localStorage.setItem(
  343. "oauth:zai:user_info",
  344. JSON.stringify({ user_id: "old-user", name: "Old" }),
  345. );
  346. Object.defineProperty(navigator, "locks", { value: undefined, configurable: true });
  347. Object.defineProperty(crypto, "randomUUID", { value: undefined, configurable: true });
  348. const repo = new BrowserOAuthCredentialRepo();
  349. const before = repo.loadCachedSession()?.id;
  350. await repo.clearSession();
  351. await repo.finishLoginAttempt("missing");
  352. return { before, after: repo.loadCachedSession() };
  353. });
  354. assert.deepEqual(result, { before: "old-user", after: null });
  355. } else {
  356. if (scenario === "foreign-subject")
  357. await h.context.route("**/api/v1/oauth/cli/poll/*", (route) =>
  358. route.fulfill({
  359. json: {
  360. code: 0,
  361. data: h.flows[0]?.ready
  362. ? {
  363. status: "ready",
  364. token: "e2e-jwt",
  365. user: { id: "upstream", username: "Bad", displayName: "Bad" },
  366. }
  367. : { status: "pending" },
  368. },
  369. }),
  370. );
  371. const callbackErrorTitle = h.page.getByRole("heading", { name: "登录失败", exact: true });
  372. if (scenario === "cancel" || scenario === "share-cancel") {
  373. // 跳转前取消:init 未返回时点取消,页面不跳转,pending 与 attempt 都不残留。
  374. // share-cancel 覆盖分享入口:入口必须把取消信号交给登录服务,否则 init 返回后仍会跳走。
  375. await h.page.getByTestId("regional-login-submit").click();
  376. await assertEventually(() => h.flows.length === 1);
  377. await h.page.getByTestId("regional-login-cancel").click();
  378. releaseInit();
  379. await h.page.waitForFunction(
  380. () => localStorage.getItem("oauth:browser_login_attempt") === null,
  381. );
  382. assert.equal(new URL(h.page.url()).origin, origin);
  383. assert.equal(
  384. await h.page.evaluate(() => localStorage.getItem("oauth_pending_logins")),
  385. null,
  386. );
  387. assert.equal(await readSession(h.page), null);
  388. await h.page.getByTestId("regional-login-submit").waitFor({ state: "visible" });
  389. } else if (scenario === "share-retry") {
  390. // 分享页授权被拒:不调用后端;“重新登录”回到原分享页,而不是无分享码的 /share。
  391. const redirect = await clickAuthorize(h);
  392. await returnFromAuthorize(h.page, redirect, h.flows[0], { error: "access_denied" });
  393. const retry = h.page.getByRole("button", {
  394. name: /^(重新登录|Sign In Again|Try again)$/,
  395. });
  396. await retry.waitFor();
  397. assert.deepEqual(h.callbacks, []);
  398. await retry.click();
  399. await h.page.getByTestId("regional-login-submit").waitFor();
  400. assert.equal(h.page.url(), `${origin}${SHARE_PATH}`);
  401. assert.equal(
  402. await h.page.evaluate(() => localStorage.getItem("oauth_pending_logins")),
  403. null,
  404. );
  405. } else if (scenario === "unknown-state") {
  406. // 不属于任何 pending 的服务端 state:按 CSRF 失败,不调用后端 callback。
  407. await h.page.goto(`${origin}/remote/v4?code=code-x&state=0123456789abcdef`);
  408. await callbackErrorTitle.waitFor();
  409. assert.deepEqual(h.callbacks, []);
  410. assert.equal(await readSession(h.page), null);
  411. } else {
  412. const redirect = await clickAuthorize(h);
  413. if (scenario === "superseded") {
  414. // 跳转期间其他标签登录了新会话:旧 flow 回调不得覆盖。
  415. const other = await h.context.newPage();
  416. await other.goto(`${origin}/remote/v4`);
  417. await other.evaluate(() => {
  418. localStorage.setItem(
  419. "oauth:browser_session",
  420. JSON.stringify({
  421. version: 1,
  422. provider: "zai_cn",
  423. userInfo: { id: "new-user", username: "New", displayName: "New" },
  424. zcodeJwtToken: "e2e-jwt",
  425. revision: "newer",
  426. }),
  427. );
  428. });
  429. await returnFromAuthorize(h.page, redirect, h.flows[0]);
  430. await callbackErrorTitle.waitFor();
  431. assert.deepEqual(h.callbacks, []);
  432. assert.equal((await readSession(h.page)).revision, "newer");
  433. assert.equal(
  434. await h.page.evaluate(() => localStorage.getItem("oauth:browser_login_attempt")),
  435. null,
  436. );
  437. } else if (scenario === "expired-retry") {
  438. // pending 过期:不调用后端;“重新登录”回到发起页原地址。
  439. // 当前页停在授权站(另一 origin),在同源标签里改 pending 期限。
  440. const storagePage = await h.context.newPage();
  441. await storagePage.goto(`${origin}/remote/v4`);
  442. await storagePage.evaluate(() => {
  443. const logins = JSON.parse(localStorage.getItem("oauth_pending_logins"));
  444. for (const login of logins) login.regional.deadline = Date.now() - 1;
  445. localStorage.setItem("oauth_pending_logins", JSON.stringify(logins));
  446. });
  447. await storagePage.close();
  448. await returnFromAuthorize(h.page, redirect, h.flows[0]);
  449. await callbackErrorTitle.waitFor();
  450. assert.deepEqual(h.callbacks, []);
  451. await h.page.getByRole("button", { name: "重新登录", exact: true }).click();
  452. await h.page.getByTestId("regional-login-submit").waitFor();
  453. assert.equal(h.page.url(), `${origin}/remote/v4`);
  454. } else if (scenario === "foreign-subject") {
  455. await returnFromAuthorize(h.page, redirect, h.flows[0]);
  456. await callbackErrorTitle.waitFor();
  457. assert.equal(await readSession(h.page), null);
  458. } else {
  459. // no-popup / clock-skew:同一标签回调;other-tab-callback:回调落在同源新标签。
  460. const callbackPage =
  461. scenario === "other-tab-callback" ? await h.context.newPage() : h.page;
  462. await returnFromAuthorize(callbackPage, redirect, h.flows[0]);
  463. await callbackPage.getByRole("heading", { name: "选择电脑", exact: true }).waitFor();
  464. assert.equal(h.callbacks.length, 1);
  465. const session = await readSession(callbackPage);
  466. assert.equal(session.zcodeJwtToken, "e2e-jwt");
  467. assert.equal(session.userInfo.id, "e2e-user");
  468. // pending 取出即删,poll 凭据不残留。
  469. assert.equal(
  470. await callbackPage.evaluate(() => localStorage.getItem("oauth_pending_logins")),
  471. null,
  472. );
  473. assert.deepEqual(h.errors, []);
  474. }
  475. }
  476. }
  477. results.push({ name: scenario, result: "passed" });
  478. } catch (error) {
  479. await h.page.screenshot({ path: resolve(artifacts, `${scenario}-failed.png`) });
  480. await writeFile(
  481. resolve(artifacts, `${scenario}-failed.txt`),
  482. await h.page.locator("body").innerText(),
  483. );
  484. throw error;
  485. } finally {
  486. await h.context.close();
  487. }
  488. }
  489. await writeFile(resolve(artifacts, "results.json"), JSON.stringify(results, null, 2));
  490. } finally {
  491. await browser.close();
  492. }