remote-login-v2.mjs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. // ML01–ML07、ML09、MD01–MD06、MD11–MD13:真实 Web 入口 + 浏览器 OAuth 回跳/登录门禁;外部 OAuth/relay 使用受控响应。
  2. // 启动:VITE_WEB_REMOTE_CONTROL_ROUTE_PATH=/remote/__test__ pnpm --filter @zcode/web exec vite --host 127.0.0.1 --port 5178 --strictPort
  3. // 运行:node packages/web/test/e2e/remote-control/authentication/manual-review/pending/remote-login-v2.mjs
  4. // 截图保留 pending,不代表真实 OAuth/手机/OSS 验收,不自动转正。
  5. import assert from "node:assert/strict";
  6. import { mkdir, writeFile } from "node:fs/promises";
  7. import { resolve } from "node:path";
  8. import { chromium } from "playwright-core";
  9. import {
  10. setup,
  11. mixedDevices,
  12. assertEventually,
  13. checkSwitchConfirmation,
  14. } from "./remote-login-v2.helpers.mjs";
  15. const origin = process.env.REMOTE_LOGIN_E2E_ORIGIN || "http://127.0.0.1:5178";
  16. const artifacts = resolve(".tmp/remote-login-v2-e2e");
  17. await mkdir(artifacts, { recursive: true });
  18. const browser = await chromium.launch({ channel: "chrome", headless: true });
  19. const results = [];
  20. const qrPath = "/remote/v4?app_version=3.13.0&sid=e2e-device&mid=e2e-mid&name=E2E";
  21. try {
  22. for (const width of [390, 1024])
  23. for (const theme of ["zai-light", "zai-dark"])
  24. for (const locale of ["zh-CN", "en-US"])
  25. for (const screen of ["login", "devices", "empty", "device-not-owned"]) {
  26. const h = await setup(browser, {
  27. width,
  28. theme,
  29. locale,
  30. signedIn: screen !== "login",
  31. devices: screen === "empty" ? [] : mixedDevices,
  32. });
  33. const isList = screen === "devices" || screen === "empty";
  34. try {
  35. await h.page.goto(`${origin}${isList ? "/remote/v4" : qrPath}`);
  36. const title =
  37. screen === "login"
  38. ? locale === "zh-CN"
  39. ? "登录后继续使用 Web 远程控制"
  40. : "Sign In To Continue"
  41. : isList
  42. ? locale === "zh-CN"
  43. ? "选择电脑"
  44. : "Choose a computer"
  45. : locale === "zh-CN"
  46. ? "该设备不属于当前账号"
  47. : "This device does not belong to this account";
  48. await h.page.getByRole("heading", { name: title, exact: true }).waitFor();
  49. if (screen === "login") {
  50. assert.deepEqual(
  51. await h.page.getByRole("button").allTextContents(),
  52. locale === "zh-CN"
  53. ? ["连接 Z.ai 继续使用全球", "连接 BigModel 继续使用中国"]
  54. : ["Connect to Z.aiGlobal", "Connect to BigModelCN"],
  55. );
  56. }
  57. if (isList) {
  58. // 空态除页头刷新图标外还有一个带文字的刷新按钮。
  59. await h.page
  60. .getByRole("button", { name: /^(刷新|Refresh)$/ })
  61. .first()
  62. .waitFor();
  63. await h.page
  64. .getByText(
  65. screen === "empty"
  66. ? locale === "zh-CN"
  67. ? "暂无设备"
  68. : "No devices yet"
  69. : "Alice’s MacBook",
  70. { exact: true },
  71. )
  72. .waitFor();
  73. assert.equal(h.traffic.lists, 1);
  74. if (screen === "devices") {
  75. // 在线组在前、离线组在后;两组各自是一个列表。
  76. const rows = h.page.locator("main ul button");
  77. assert.match(await rows.nth(0).innerText(), /Alice’s MacBook/);
  78. assert.match(await rows.nth(1).innerText(), /Workstation/);
  79. assert.equal(await rows.nth(2).isDisabled(), true);
  80. const opacities = await rows.evaluateAll((elements) =>
  81. elements.map((element) => getComputedStyle(element.firstElementChild).opacity),
  82. );
  83. assert.notEqual(opacities[0], opacities[2], "离线行应弱化");
  84. assert.match(await h.page.locator("main").innerText(), /E2E · Z\.ai/);
  85. }
  86. }
  87. await h.page.evaluate(() => document.fonts.ready);
  88. assert.equal(
  89. await h.page.evaluate(() => document.documentElement.scrollWidth > innerWidth),
  90. false,
  91. );
  92. // 归属失败后按 MID 查一次当前账号设备;mixedDevices 里原 SID 仍在线,不接续,留在失败页。
  93. if (screen === "device-not-owned") assert.equal(h.traffic.lists, 1);
  94. assert.equal(h.traffic.tokens, screen === "device-not-owned" ? 1 : 0);
  95. assert.equal(h.traffic.sockets, screen === "device-not-owned" ? 1 : 0);
  96. assert.deepEqual(h.errors, []);
  97. const filename = `${screen}-${width}-${theme}-${locale}.png`;
  98. await h.page.screenshot({ path: resolve(artifacts, filename), fullPage: true });
  99. if (screen === "device-not-owned") {
  100. assert.equal(
  101. await h.page
  102. .getByRole("button", { name: /选择其他设备|Choose another device/ })
  103. .count(),
  104. 1,
  105. );
  106. }
  107. if (screen === "device-not-owned" || screen === "devices")
  108. results.push(
  109. await checkSwitchConfirmation(h, { screen, width, theme, locale, artifacts }),
  110. );
  111. results.push({ screen, width, theme, locale, screenshot: filename, result: "passed" });
  112. } finally {
  113. await h.context.close();
  114. }
  115. }
  116. // 列表三个刷新触发、选择后回写、刷新页面走有 SID 路径。
  117. const selection = await setup(browser, { signedIn: true, relayError: null });
  118. try {
  119. await selection.page.goto(`${origin}/remote/v4?app_version=3.13.0`);
  120. await selection.page.getByRole("button", { name: /Alice’s MacBook/ }).waitFor();
  121. assert.equal(selection.traffic.lists, 1);
  122. await selection.page.getByRole("button", { name: "刷新", exact: true }).click();
  123. await assertEventually(() => selection.traffic.lists === 2);
  124. // 刷新按钮名称固定为“刷新”(请求中只转圈并禁用),需等它恢复可用再触发回前台刷新。
  125. const refresh = selection.page.getByRole("button", { name: "刷新", exact: true });
  126. for (let attempt = 0; attempt < 50 && (await refresh.isDisabled()); attempt++)
  127. await selection.page.waitForTimeout(100);
  128. assert.equal(await refresh.isDisabled(), false);
  129. await selection.page.evaluate(() => {
  130. Object.defineProperty(document, "visibilityState", { configurable: true, value: "hidden" });
  131. document.dispatchEvent(new Event("visibilitychange"));
  132. });
  133. assert.equal(selection.traffic.lists, 2);
  134. await selection.page.evaluate(() => {
  135. Object.defineProperty(document, "visibilityState", { configurable: true, value: "visible" });
  136. document.dispatchEvent(new Event("visibilitychange"));
  137. });
  138. await assertEventually(() => selection.traffic.lists === 3);
  139. await selection.page.getByRole("button", { name: /Alice’s MacBook/ }).click();
  140. await assertEventually(() => selection.traffic.bootstraps === 1);
  141. assert.deepEqual(Object.fromEntries(new URL(selection.page.url()).searchParams), {
  142. app_version: "3.13.0",
  143. sid: "e2e-device",
  144. mid: "e2e-mid",
  145. name: "Alice’s MacBook",
  146. });
  147. assert.equal(
  148. await selection.page.evaluate(() => localStorage.getItem("zcode-web-remote-last-device-sid")),
  149. "e2e-device",
  150. );
  151. await selection.page.reload();
  152. await assertEventually(() => selection.traffic.bootstraps === 2);
  153. assert.equal(selection.traffic.lists, 3);
  154. assert.deepEqual(selection.errors, []);
  155. results.push({ case: "MD01 列表三种刷新与选择;MD02 刷新恢复", result: "passed" });
  156. } finally {
  157. await selection.context.close();
  158. }
  159. for (const lastSid of ["e2e-device", "offline", "other-account-device"]) {
  160. const h = await setup(browser, { signedIn: true, relayError: null, lastSid });
  161. try {
  162. await h.page.goto(`${origin}/remote/v4?app_version=3.13.0`);
  163. if (lastSid === "e2e-device") await assertEventually(() => h.traffic.bootstraps === 1);
  164. else {
  165. await h.page.getByRole("button", { name: /Alice’s MacBook/ }).waitFor();
  166. assert.equal(h.traffic.tokens, 0);
  167. }
  168. assert.equal(h.traffic.lists, 1);
  169. assert.deepEqual(h.errors, []);
  170. results.push({ case: `MD03 最近设备 ${lastSid}`, result: "passed" });
  171. } finally {
  172. await h.context.close();
  173. }
  174. }
  175. const other = await setup(browser, { signedIn: true, lastSid: "e2e-device" });
  176. try {
  177. await other.page.goto(`${origin}${qrPath}`);
  178. await other.page.getByRole("button", { name: "选择其他设备", exact: true }).click();
  179. await other.page.getByRole("button", { name: /Alice’s MacBook/ }).waitFor();
  180. assert.equal(other.traffic.tokens, 1);
  181. // 第 1 次是归属失败后的旧 SID 接续查询(原 SID 在线,不接续),第 2 次是“选择其他设备”。
  182. assert.equal(other.traffic.lists, 2);
  183. assert.deepEqual(Object.fromEntries(new URL(other.page.url()).searchParams), {
  184. app_version: "3.13.0",
  185. });
  186. assert.equal(await other.page.evaluate(() => localStorage.getItem("zcodejwttoken")), "e2e-jwt");
  187. await other.page.getByRole("button", { name: "切换", exact: true }).click();
  188. await other.page.getByRole("button", { name: "退出并切换", exact: true }).click();
  189. await other.page.getByRole("button", { name: /连接 Z.ai 继续使用/ }).waitFor();
  190. assert.equal(await other.page.evaluate(() => localStorage.getItem("zcodejwttoken")), null);
  191. assert.deepEqual(other.errors, []);
  192. results.push({ case: "MD04 失败页换设备跳过最近直连;MD05 列表切换账号", result: "passed" });
  193. } finally {
  194. await other.context.close();
  195. }
  196. const shortScreen = await setup(browser, {
  197. signedIn: true,
  198. height: 300,
  199. relayError: null,
  200. devices: Array.from({ length: 12 }, (_, index) => ({
  201. ...mixedDevices[2],
  202. device_sid: index === 0 ? "e2e-device" : `device-${index}`,
  203. // 每台电脑独立 MID;同 MID 的多个 SID 会聚合成一行“N 个连接”。
  204. device_mid: index === 0 ? "e2e-mid" : `mid-${index}`,
  205. meta: { name: `Computer ${String(index).padStart(2, "0")}` },
  206. })),
  207. });
  208. try {
  209. await shortScreen.page.goto(`${origin}/remote/v4`);
  210. await shortScreen.page.getByRole("button", { name: /Computer 11/ }).waitFor();
  211. const geometry = await shortScreen.page.locator("main").evaluate((main) => {
  212. main.scrollTop = main.scrollHeight;
  213. return {
  214. scrollTop: main.scrollTop,
  215. lastBottom: main.querySelector("li:last-child").getBoundingClientRect().bottom,
  216. viewport: innerHeight,
  217. };
  218. });
  219. assert.ok(geometry.scrollTop > 0);
  220. assert.ok(geometry.lastBottom <= geometry.viewport);
  221. const firstRow = shortScreen.page.getByRole("button", { name: /Computer 00/ });
  222. const unfocused = await firstRow.evaluate(
  223. (element) => getComputedStyle(element).backgroundColor,
  224. );
  225. await shortScreen.page.getByRole("button", { name: "刷新", exact: true }).focus();
  226. // 刷新 → 账号行“切换” → 第一台设备
  227. await shortScreen.page.keyboard.press("Tab");
  228. await shortScreen.page.keyboard.press("Tab");
  229. assert.equal(await firstRow.evaluate((element) => element === document.activeElement), true);
  230. assert.notEqual(
  231. await firstRow.evaluate((element) => getComputedStyle(element).backgroundColor),
  232. unfocused,
  233. );
  234. await shortScreen.page.keyboard.press("Enter");
  235. await assertEventually(() => shortScreen.traffic.bootstraps === 1);
  236. assert.deepEqual(shortScreen.errors, []);
  237. results.push({ case: "MD06 矮屏长列表末行可达、键盘焦点与选择", result: "passed" });
  238. } finally {
  239. await shortScreen.context.close();
  240. }
  241. // 归属失败后从旧 Z.AI 会话切到 BigModel,两个入口仍由同一门禁提供。
  242. const switched = await setup(browser, {
  243. signedIn: true,
  244. initialProvider: "zai",
  245. provider: "bigmodel",
  246. });
  247. try {
  248. await switched.page.goto(`${origin}${qrPath}`);
  249. await switched.page.getByRole("button", { name: "切换账号", exact: true }).click();
  250. await switched.page.getByRole("button", { name: "退出并切换", exact: true }).click();
  251. await switched.page.getByRole("button", { name: /连接 BigModel 继续使用/ }).click();
  252. await assertEventually(() => !!switched.traffic.authorize);
  253. assert.equal(switched.traffic.authorize.pathname, "/login");
  254. const state = switched.traffic.authorize.searchParams.get("state");
  255. const payload = JSON.parse(Buffer.from(state, "base64url").toString());
  256. assert.equal(payload.app_return_to, `${origin}${qrPath}`);
  257. const callback = new URL(switched.traffic.authorize.searchParams.get("redirect"));
  258. assert.equal(callback.search, new URL(qrPath, origin).search);
  259. const redirectUri = callback.toString();
  260. callback.searchParams.set("authCode", "e2e-code");
  261. callback.searchParams.set("state", state);
  262. await switched.page.goto(`${origin}${callback.pathname}${callback.search}`);
  263. await switched.page.waitForURL(`${origin}${qrPath}`);
  264. assert.equal(switched.traffic.exchange.redirect_uri, redirectUri);
  265. assert.equal(
  266. await switched.page.evaluate(() => localStorage.getItem("oauth:active_provider")),
  267. "bigmodel",
  268. );
  269. assert.equal(
  270. await switched.page.evaluate(() => localStorage.getItem("oauth:zai:access_token")),
  271. null,
  272. );
  273. assert.deepEqual(switched.errors, []);
  274. results.push({ case: "ML03 归属失败后切到 BigModel 并回原扫码地址", result: "passed" });
  275. } finally {
  276. await switched.context.close();
  277. }
  278. // 正式/测试入口首次登录或401重登 → 原 URL 回跳 → terminal 配对并发送 bootstrap。
  279. for (const path of ["/remote/v4", "/remote/__test__"])
  280. for (const signedIn of [false, true])
  281. for (const width of [390, 1024])
  282. for (const provider of ["zai", "bigmodel"]) {
  283. const login = await setup(browser, { relayError: null, provider, width, signedIn });
  284. const loginQrPath = qrPath.replace("/remote/v4", path);
  285. try {
  286. if (signedIn) {
  287. // 只让旧登录态的第一次取token失败,新登录后恢复正常服务。
  288. await login.page.route(
  289. "**/api/v1/remote/token",
  290. async (route) => {
  291. login.traffic.tokens++;
  292. await route.fulfill({ status: 401, json: { code: 1001, msg: "unauthorized" } });
  293. },
  294. { times: 1 },
  295. );
  296. }
  297. await login.page.goto(`${origin}${loginQrPath}`);
  298. await login.page.getByRole("button", { name: /连接 Z.ai 继续使用/ }).waitFor();
  299. assert.equal(await login.page.getByRole("dialog").count(), 0);
  300. assert.equal(login.page.url(), `${origin}${loginQrPath}`);
  301. assert.equal(
  302. await login.page.evaluate(() => localStorage.getItem("zcodejwttoken")),
  303. null,
  304. );
  305. assert.equal(login.traffic.tokens, signedIn ? 1 : 0);
  306. assert.equal(login.traffic.sockets, 0);
  307. await login.page
  308. .getByRole("button", {
  309. name: provider === "zai" ? /连接 Z.ai 继续使用/ : /连接 BigModel 继续使用/,
  310. })
  311. .click();
  312. await assertEventually(() => !!login.traffic.authorize);
  313. const state = login.traffic.authorize.searchParams.get("state");
  314. const redirectUri = login.traffic.authorize.searchParams.get(
  315. provider === "zai" ? "redirect_uri" : "redirect",
  316. );
  317. const callback = new URL(redirectUri);
  318. assert.equal(callback.pathname, "/remote/v4");
  319. assert.equal(callback.search, new URL(loginQrPath, origin).search);
  320. if (provider === "bigmodel") {
  321. assert.equal(
  322. login.traffic.authorize.origin,
  323. process.env.REMOTE_LOGIN_E2E_BIGMODEL_ORIGIN || "https://bigmodel.cn",
  324. );
  325. assert.equal(login.traffic.authorize.pathname, "/login");
  326. assert.equal(login.traffic.authorize.searchParams.get("appId"), "zcode");
  327. assert.equal(login.traffic.authorize.searchParams.has("redirect_uri"), false);
  328. }
  329. const payload = JSON.parse(Buffer.from(state, "base64url").toString());
  330. assert.equal(payload.app_return_to, `${origin}${loginQrPath}`);
  331. await login.page.goto(`${origin}/remote/v4`);
  332. assert.equal(
  333. await login.page.evaluate(
  334. () => JSON.parse(localStorage.getItem("oauth_pending_logins"))[0].provider,
  335. ),
  336. provider,
  337. );
  338. callback.searchParams.set(provider === "bigmodel" ? "authCode" : "code", "e2e-code");
  339. callback.searchParams.set("state", state);
  340. // 仅用本地 origin 承载真实入口;回调 path/query 来自实际授权地址,不另造无参数回调。
  341. await login.page.goto(`${origin}${callback.pathname}${callback.search}`);
  342. await login.page.waitForURL(`${origin}${loginQrPath}`);
  343. await assertEventually(() => login.traffic.bootstraps === 1);
  344. assert.equal(login.traffic.tokens, signedIn ? 2 : 1);
  345. assert.equal(login.traffic.sockets, 1);
  346. assert.equal(
  347. await login.page.evaluate(() => localStorage.getItem("zcodejwttoken")),
  348. "e2e-jwt",
  349. );
  350. assert.equal(
  351. await login.page.evaluate(() => localStorage.getItem("oauth:active_provider")),
  352. provider,
  353. );
  354. assert.equal(
  355. await login.page.evaluate(
  356. (p) => localStorage.getItem(`oauth:${p}:access_token`),
  357. provider,
  358. ),
  359. "e2e-access",
  360. );
  361. assert.equal(
  362. await login.page.evaluate(() => localStorage.getItem("oauth_pending_logins")),
  363. null,
  364. );
  365. assert.equal(login.traffic.exchange.provider, provider);
  366. assert.equal(login.traffic.exchange.redirect_uri, redirectUri);
  367. assert.deepEqual(login.errors, []);
  368. results.push({
  369. case: `ML04 ${path} ${provider} ${width}px ${signedIn ? "401重登" : "首次登录"}保留回调参数并配对`,
  370. result: "passed",
  371. });
  372. } finally {
  373. await login.context.close();
  374. }
  375. }
  376. // ML07:回调落在同一浏览器的另一个标签页(新标签页 sessionStorage 为空,只共享 localStorage)。
  377. // 修复前回调页读不到发起页 sessionStorage 中的 nonce,停在 “OAuth CSRF 检测失败”。
  378. for (const provider of ["zai", "bigmodel"]) {
  379. const login = await setup(browser, { relayError: null, provider });
  380. const callbackPage = await login.context.newPage();
  381. callbackPage.on("pageerror", (error) => login.errors.push(error.message));
  382. try {
  383. await login.page.goto(`${origin}${qrPath}`);
  384. await login.page
  385. .getByRole("button", {
  386. name: provider === "zai" ? /连接 Z.ai 继续使用/ : /连接 BigModel 继续使用/,
  387. })
  388. .click();
  389. await assertEventually(() => !!login.traffic.authorize);
  390. const redirectUri = login.traffic.authorize.searchParams.get(
  391. provider === "zai" ? "redirect_uri" : "redirect",
  392. );
  393. const callback = new URL(redirectUri);
  394. callback.searchParams.set(provider === "bigmodel" ? "authCode" : "code", "e2e-code");
  395. callback.searchParams.set("state", login.traffic.authorize.searchParams.get("state"));
  396. await callbackPage.goto(`${origin}${callback.pathname}${callback.search}`);
  397. await callbackPage.waitForURL(`${origin}${qrPath}`);
  398. await assertEventually(() => login.traffic.bootstraps === 1);
  399. assert.equal(login.traffic.exchange.provider, provider);
  400. assert.equal(login.traffic.exchange.redirect_uri, redirectUri);
  401. assert.equal(
  402. await callbackPage.evaluate(() => localStorage.getItem("zcodejwttoken")),
  403. "e2e-jwt",
  404. );
  405. assert.equal(
  406. await callbackPage.evaluate(() => localStorage.getItem("oauth_pending_logins")),
  407. null,
  408. );
  409. assert.deepEqual(login.errors, []);
  410. results.push({ case: `ML07 ${provider} 回调落在新标签页仍完成登录并配对`, result: "passed" });
  411. } finally {
  412. await callbackPage.screenshot({ path: resolve(artifacts, `ml07-${provider}.png`) });
  413. await login.context.close();
  414. }
  415. }
  416. for (const provider of ["zai", "bigmodel"])
  417. for (const tokenStatus of [200, 401]) {
  418. const h = await setup(browser, { signedIn: true, tokenStatus, relayError: null, provider });
  419. try {
  420. await h.page.goto(`${origin}${qrPath}`);
  421. if (tokenStatus === 200) await assertEventually(() => h.traffic.bootstraps === 1);
  422. else {
  423. await h.page.getByRole("button", { name: /连接 Z.ai 继续使用/ }).waitFor();
  424. assert.equal(await h.page.evaluate(() => localStorage.getItem("zcodejwttoken")), null);
  425. assert.equal(h.page.url(), `${origin}${qrPath}`);
  426. assert.equal(h.traffic.sockets, 0);
  427. await h.page.getByRole("button", { name: /连接 BigModel 继续使用/ }).click();
  428. await assertEventually(() => !!h.traffic.authorize);
  429. assert.equal(h.traffic.authorize.pathname, "/login");
  430. const state = JSON.parse(
  431. Buffer.from(h.traffic.authorize.searchParams.get("state"), "base64url").toString(),
  432. );
  433. assert.equal(state.app_return_to, `${origin}${qrPath}`);
  434. }
  435. assert.deepEqual(h.errors, []);
  436. results.push({
  437. case: `${provider} ${tokenStatus === 200 ? "ML05 已登录直连" : "ML06 token401回登录保留原URL"}`,
  438. result: "passed",
  439. });
  440. } finally {
  441. await h.context.close();
  442. }
  443. }
  444. // ML09:旧 JWT 的 token 请求在途时,另一个标签页写入新 JWT(同源 localStorage 共享),旧请求才回 401。
  445. // 修复前入口直接登出,清掉新 JWT 并回登录页;修复后按可重试处理,用新 JWT 重新申请并配对。
  446. {
  447. const h = await setup(browser, { signedIn: true, relayError: null });
  448. let releaseStale;
  449. const staleHeld = new Promise((done) => (releaseStale = done));
  450. const authorizations = [];
  451. await h.page.route("**/api/v1/remote/token", async (route) => {
  452. h.traffic.tokens++;
  453. authorizations.push(route.request().headers().authorization);
  454. if (authorizations.length === 1) {
  455. await staleHeld;
  456. await route.fulfill({ status: 401, json: { code: 1001, msg: "unauthorized" } });
  457. return;
  458. }
  459. await route.fulfill({
  460. json: { code: 0, msg: "", data: { token: "AAAAAAAAAAAAAAAAAAAAAA", expires_in: 60 } },
  461. });
  462. });
  463. try {
  464. await h.page.goto(`${origin}${qrPath}`);
  465. await assertEventually(() => authorizations.length === 1);
  466. await h.page.evaluate(() => localStorage.setItem("zcodejwttoken", "e2e-jwt-2"));
  467. releaseStale();
  468. await assertEventually(() => h.traffic.bootstraps === 1);
  469. assert.deepEqual(authorizations, ["Bearer e2e-jwt", "Bearer e2e-jwt-2"]);
  470. assert.equal(await h.page.evaluate(() => localStorage.getItem("zcodejwttoken")), "e2e-jwt-2");
  471. assert.equal(await h.page.getByRole("button", { name: /连接 Z.ai 继续使用/ }).count(), 0);
  472. assert.equal(h.traffic.sockets, 1);
  473. assert.equal(h.page.url(), `${origin}${qrPath}`);
  474. assert.deepEqual(h.errors, []);
  475. results.push({ case: "ML09 迟到401不清除其他标签页的新登录并用新JWT配对", result: "passed" });
  476. } finally {
  477. await h.context.close();
  478. }
  479. }
  480. // MD11–MD13:旧 SID 自动接续。桌面重新注册后同 MID 换了新 SID,旧链接仍带旧 SID。
  481. const sameMidDevices = (...sids) => [
  482. { device_sid: "e2e-device", device_mid: "e2e-mid", online: false, created_at: 1, meta: {} },
  483. ...sids.map((sid) => ({
  484. device_sid: sid,
  485. device_mid: "e2e-mid",
  486. online: true,
  487. created_at: 2,
  488. meta: { name: "Alice’s MacBook", platform: "darwin", version: "3.15.0" },
  489. })),
  490. mixedDevices[1],
  491. ];
  492. for (const oldReply of ["AUTH_FAILED", "waiting"]) {
  493. const h = await setup(browser, {
  494. signedIn: true,
  495. devices: sameMidDevices("e2e-device-new"),
  496. relayReplies: { "e2e-device": oldReply, "e2e-device-new": "matched" },
  497. });
  498. try {
  499. await h.page.goto(`${origin}${qrPath}`);
  500. // waiting 走首次 30 秒等待超时(desktop-disconnected)后才查询。
  501. await assertEventually(() => h.traffic.bootstraps === 1, 45_000);
  502. assert.deepEqual(h.traffic.authSids.slice(-2), ["e2e-device", "e2e-device-new"]);
  503. assert.equal(h.traffic.lists, 1);
  504. assert.deepEqual(Object.fromEntries(new URL(h.page.url()).searchParams), {
  505. app_version: "3.13.0",
  506. sid: "e2e-device-new",
  507. mid: "e2e-mid",
  508. name: "Alice’s MacBook",
  509. });
  510. assert.equal(
  511. await h.page.evaluate(() => localStorage.getItem("zcode-web-remote-last-device-sid")),
  512. "e2e-device-new",
  513. );
  514. // 刷新按新 SID 直连,不再查询列表。
  515. await h.page.reload();
  516. await assertEventually(() => h.traffic.bootstraps === 2);
  517. assert.equal(h.traffic.authSids.at(-1), "e2e-device-new");
  518. assert.equal(h.traffic.lists, 1);
  519. assert.deepEqual(h.errors, []);
  520. results.push({
  521. case: `${oldReply === "AUTH_FAILED" ? "MD11 归属失败" : "MD12 等待超时"}后接续同 MID 唯一在线新 SID`,
  522. result: "passed",
  523. });
  524. } finally {
  525. await h.context.close();
  526. }
  527. }
  528. for (const [label, devices, relayReplies, expectedSockets] of [
  529. // 同 MID 多个在线 SID:不猜目标,留在失败页由用户选择。
  530. [
  531. "同 MID 多个在线",
  532. sameMidDevices("e2e-device-a", "e2e-device-b"),
  533. { "e2e-device": "AUTH_FAILED" },
  534. 1,
  535. ],
  536. // 接续出的新 SID 配对前又失败:只接续一次,不在 SID 间循环。
  537. [
  538. "接续目标也失效",
  539. sameMidDevices("e2e-device-new"),
  540. { "e2e-device": "AUTH_FAILED", "e2e-device-new": "AUTH_FAILED" },
  541. 2,
  542. ],
  543. ]) {
  544. const h = await setup(browser, { signedIn: true, devices, relayReplies });
  545. try {
  546. await h.page.goto(`${origin}${qrPath}`);
  547. await h.page.getByRole("heading", { name: "该设备不属于当前账号", exact: true }).waitFor();
  548. assert.equal(h.traffic.lists, 1);
  549. assert.equal(h.traffic.sockets, expectedSockets);
  550. assert.equal(h.traffic.bootstraps, 0);
  551. assert.deepEqual(h.errors, []);
  552. results.push({ case: `MD13 ${label}:不接续,显示原失败页`, result: "passed" });
  553. } finally {
  554. await h.context.close();
  555. }
  556. }
  557. } finally {
  558. await writeFile(resolve(artifacts, "results.json"), JSON.stringify(results, null, 2));
  559. const shots = results.filter((result) => result.screenshot);
  560. await writeFile(
  561. resolve(artifacts, "index.html"),
  562. `<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>Relay V2 手机入口截图矩阵</title><style>body{margin:24px;background:#eee;color:#222;font:14px system-ui}main{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px}figure{margin:0;background:white;padding:12px}img{width:100%;height:422px;object-fit:contain}figcaption{margin-bottom:12px}a{color:inherit}</style><h1>Relay V2 手机入口截图矩阵</h1><p>受控 OAuth / relay,本地浏览器证据。设备列表16张,登录与归属失败16张,切换账号确认16张。</p><main>${shots.map((shot) => `<figure><figcaption>${shot.screen} · ${shot.width}px · ${shot.theme} · ${shot.locale}</figcaption><a href="${shot.screenshot}"><img src="${shot.screenshot}" alt="${shot.screen}"></a></figure>`).join("")}</main></html>`,
  563. );
  564. await browser.close();
  565. }
  566. console.log(`Passed ${results.length} checks; screenshots: ${artifacts}`);