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

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