coding-plan-upgrade-mock-server.ts 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  1. import { requestSecurityClientConfig } from "./request-security-edition/index.js";
  2. /* eslint-disable max-lines -- E2E fixture server 需要集中维护 ZCode client config 与 BigModel 购买接口响应 */
  3. import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
  4. import { once } from "node:events";
  5. import { readFile } from "node:fs/promises";
  6. import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
  7. import { createMarketingTouchFixture } from "./marketing-touch-fixture.js";
  8. import { rewardsWebsiteFixture } from "./rewards-website-fixture.js";
  9. export type CodingPlanUpgradeMockScenario =
  10. | "manual-claim-experience"
  11. | "personal-sold-out"
  12. | "personal-system-busy"
  13. | "webview-refresh-provider";
  14. export interface CodingPlanUpgradeMockRequest {
  15. method: string;
  16. path: string;
  17. query: Record<string, string>;
  18. headers: Record<string, string>;
  19. keyCreation?: { name?: unknown; usageScene?: unknown };
  20. }
  21. export interface CodingPlanUpgradeMockServer {
  22. baseUrl: string;
  23. scenario: CodingPlanUpgradeMockScenario;
  24. stop(): Promise<void>;
  25. }
  26. interface CodingPlanUpgradeMockState {
  27. associatedAuthMode: "off" | "ok" | "unauthorized" | "json-unauthorized" | "forbidden";
  28. associatedProfileHeld: boolean;
  29. associatedBusinessHeld: boolean;
  30. associatedBusinessWaiters: Array<() => void>;
  31. associatedProfileWaiters: Array<() => void>;
  32. webviewMode: "hold" | "fail" | "ready";
  33. webviewWaiters: Array<() => void>;
  34. highspeedHeld: boolean;
  35. highspeedOwnerRace: boolean;
  36. highspeedLifetimeMs: number;
  37. highspeedWaiters: Array<() => void>;
  38. subscriptionListHeld: boolean;
  39. subscriptionListWaiters: Array<() => void>;
  40. customerInfoHeld: boolean;
  41. customerInfoWaiters: Array<() => void>;
  42. inventoryMode: "hold" | "fail" | "ready";
  43. inventoryWaiters: Array<() => void>;
  44. clientConfigPayload: CodingPlanClientConfigFixture;
  45. manualClaimBucketReady: boolean;
  46. manualClaimCompleted: boolean;
  47. manualClaimShouldFail: boolean;
  48. startPlanExpired: boolean;
  49. purchaseCompleted: boolean;
  50. scenario: CodingPlanUpgradeMockScenario;
  51. }
  52. const DEFAULT_FULL_E2E_SPEC_GLOB = "./test/e2e/**/*.test.ts";
  53. export function resolveCodingPlanUpgradeMockScenario(
  54. specs: readonly string[],
  55. ): CodingPlanUpgradeMockScenario | null {
  56. if (specs.some((spec) => spec.includes("marketing-touch-"))) {
  57. return "manual-claim-experience";
  58. }
  59. if (specs.some((spec) => spec.includes("coding-plan-upgrade-personal-system-busy"))) {
  60. return "personal-system-busy";
  61. }
  62. if (specs.some((spec) => spec.includes("coding-plan-upgrade-personal-sold-out"))) {
  63. return "personal-sold-out";
  64. }
  65. if (
  66. specs.some(
  67. (spec) =>
  68. spec.includes("coding-plan-upgrade-webview-refresh-provider") ||
  69. spec.includes("account-key-usage-scene") ||
  70. spec.includes("highspeed-owner-ui-race.test.ts"),
  71. )
  72. ) {
  73. return "webview-refresh-provider";
  74. }
  75. return null;
  76. }
  77. export function shouldPrepareCodingPlanUpgradeMockForBuild(specs: readonly string[]): boolean {
  78. return (
  79. resolveCodingPlanUpgradeMockScenario(specs) !== null ||
  80. specs.some((spec) => spec.replace(/\\/gu, "/") === DEFAULT_FULL_E2E_SPEC_GLOB)
  81. );
  82. }
  83. export async function resetCodingPlanUpgradeMockServer(
  84. baseUrl: string,
  85. scenario: CodingPlanUpgradeMockScenario,
  86. options: { marketingTouch?: boolean } = {},
  87. ): Promise<void> {
  88. const response = await fetch(`${baseUrl}/__e2e/coding-plan/reset`, {
  89. body: JSON.stringify({ scenario, marketingTouch: options.marketingTouch === true }),
  90. headers: { "content-type": "application/json" },
  91. method: "POST",
  92. });
  93. if (!response.ok) {
  94. throw new Error(
  95. `Coding Plan E2E mock reset failed: ${response.status} ${await response.text()}`,
  96. );
  97. }
  98. }
  99. export async function startCodingPlanUpgradeMockServer(
  100. scenario: CodingPlanUpgradeMockScenario,
  101. options: { marketingTouch?: boolean } = {},
  102. ): Promise<CodingPlanUpgradeMockServer> {
  103. // 修复原因:pnpm filter 会把 E2E cwd 切到 packages/desktop,不能用 cwd 定位仓库级 fixture。
  104. const clientConfigFixtureUrl = new URL(
  105. "../fixtures/coding-plan-client-configs.json",
  106. import.meta.url,
  107. );
  108. const baseClientConfigPayload = JSON.parse(
  109. await readFile(clientConfigFixtureUrl, "utf8"),
  110. ) as CodingPlanClientConfigFixture;
  111. const requests: CodingPlanUpgradeMockRequest[] = [];
  112. const state = createCodingPlanUpgradeMockState(baseClientConfigPayload, scenario);
  113. // 同套餐场景也供旧测试复用,不能隐式注入需要 release 的营销领取暂停。
  114. let marketing = options.marketingTouch ? await createMarketingTouchFixture() : null;
  115. const server = createServer((request, response) => {
  116. void (async () => {
  117. const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
  118. if (request.method === "POST" && pathname === "/__e2e/coding-plan/reset") {
  119. const payload = await readJsonBody<{ scenario?: unknown; marketingTouch?: boolean }>(
  120. request,
  121. );
  122. if (!isCodingPlanUpgradeMockScenario(payload.scenario)) {
  123. sendJson(response, { code: 400, msg: "Invalid Coding Plan E2E scenario" }, 400);
  124. return;
  125. }
  126. // 混合 suite 复用构建时的 origin;营销开关和投放也必须按 worker 重置,否则弹窗会遮挡购买入口。
  127. const nextMarketing = payload.marketingTouch ? await createMarketingTouchFixture() : null;
  128. marketing?.stop();
  129. marketing = nextMarketing;
  130. state.webviewWaiters.splice(0).forEach((release) => release());
  131. state.customerInfoWaiters.splice(0).forEach((release) => release());
  132. state.subscriptionListWaiters.splice(0).forEach((release) => release());
  133. state.highspeedWaiters.splice(0).forEach((release) => release());
  134. state.associatedProfileWaiters.splice(0).forEach((release) => release());
  135. state.associatedBusinessWaiters.splice(0).forEach((release) => release());
  136. state.inventoryWaiters.splice(0).forEach((release) => release());
  137. Object.assign(
  138. state,
  139. createCodingPlanUpgradeMockState(baseClientConfigPayload, payload.scenario),
  140. );
  141. requests.splice(0, requests.length);
  142. sendJson(response, { ok: true, scenario: state.scenario });
  143. return;
  144. }
  145. if (marketing && /^\/(cn|en)\/rewards$/.test(pathname)) {
  146. response.writeHead(200, {
  147. "Content-Type": "text/html; charset=utf-8",
  148. "Cache-Control": "no-store",
  149. });
  150. response.end(rewardsWebsiteFixture);
  151. return;
  152. }
  153. if (await marketing?.handle(request, response)) return;
  154. if (!marketing && pathname === "/api/v1/marketing/touch") {
  155. sendJson(response, {
  156. code: 0,
  157. data: {
  158. server_time: Math.floor(Date.now() / 1000),
  159. language: request.headers["x-client-language"] === "zh-CN" ? "zh-CN" : "en-US",
  160. deliveries: [],
  161. },
  162. });
  163. return;
  164. }
  165. await handleRequest(state, requests, request, response, marketing !== null);
  166. })().catch((error) => {
  167. if (!response.headersSent) {
  168. sendJson(response, { code: 500, msg: formatErrorMessage(error) }, 500);
  169. return;
  170. }
  171. response.destroy(error instanceof Error ? error : new Error(String(error)));
  172. });
  173. });
  174. server.listen(0, "127.0.0.1");
  175. await once(server, "listening");
  176. const address = server.address();
  177. if (!address || typeof address === "string") {
  178. throw new Error("Coding Plan E2E mock server did not bind to a TCP port");
  179. }
  180. return {
  181. baseUrl: `http://127.0.0.1:${address.port}`,
  182. get scenario() {
  183. return state.scenario;
  184. },
  185. stop: async () => {
  186. marketing?.stop();
  187. state.webviewWaiters.splice(0).forEach((release) => release());
  188. state.customerInfoWaiters.splice(0).forEach((release) => release());
  189. state.subscriptionListWaiters.splice(0).forEach((release) => release());
  190. state.highspeedWaiters.splice(0).forEach((release) => release());
  191. state.associatedProfileWaiters.splice(0).forEach((release) => release());
  192. state.associatedBusinessWaiters.splice(0).forEach((release) => release());
  193. state.inventoryWaiters.splice(0).forEach((release) => release());
  194. server.close();
  195. await once(server, "close");
  196. },
  197. };
  198. }
  199. async function handleRequest(
  200. state: CodingPlanUpgradeMockState,
  201. requests: CodingPlanUpgradeMockRequest[],
  202. request: IncomingMessage,
  203. response: ServerResponse,
  204. marketingTouch: boolean,
  205. ) {
  206. const url = new URL(request.url ?? "/", "http://127.0.0.1");
  207. if (url.pathname === "/__e2e/coding-plan/webview-state") {
  208. sendJson(response, { pending: state.webviewWaiters.length });
  209. return;
  210. }
  211. if (request.method === "POST" && url.pathname === "/__e2e/coding-plan/webview-mode") {
  212. const { mode } = await readJsonBody<{ mode: "hold" | "fail" | "ready" }>(request);
  213. state.webviewMode = mode;
  214. state.webviewWaiters.splice(0).forEach((release) => release());
  215. sendJson(response, { ok: true });
  216. return;
  217. }
  218. if (request.method === "POST" && url.pathname === "/__e2e/coding-plan/associated-auth") {
  219. const body = await readJsonBody<{
  220. mode: CodingPlanUpgradeMockState["associatedAuthMode"];
  221. held: boolean;
  222. businessHeld?: boolean;
  223. }>(request);
  224. state.associatedAuthMode = body.mode;
  225. state.associatedProfileHeld = body.held;
  226. state.associatedBusinessHeld = body.businessHeld ?? false;
  227. if (!state.associatedBusinessHeld)
  228. state.associatedBusinessWaiters.splice(0).forEach((release) => release());
  229. if (!body.held) state.associatedProfileWaiters.splice(0).forEach((release) => release());
  230. sendJson(response, { ok: true });
  231. return;
  232. }
  233. if (
  234. request.method === "GET" &&
  235. url.pathname === "/api/biz/pay/check-pending-orders" &&
  236. state.associatedAuthMode !== "off"
  237. ) {
  238. recordRequest(requests, request, url);
  239. const status =
  240. state.associatedAuthMode === "unauthorized"
  241. ? 401
  242. : state.associatedAuthMode === "forbidden"
  243. ? 403
  244. : 200;
  245. const code = state.associatedAuthMode === "json-unauthorized" ? 401 : status;
  246. if (state.associatedBusinessHeld)
  247. await new Promise<void>((resolve) => state.associatedBusinessWaiters.push(resolve));
  248. sendJson(
  249. response,
  250. {
  251. code,
  252. msg: status === 200 ? "ok" : "rejected",
  253. data: status === 200 ? { hasPendingOrders: false } : null,
  254. },
  255. status,
  256. );
  257. return;
  258. }
  259. if (
  260. request.method === "GET" &&
  261. url.pathname === "/api/v1/oauth/profile" &&
  262. request.headers.authorization === "Bearer e2e-expiring-primary" &&
  263. state.associatedAuthMode !== "off"
  264. ) {
  265. recordRequest(requests, request, url);
  266. if (state.associatedProfileHeld)
  267. await new Promise<void>((resolve) => state.associatedProfileWaiters.push(resolve));
  268. sendJson(response, {
  269. code: 0,
  270. data: {
  271. user: { user_id: "e2e-expiring-user", name: "Associated" },
  272. bigmodel: { customer_id: "e2e-user", access_token: "e2e-renewed-business" },
  273. },
  274. });
  275. return;
  276. }
  277. if (request.method === "GET" && url.pathname === "/__e2e/coding-plan/requests") {
  278. sendJson(response, { requests });
  279. return;
  280. }
  281. if (request.method === "POST" && url.pathname === "/__e2e/coding-plan/subscription-list-hold") {
  282. const { held } = await readJsonBody<{ held: boolean }>(request);
  283. state.subscriptionListHeld = held;
  284. if (!held) state.subscriptionListWaiters.splice(0).forEach((release) => release());
  285. sendJson(response, { ok: true });
  286. return;
  287. }
  288. if (request.method === "POST" && url.pathname === "/__e2e/coding-plan/highspeed-hold") {
  289. const { held } = await readJsonBody<{ held: boolean }>(request);
  290. state.highspeedHeld = held;
  291. if (!held) state.highspeedWaiters.splice(0).forEach((release) => release());
  292. sendJson(response, { ok: true });
  293. return;
  294. }
  295. if (request.method === "POST" && url.pathname === "/__e2e/coding-plan/highspeed-owner-race") {
  296. state.highspeedOwnerRace = true;
  297. state.highspeedLifetimeMs = 5_000;
  298. state.highspeedHeld = true;
  299. // draw 正常返回,只挂起 healthy。按 FIFO 单独释放旧响应,保留新请求占位。
  300. sendJson(response, { ok: true });
  301. return;
  302. }
  303. if (request.method === "POST" && url.pathname === "/__e2e/coding-plan/highspeed-release-one") {
  304. const release = state.highspeedWaiters.shift();
  305. release?.();
  306. sendJson(response, { released: !!release });
  307. return;
  308. }
  309. if (state.highspeedOwnerRace && url.pathname === "/api/v1/oauth/cli/init") {
  310. sendJson(response, {
  311. code: 0,
  312. data: {
  313. flow_id: "owner-ui-relogin",
  314. authorize_url: "https://example.com/authorize?state=owner-ui-relogin",
  315. expires_at: Math.floor(Date.now() / 1000) + 300,
  316. poll_interval_sec: 1,
  317. },
  318. });
  319. return;
  320. }
  321. if (state.highspeedOwnerRace && url.pathname === "/api/v1/oauth/cli/poll/owner-ui-relogin") {
  322. sendJson(response, {
  323. code: 0,
  324. data: {
  325. status: "ready",
  326. token: "e2e-owner-new-primary",
  327. user: { user_id: "e2e-owner-user", name: "Owner User" },
  328. zai: { access_token: "e2e-owner-cn-upstream" },
  329. bigmodel: { customer_id: "e2e-user", access_token: "e2e-linked-bigmodel-jwt" },
  330. },
  331. });
  332. return;
  333. }
  334. if (request.method === "POST" && url.pathname === "/__e2e/coding-plan/customer-info-hold") {
  335. const { held } = await readJsonBody<{ held: boolean }>(request);
  336. state.customerInfoHeld = held;
  337. if (!held) state.customerInfoWaiters.splice(0).forEach((release) => release());
  338. sendJson(response, { ok: true });
  339. return;
  340. }
  341. if (request.method === "POST" && url.pathname === "/__e2e/coding-plan/inventory-mode") {
  342. const { mode } = await readJsonBody<{ mode: "hold" | "fail" | "ready" }>(request);
  343. state.inventoryMode = mode;
  344. state.inventoryWaiters.splice(0).forEach((release) => release());
  345. sendJson(response, { ok: true });
  346. return;
  347. }
  348. if (
  349. request.method === "POST" &&
  350. url.pathname === "/__e2e/coding-plan/manual-claim-failure" &&
  351. state.scenario === "manual-claim-experience"
  352. ) {
  353. state.manualClaimShouldFail = true;
  354. sendJson(response, { ok: true });
  355. return;
  356. }
  357. if (
  358. request.method === "POST" &&
  359. url.pathname === "/__e2e/coding-plan/manual-claim-bucket-ready" &&
  360. state.scenario === "manual-claim-experience"
  361. ) {
  362. state.manualClaimBucketReady = true;
  363. sendJson(response, { ok: true });
  364. return;
  365. }
  366. if (
  367. request.method === "POST" &&
  368. url.pathname === "/__e2e/coding-plan/manual-claim-next-window" &&
  369. state.scenario === "manual-claim-experience"
  370. ) {
  371. // Bug 原因:下一时段只重置 completed 会让失败用例的一次性开关泄漏到后续成功用例。
  372. state.manualClaimCompleted = false;
  373. state.manualClaimShouldFail = false;
  374. sendJson(response, { ok: true });
  375. return;
  376. }
  377. const recordedRequest = recordRequest(requests, request, url);
  378. if (
  379. request.method === "POST" &&
  380. url.pathname === "/__e2e/coding-plan/start-expired" &&
  381. state.scenario === "manual-claim-experience"
  382. ) {
  383. state.startPlanExpired = true;
  384. sendJson(response, { ok: true });
  385. return;
  386. }
  387. if (
  388. request.method === "GET" &&
  389. url.pathname === "/api/v1/zcode-plan/billing/preview" &&
  390. state.scenario === "manual-claim-experience"
  391. ) {
  392. sendJson(response, {
  393. code: 0,
  394. msg: "ok",
  395. data: {
  396. server_time: Math.floor(Date.now() / 1_000),
  397. plans: state.manualClaimCompleted
  398. ? []
  399. : [
  400. {
  401. plan_id: "weekend-plan-e2e",
  402. name: "ZCode Weekend Build",
  403. description: "Deterministic manual claim fixture",
  404. priority: 100,
  405. entitlements: [
  406. {
  407. entitlement_id: "weekend-glm-flash",
  408. show_name: "GLM-5.3-Flash",
  409. meter: "model_usage",
  410. unit_type: "token",
  411. capabilities: ["model:glm-5.3-flash"],
  412. grant_units: 10_000_000_000,
  413. period: "one_time",
  414. priority: 10,
  415. },
  416. ],
  417. },
  418. ],
  419. },
  420. });
  421. return;
  422. }
  423. if (
  424. request.method === "POST" &&
  425. url.pathname === "/api/v1/zcode-plan/billing/claim" &&
  426. state.scenario === "manual-claim-experience"
  427. ) {
  428. if (state.manualClaimShouldFail) {
  429. state.manualClaimShouldFail = false;
  430. state.manualClaimCompleted = true;
  431. sendJson(response, { code: 1003, data: null, msg: "already claimed" });
  432. return;
  433. }
  434. state.manualClaimCompleted = true;
  435. const nowSeconds = Math.floor(Date.now() / 1_000);
  436. sendJson(response, {
  437. code: 0,
  438. msg: "ok",
  439. data: {
  440. server_time: nowSeconds,
  441. plan: {
  442. user_plan_id: "user-weekend-plan-e2e",
  443. plan_id: "weekend-plan-e2e",
  444. status: "active",
  445. starts_at: nowSeconds,
  446. ends_at: nowSeconds + 86_400,
  447. entitlements: [
  448. {
  449. entitlement_id: "weekend-glm-flash",
  450. show_name: "GLM-5.3-Flash",
  451. effective_at: nowSeconds + 3_600,
  452. },
  453. ],
  454. },
  455. },
  456. });
  457. return;
  458. }
  459. if (request.method === "GET" && url.pathname === "/coding-plan") {
  460. if (state.webviewMode === "hold")
  461. await new Promise<void>((resolve) => state.webviewWaiters.push(resolve));
  462. if (state.webviewMode === "fail") {
  463. response.destroy();
  464. return;
  465. }
  466. sendHtml(response, buildCodingPlanWebviewFixtureHtml(state.scenario));
  467. return;
  468. }
  469. if (request.method === "POST" && url.pathname === "/__e2e/coding-plan/purchase-complete") {
  470. state.purchaseCompleted = true;
  471. sendJson(response, { ok: true });
  472. return;
  473. }
  474. if (request.method === "GET" && url.pathname === "/api/v2/releases/latest") {
  475. sendJson(response, {
  476. code: 0,
  477. data: { config_version: "coding-plan-upgrade-e2e" },
  478. config_version: "coding-plan-upgrade-e2e",
  479. });
  480. return;
  481. }
  482. if (
  483. request.method === "GET" &&
  484. url.pathname === "/api/v1/oauth/profile" &&
  485. request.headers.authorization === "Bearer e2e-association-upgrade-jwt"
  486. ) {
  487. sendJson(response, {
  488. code: 0,
  489. data: {
  490. user: { user_id: "e2e-association-user", name: "Associated User" },
  491. bigmodel: { customer_id: "e2e-user", access_token: "e2e-associated-ui-bigmodel-jwt" },
  492. },
  493. });
  494. return;
  495. }
  496. if (request.method === "GET" && url.pathname === "/api/v1/client/configs") {
  497. sendJson(response, state.clientConfigPayload);
  498. return;
  499. }
  500. if (
  501. request.method === "GET" &&
  502. url.pathname === "/api/v1/zcode-plan/billing/balance" &&
  503. (state.scenario === "manual-claim-experience" || state.scenario === "webview-refresh-provider")
  504. ) {
  505. // Bug 原因:领取 fixture 只 mock 了旧 quota 接口;当前 Start 可用性以
  506. // billing/balance 为准,缺失时刷新会把刚写入的 Start selectedKey 收敛回 Individual。
  507. sendJson(
  508. response,
  509. state.startPlanExpired
  510. ? {
  511. code: 0,
  512. msg: "ok",
  513. data: {
  514. server_time: Math.floor(Date.now() / 1000),
  515. plans: [],
  516. balances: [],
  517. },
  518. }
  519. : buildManualClaimStartPlanBalance(
  520. state.manualClaimCompleted,
  521. state.manualClaimBucketReady,
  522. ),
  523. );
  524. return;
  525. }
  526. if (request.method === "POST" && url.pathname === "/api/biz/pay/batch-preview") {
  527. if (state.scenario === "personal-system-busy") {
  528. // 修复原因:系统繁忙是接口整体失败语义,不能伪造成商品售罄。
  529. // 服务层会把 WAF/HTML 类不可展示响应收敛成 coding_plan_system_busy,再交给 UI 本地化。
  530. sendJson(response, {
  531. code: 503,
  532. msg: "<html>request has been blocked</html>",
  533. data: null,
  534. });
  535. return;
  536. }
  537. const personalProducts =
  538. state.clientConfigPayload.data.configs.codingPlanStaticProducts[
  539. BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan
  540. ] ?? [];
  541. sendJson(response, {
  542. code: 200,
  543. data: {
  544. isAuthenticated: true,
  545. isSubscribed: false,
  546. productList: personalProducts.map((product) => ({
  547. ...product,
  548. canPurchase: false,
  549. soldOut: true,
  550. })),
  551. },
  552. });
  553. return;
  554. }
  555. if (request.method === "GET" && url.pathname === "/api/monitor/usage/quota/limit") {
  556. if (state.scenario === "webview-refresh-provider") {
  557. sendJson(response, { code: 200, data: { level: "pro", limits: [] } });
  558. return;
  559. }
  560. if (state.scenario === "manual-claim-experience") {
  561. const nowSeconds = Math.floor(Date.now() / 1_000);
  562. sendJson(response, {
  563. code: 0,
  564. msg: "ok",
  565. data: {
  566. plans: [
  567. {
  568. plan_id: "weekend-plan-e2e",
  569. name: "ZCode Weekend Build",
  570. status: "active",
  571. starts_at: nowSeconds,
  572. ends_at: nowSeconds + 86_400,
  573. entitlements: [{ meter: "model_usage", period: "one_time" }],
  574. },
  575. ],
  576. balances: [
  577. {
  578. plan_id: "weekend-plan-e2e",
  579. entitlement_id: "weekend-glm-flash",
  580. show_name: "GLM-5.3-Flash",
  581. capabilities: ["model:glm-5.3-flash"],
  582. total_units: 10_000_000_000,
  583. used_units: 0,
  584. remaining_units: 10_000_000_000,
  585. available_units: 10_000_000_000,
  586. expires_at: nowSeconds + 86_400,
  587. },
  588. ],
  589. },
  590. });
  591. return;
  592. }
  593. // 修复原因:sidebar 升级入口通过 entitlement 判断账号是已连接但未开通套餐;
  594. // mock 必须用 HTTP 200 承载业务 no_plan,否则 readApiJson 会提前抛错,
  595. // 购买面板会被当成不可用账号并跳过 batch-preview。
  596. sendJson(response, {
  597. code: 404,
  598. msg: "当前用户不存在coding plan",
  599. data: null,
  600. });
  601. return;
  602. }
  603. if (request.method === "GET" && url.pathname === "/api/biz/subscription/list") {
  604. if (state.subscriptionListHeld)
  605. await new Promise<void>((resolve) => state.subscriptionListWaiters.push(resolve));
  606. sendJson(response, {
  607. code: 200,
  608. data:
  609. state.scenario === "webview-refresh-provider" ||
  610. (state.scenario === "manual-claim-experience" && state.manualClaimCompleted)
  611. ? [
  612. {
  613. productId: "glm-coding-pro-e2e",
  614. productName: "GLM Coding Pro",
  615. status: "VALID",
  616. inCurrentPeriod: true,
  617. },
  618. ]
  619. : [],
  620. });
  621. return;
  622. }
  623. if (request.method === "GET" && url.pathname === "/api/biz/customer/getCustomerInfo") {
  624. if (request.headers.authorization === "e2e-legacy-migration-business") {
  625. sendJson(response, {
  626. code: 200,
  627. data: { customerNumber: "e2e-business-customer", customerName: "Legacy Business Profile" },
  628. });
  629. return;
  630. }
  631. // 将单卡 provider 同步停在网络边界,验证全局查询已完成后的 Subscribe 加载反馈。
  632. if (state.customerInfoHeld) {
  633. await new Promise<void>((resolve) => state.customerInfoWaiters.push(resolve));
  634. }
  635. sendJson(response, {
  636. code: 200,
  637. data:
  638. state.purchaseCompleted ||
  639. // 营销升级先查询全部连接的权益;没有项目凭据会停在 unknown,无法打开升级页。
  640. // 只补可查询项目,不把“尚未领取”伪造成已有订阅。
  641. marketingTouch ||
  642. // 无套餐仍需可查询的项目凭据;空项目会让 Account State 变为 unknown,遮蔽订阅入口。
  643. state.scenario === "personal-sold-out" ||
  644. state.scenario === "personal-system-busy" ||
  645. // 当前账号服务通过组织/项目取得凭据;库存场景购买前已经拥有个人套餐,不能只伪造订阅列表。
  646. state.scenario === "webview-refresh-provider" ||
  647. (state.scenario === "manual-claim-experience" && state.manualClaimCompleted)
  648. ? {
  649. organizations: [
  650. {
  651. organizationId: "org-e2e",
  652. projects: [{ projectId: "proj-e2e", projectType: 0 }],
  653. },
  654. ],
  655. }
  656. : { organizations: [] },
  657. });
  658. return;
  659. }
  660. if (
  661. (request.method === "GET" || request.method === "POST") &&
  662. url.pathname === "/api/biz/v1/organization/org-e2e/projects/proj-e2e/api_keys"
  663. ) {
  664. if (request.method === "POST" && recordedRequest) {
  665. // 仅记录创建用途与名称,不把可能含凭据的任意请求体写入 E2E ledger。
  666. const { name, usageScene } = await readJsonBody<{
  667. name?: unknown;
  668. usageScene?: unknown;
  669. }>(request);
  670. recordedRequest.keyCreation = { name, usageScene };
  671. }
  672. sendJson(response, {
  673. code: 200,
  674. data: !state.purchaseCompleted
  675. ? request.method === "GET"
  676. ? [{ name: "zcode", apiKey: "bigmodel-personal-api-key" }]
  677. : { name: "zcode", apiKey: "bigmodel-personal-api-key" }
  678. : request.method === "GET"
  679. ? [{ name: "zcode", apiKey: "bigmodel-webview-refreshed-key" }]
  680. : { name: "zcode", apiKey: "bigmodel-webview-refreshed-key" },
  681. });
  682. return;
  683. }
  684. if (
  685. request.method === "POST" &&
  686. /^\/api\/biz\/v1\/organization\/org-e2e\/projects\/proj-e2e\/api_keys\/[^/]+\/access_tokens$/.test(
  687. url.pathname,
  688. )
  689. ) {
  690. const body = await readJsonBody<{ clientType?: string }>(request);
  691. if (body.clientType !== "zcode" || !request.headers.authorization?.startsWith("Bearer ")) {
  692. sendJson(response, { code: 400, msg: "invalid_token_request" });
  693. return;
  694. }
  695. const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
  696. const token = `${encode({ alg: "HS256", typ: "JWT", sign_type: "SIGN" })}.${encode({ token_use: "project_access", api_key: "e2e-key", exp: Math.floor(Date.now() / 1000) + 600 })}.e2e-signature`;
  697. sendJson(response, {
  698. code: 200,
  699. data: {
  700. enable: true,
  701. accessToken: token,
  702. tokenType: "Bearer",
  703. expiresIn: 600,
  704. expiresAt: Math.floor(Date.now() / 1000) + 600,
  705. },
  706. });
  707. return;
  708. }
  709. if (
  710. request.method === "GET" &&
  711. (url.pathname ===
  712. "/api/biz/v1/organization/org-e2e/projects/proj-e2e/api_keys/copy/bigmodel-webview-refreshed-key" ||
  713. url.pathname ===
  714. "/api/biz/v1/organization/org-e2e/projects/proj-e2e/api_keys/copy/bigmodel-personal-api-key")
  715. ) {
  716. sendJson(response, {
  717. code: 200,
  718. // Bug 原因:Z.ai 的 resolver 需要 copy secret,但 BigModel 的 apiKey 本身已是
  719. // 完整凭据。fixture 若无条件返回 Z.ai secret,会把 BigModel key 错拼成 key.secret。
  720. data: {
  721. secretKey:
  722. request.headers.authorization === "Bearer zai-webview-oauth-token"
  723. ? "zai-webview-refreshed-secret"
  724. : "",
  725. },
  726. });
  727. return;
  728. }
  729. if (request.method === "GET" && url.pathname === "/api/v1/off-peak/ticket/availability") {
  730. sendJson(response, { can_take_number: true });
  731. return;
  732. }
  733. if (state.highspeedOwnerRace && url.pathname === "/api/monitor/usage/model-performance-day") {
  734. sendJson(response, { code: 200, data: { proMaxDecodeSpeed: [25] } });
  735. return;
  736. }
  737. if (
  738. request.method === "GET" &&
  739. url.pathname === "/api/v1/highspeed/e2e-linked-highspeed/healthy"
  740. ) {
  741. if (state.highspeedHeld)
  742. await new Promise<void>((resolve) => state.highspeedWaiters.push(resolve));
  743. sendJson(response, {
  744. code: 0,
  745. msg: "ok",
  746. data: {
  747. card_id: "e2e-linked-highspeed",
  748. prompt_tokens: 1,
  749. completion_tokens: 100,
  750. duration_seconds: 2,
  751. },
  752. });
  753. return;
  754. }
  755. if (request.method === "POST" && url.pathname === "/api/v1/highspeed/draw") {
  756. const body = await readJsonBody<{ task_id: string; provider: string; model: string }>(request);
  757. if (state.highspeedHeld && !state.highspeedOwnerRace)
  758. await new Promise<void>((resolve) => state.highspeedWaiters.push(resolve));
  759. sendJson(response, {
  760. code: 0,
  761. msg: "ok",
  762. data: {
  763. card: {
  764. card_id: "e2e-linked-highspeed",
  765. task_id: body.task_id,
  766. provider: body.provider,
  767. model: body.model,
  768. issued_at: Date.now(),
  769. expires_at: Date.now() + state.highspeedLifetimeMs,
  770. },
  771. next_draw_at: Date.now() + 60_000,
  772. },
  773. });
  774. return;
  775. }
  776. if (request.method === "GET" && url.pathname === "/api/v1/coding-plan/reset/status") {
  777. sendJson(response, {
  778. code: 0,
  779. data: {
  780. available_five_hour_resets: [],
  781. available_week_resets: [],
  782. latest_five_hour_reset_history: null,
  783. latest_week_reset_history: null,
  784. has_unread_history: false,
  785. },
  786. });
  787. return;
  788. }
  789. if (request.method === "GET" && url.pathname === "/api/v1/mcp/usage") {
  790. sendJson(response, {
  791. code: 0,
  792. data: {
  793. server_time: Math.floor(Date.now() / 1000),
  794. total_usage: { used: 1, limit: 100, remaining: 99 },
  795. },
  796. });
  797. return;
  798. }
  799. if (
  800. request.method === "GET" &&
  801. (url.pathname === "/api/biz/subscription/enterprise/v2/pricing" ||
  802. url.pathname === "/api/biz/campaign/partner/enterprise/pricing")
  803. ) {
  804. if (url.pathname === "/api/biz/subscription/enterprise/v2/pricing") {
  805. if (state.inventoryMode === "hold")
  806. await new Promise<void>((resolve) => state.inventoryWaiters.push(resolve));
  807. if (state.inventoryMode === "fail") {
  808. sendJson(response, { code: 503, msg: "inventory unavailable" }, 503);
  809. return;
  810. }
  811. }
  812. sendJson(response, { code: 200, data: { productList: [] } });
  813. return;
  814. }
  815. sendJson(
  816. response,
  817. {
  818. code: 404,
  819. msg: `Unhandled E2E mock path: ${request.method} ${url.pathname}`,
  820. },
  821. 404,
  822. );
  823. }
  824. function createCodingPlanUpgradeMockState(
  825. basePayload: CodingPlanClientConfigFixture,
  826. scenario: CodingPlanUpgradeMockScenario,
  827. ): CodingPlanUpgradeMockState {
  828. const clientConfigPayload = structuredClone(basePayload);
  829. enrichClientConfigPayloadForUpgradeE2E(clientConfigPayload, scenario);
  830. return {
  831. clientConfigPayload,
  832. manualClaimBucketReady: false,
  833. manualClaimCompleted: false,
  834. manualClaimShouldFail: false,
  835. startPlanExpired: false,
  836. highspeedHeld: false,
  837. highspeedOwnerRace: false,
  838. highspeedLifetimeMs: 60_000,
  839. highspeedWaiters: [],
  840. associatedAuthMode: "off",
  841. associatedProfileHeld: false,
  842. associatedBusinessHeld: false,
  843. associatedBusinessWaiters: [],
  844. associatedProfileWaiters: [],
  845. subscriptionListHeld: false,
  846. subscriptionListWaiters: [],
  847. customerInfoHeld: false,
  848. customerInfoWaiters: [],
  849. inventoryMode: "ready",
  850. webviewMode: "ready",
  851. webviewWaiters: [],
  852. inventoryWaiters: [],
  853. purchaseCompleted: false,
  854. scenario,
  855. };
  856. }
  857. function buildManualClaimStartPlanBalance(claimed: boolean, newBucketReady: boolean) {
  858. const nowSeconds = Math.floor(Date.now() / 1_000);
  859. const oldPlanId = "zcode-v3-start-plan";
  860. const newPlanId = "weekend-plan-e2e";
  861. const oldPlan = {
  862. ends_at: nowSeconds + 4 * 86_400,
  863. entitlements: [
  864. {
  865. effective_at: 0,
  866. entitlement_id: "start-glm-turbo-e2e",
  867. show_name: "GLM-5-Turbo",
  868. },
  869. ],
  870. name: "ZCode V3 Start Plan",
  871. plan_id: oldPlanId,
  872. starts_at: nowSeconds - 86_400,
  873. status: "active",
  874. };
  875. const oldBalance = {
  876. available_units: 1_000_000_000,
  877. capabilities: ["model:glm-5-turbo"],
  878. entitlement_id: "start-glm-turbo-e2e",
  879. expires_at: nowSeconds + 4 * 86_400,
  880. plan_id: oldPlanId,
  881. remaining_units: 500_000_000,
  882. show_name: "GLM-5-Turbo",
  883. total_units: 1_000_000_000,
  884. used_units: 500_000_000,
  885. };
  886. const newPlan = {
  887. ends_at: nowSeconds + 86_400,
  888. entitlements: [
  889. {
  890. // 已到达排期时间但额度桶尚未生成,驱动设置页显示「刷新权益」。
  891. effective_at: nowSeconds - 60,
  892. entitlement_id: "weekend-glm-flash",
  893. show_name: "GLM-5.3-Flash",
  894. },
  895. ],
  896. name: "ZCode Weekend Build",
  897. plan_id: newPlanId,
  898. starts_at: nowSeconds - 60,
  899. status: "active",
  900. };
  901. const newBalance = {
  902. available_units: 10_000_000_000,
  903. capabilities: ["model:glm-5.3-flash"],
  904. entitlement_id: "weekend-glm-flash",
  905. expires_at: nowSeconds + 86_400,
  906. plan_id: newPlanId,
  907. remaining_units: 10_000_000_000,
  908. show_name: "GLM-5.3-Flash",
  909. total_units: 10_000_000_000,
  910. used_units: 0,
  911. };
  912. return {
  913. code: 0,
  914. data: {
  915. server_time: nowSeconds,
  916. balances: [oldBalance, ...(claimed && newBucketReady ? [newBalance] : [])],
  917. plans: [oldPlan, ...(claimed ? [newPlan] : [])],
  918. },
  919. msg: "ok",
  920. success: true,
  921. };
  922. }
  923. function isCodingPlanUpgradeMockScenario(value: unknown): value is CodingPlanUpgradeMockScenario {
  924. return (
  925. value === "manual-claim-experience" ||
  926. value === "personal-sold-out" ||
  927. value === "personal-system-busy" ||
  928. value === "webview-refresh-provider"
  929. );
  930. }
  931. async function readJsonBody<T>(request: IncomingMessage): Promise<T> {
  932. const chunks: Buffer[] = [];
  933. for await (const chunk of request) {
  934. chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  935. }
  936. const raw = Buffer.concat(chunks).toString("utf8").trim();
  937. return (raw ? JSON.parse(raw) : {}) as T;
  938. }
  939. function formatErrorMessage(error: unknown) {
  940. return error instanceof Error ? error.message : String(error);
  941. }
  942. interface CodingPlanClientConfigFixture {
  943. data: {
  944. builtinProviders?: Array<{
  945. id?: string;
  946. name?: string;
  947. schema?: string;
  948. baseUrl?: string;
  949. models?: string[];
  950. }>;
  951. builtinModels?: Array<{
  952. modelId: string;
  953. name?: string;
  954. contextWindow?: number;
  955. maxCompletionTokens?: number;
  956. priority?: number;
  957. }>;
  958. configs: {
  959. codingPlanStaticProducts: Partial<
  960. Record<
  961. string,
  962. Array<{
  963. productId: string;
  964. productName: string;
  965. priceUnit: "month" | "quarter" | "year";
  966. payAmount?: number;
  967. }>
  968. >
  969. >;
  970. };
  971. };
  972. }
  973. function enrichClientConfigPayloadForUpgradeE2E(
  974. payload: CodingPlanClientConfigFixture,
  975. scenario: CodingPlanUpgradeMockScenario,
  976. ) {
  977. if (scenario === "manual-claim-experience") {
  978. // Bug 原因:领取 fixture 需要同时下发 Individual 与 Start;且 BigModel OAuth
  979. // resolver 会从同 family 的远端列表选择首个 Anthropic provider,Individual 必须排在前面,
  980. // 否则会把 Start 模型错误复用到 Individual,无法覆盖真实切换链路。
  981. payload.data.builtinProviders = [
  982. {
  983. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan,
  984. name: "BigModel - Coding Plan",
  985. schema: "anthropic",
  986. baseUrl: "https://open.bigmodel.cn/api/anthropic",
  987. models: ["GLM-5.3-Flash"],
  988. },
  989. {
  990. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan,
  991. name: "BigModel - Start Plan",
  992. schema: "anthropic",
  993. baseUrl: "https://open.bigmodel.cn/api/anthropic",
  994. models: ["GLM-5.3-Flash", "GLM-5-Turbo"],
  995. },
  996. ];
  997. payload.data.builtinModels = [
  998. {
  999. modelId: "GLM-5-Turbo",
  1000. name: "GLM-5-Turbo",
  1001. contextWindow: 1_048_576,
  1002. maxCompletionTokens: 131_072,
  1003. priority: 101,
  1004. },
  1005. {
  1006. modelId: "GLM-5.3-Flash",
  1007. name: "GLM-5.3-Flash",
  1008. contextWindow: 1_048_576,
  1009. maxCompletionTokens: 131_072,
  1010. priority: 100,
  1011. },
  1012. ];
  1013. Object.assign(payload.data.configs, requestSecurityClientConfig());
  1014. return;
  1015. }
  1016. if (scenario !== "webview-refresh-provider") {
  1017. return;
  1018. }
  1019. payload.data.builtinProviders = [
  1020. {
  1021. id: "bigmodel",
  1022. name: "BigModel - Coding Plan",
  1023. schema: "anthropic",
  1024. baseUrl: "https://open.bigmodel.cn/api/anthropic",
  1025. models: ["glm-5.1-highspeed"],
  1026. },
  1027. {
  1028. id: "zai",
  1029. name: "Z.ai - Coding Plan",
  1030. schema: "anthropic",
  1031. baseUrl: "https://api.z.ai/api/anthropic",
  1032. models: ["glm-5.1-highspeed"],
  1033. },
  1034. ];
  1035. }
  1036. function buildCodingPlanWebviewFixtureHtml(scenario: CodingPlanUpgradeMockScenario): string {
  1037. const label =
  1038. scenario === "personal-system-busy"
  1039. ? "System busy"
  1040. : scenario === "personal-sold-out"
  1041. ? "Sold out"
  1042. : "Complete purchase";
  1043. return `<!doctype html>
  1044. <html>
  1045. <head>
  1046. <meta charset="utf-8" />
  1047. <title>Coding Plan E2E</title>
  1048. </head>
  1049. <body>
  1050. <main data-testid="coding-plan-webview-fixture">
  1051. <h1>Coding Plan E2E</h1>
  1052. <button id="complete" type="button">${label}</button>
  1053. </main>
  1054. <script>
  1055. document.getElementById("complete").addEventListener("click", async () => {
  1056. await fetch("/__e2e/coding-plan/purchase-complete", {
  1057. method: "POST",
  1058. keepalive: true
  1059. });
  1060. window.zcodeBridge.notifyPurchaseComplete({
  1061. provider: "bigmodel",
  1062. timestamp: Date.now()
  1063. });
  1064. });
  1065. </script>
  1066. </body>
  1067. </html>`;
  1068. }
  1069. function recordRequest(
  1070. requests: CodingPlanUpgradeMockRequest[],
  1071. request: IncomingMessage,
  1072. url: URL,
  1073. ) {
  1074. if (url.pathname === "/__e2e/coding-plan/requests") {
  1075. return;
  1076. }
  1077. const recorded: CodingPlanUpgradeMockRequest = {
  1078. method: request.method ?? "GET",
  1079. path: url.pathname,
  1080. query: Object.fromEntries(url.searchParams.entries()),
  1081. headers: Object.fromEntries(
  1082. Object.entries(request.headers).flatMap(([key, value]) => {
  1083. if (Array.isArray(value)) return [[key, value.join(",")]];
  1084. return typeof value === "string" ? [[key, value]] : [];
  1085. }),
  1086. ),
  1087. };
  1088. requests.push(recorded);
  1089. return recorded;
  1090. }
  1091. function sendHtml(response: ServerResponse, html: string) {
  1092. response.writeHead(200, {
  1093. "content-type": "text/html; charset=utf-8",
  1094. "cache-control": "no-store",
  1095. });
  1096. response.end(html);
  1097. }
  1098. function sendJson(response: ServerResponse, payload: unknown, statusCode = 200) {
  1099. response.writeHead(statusCode, {
  1100. "content-type": "application/json; charset=utf-8",
  1101. "cache-control": "no-store",
  1102. });
  1103. response.end(JSON.stringify(payload));
  1104. }