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

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