network-capture-proxy.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. /* eslint-disable max-lines -- E2E 抓包代理需要集中维护 MITM、脱敏、chunk timeline、SSE event 解析和 artifact 序列化,拆开会让录制协议更难追踪。 */
  2. import { createPrivateKey, createPublicKey, X509Certificate } from "node:crypto";
  3. import { existsSync, readFileSync, writeFileSync } from "node:fs";
  4. import { readdir, readFile, rm } from "node:fs/promises";
  5. import { join, resolve } from "node:path";
  6. import { rootCertificates } from "node:tls";
  7. import {
  8. ZCODE_AGENT_CA_CERT_ENV_KEY,
  9. ZCODE_HTTP_PROXY_ENV_KEY,
  10. ZCODE_NO_PROXY_ENV_KEY,
  11. } from "@zcode/shared";
  12. import { Proxy } from "http-mitm-proxy";
  13. import type { IContext } from "http-mitm-proxy";
  14. import { writeE2EJsonFileAtomically } from "./e2e-atomic-json-file.js";
  15. import {
  16. redactE2ENetworkCaptureJson,
  17. redactE2ENetworkCaptureJsonText,
  18. sanitizeE2ENetworkCaptureHeaders,
  19. shouldRecordE2ENetworkResponseChunkTimeline,
  20. } from "./e2e-network-capture-redaction.js";
  21. const DEFAULT_RESPONSE_PREVIEW_BYTES = 64 * 1024;
  22. const DEFAULT_RESPONSE_CHUNK_TIMELINE_BYTES = 8 * 1024 * 1024;
  23. const DEFAULT_REQUEST_BODY_BYTES = 512 * 1024;
  24. export const DEFAULT_E2E_NETWORK_CAPTURE_NO_PROXY = [
  25. "localhost",
  26. "127.0.0.1",
  27. "::1",
  28. "js.stripe.com",
  29. "zcode.z.ai",
  30. // Plugin 商店原始图标 CDN 不需要进入模型请求抓包;直连也避免 Electron MITM 证书导致图片回退。
  31. "cdn-zcode.z.ai",
  32. "cdn.zcode-ai.com",
  33. ].join(",");
  34. export interface E2ENetworkCaptureRecord {
  35. completedAt?: string;
  36. durationMs?: number;
  37. error?: string;
  38. host: string;
  39. id: string;
  40. method: string;
  41. path: string;
  42. protocol: "http" | "https";
  43. requestBodyBytes: number;
  44. requestBodyTruncated?: boolean;
  45. requestHeaders: Record<string, string>;
  46. requestJson?: unknown;
  47. requestTextPreview?: string;
  48. replay?: {
  49. closeMode?: "end" | "destroy";
  50. fixtureId?: string;
  51. };
  52. responseBodyBytes: number;
  53. responseBodyTruncated?: boolean;
  54. responseChunkTimeline?: E2ENetworkResponseChunk[];
  55. responseChunkTimelineTruncated?: boolean;
  56. responseEvents?: E2ENetworkCaptureResponseEvent[];
  57. responseHeaders: Record<string, string>;
  58. responseTextPreview?: string;
  59. startedAt: string;
  60. status: "pending" | "complete" | "error";
  61. statusCode?: number;
  62. statusMessage?: string;
  63. url: string;
  64. }
  65. export interface E2ENetworkResponseChunk {
  66. base64: string;
  67. byteLength: number;
  68. offsetMs: number;
  69. }
  70. export interface E2ENetworkCaptureResponseEvent {
  71. byteLength: number;
  72. offsetMs: number;
  73. partial?: boolean;
  74. sequence: number;
  75. text: string;
  76. }
  77. export interface E2ENetworkCaptureArtifact {
  78. generatedAt: string;
  79. proxy: {
  80. caCertPath: string;
  81. host: string;
  82. port: number;
  83. proxyUrl: string;
  84. };
  85. records: E2ENetworkCaptureRecord[];
  86. version: 1;
  87. }
  88. export interface E2ENetworkCaptureProxy {
  89. artifactPath: string;
  90. caCertPath: string;
  91. env: Record<string, string>;
  92. proxyUrl: string;
  93. stop(): Promise<void>;
  94. }
  95. interface StartNetworkCaptureProxyOptions {
  96. artifactPath: string;
  97. caDir: string;
  98. host?: string;
  99. port?: number;
  100. requestBodyLimitBytes?: number;
  101. responseChunkTimelineLimitBytes?: number;
  102. responsePreviewLimitBytes?: number;
  103. recordResponseChunkTimeline?: boolean;
  104. responseMocks?: readonly E2ENetworkCaptureResponseMock[];
  105. requestRedirects?: readonly { host: string; path: string; targetUrl: string }[];
  106. }
  107. export interface E2ENetworkCaptureResponseMock {
  108. /** case-local 回放可按请求体选择固定响应,仍经真实 HTTPS/鉴权/SDK 路径。 */
  109. body: string | ((requestBody: string) => string);
  110. headers?: Record<string, string> | ((requestBody: string) => Record<string, string>);
  111. host?: string;
  112. method?: string;
  113. path: string;
  114. statusCode?: number;
  115. statusMessage?: string;
  116. }
  117. interface MutableCaptureRecord extends E2ENetworkCaptureRecord {
  118. requestChunks: Buffer[];
  119. responseChunkTimelineBytes: number;
  120. responseChunks: Buffer[];
  121. responseSseBuffer: string;
  122. responseSseStartedAtMs?: number;
  123. }
  124. export async function startE2ENetworkCaptureProxy(
  125. options: StartNetworkCaptureProxyOptions,
  126. ): Promise<E2ENetworkCaptureProxy> {
  127. const host = options.host ?? "127.0.0.1";
  128. const requestedPort = options.port ?? 0;
  129. const caDir = resolve(options.caDir);
  130. const artifactPath = resolve(options.artifactPath);
  131. const requestBodyLimitBytes = options.requestBodyLimitBytes ?? DEFAULT_REQUEST_BODY_BYTES;
  132. const recordResponseChunkTimeline = options.recordResponseChunkTimeline ?? false;
  133. const responseChunkTimelineLimitBytes =
  134. options.responseChunkTimelineLimitBytes ?? DEFAULT_RESPONSE_CHUNK_TIMELINE_BYTES;
  135. const responsePreviewLimitBytes =
  136. options.responsePreviewLimitBytes ?? DEFAULT_RESPONSE_PREVIEW_BYTES;
  137. await removeUnusableE2ENetworkCaptureLeafCertificates(caDir);
  138. const records = new Map<string, MutableCaptureRecord>();
  139. const order: string[] = [];
  140. const proxy = new Proxy();
  141. let artifactWriteQueue = Promise.resolve();
  142. const writeArtifact = () => {
  143. const artifact = {
  144. generatedAt: new Date().toISOString(),
  145. proxy: {
  146. caCertPath: join(caDir, "certs", "ca.pem"),
  147. host,
  148. port: proxy.httpPort,
  149. proxyUrl: buildProxyUrl(host, proxy.httpPort),
  150. },
  151. records: order
  152. .map((id) => records.get(id))
  153. .filter((record): record is MutableCaptureRecord => Boolean(record))
  154. .map(serializeRecord),
  155. version: 1,
  156. } satisfies E2ENetworkCaptureArtifact;
  157. // Proxy hooks 不能 await 文件 IO;把快照串行排队,并在边界处显式 flush。
  158. // 单次证据写失败只记录 warn,不能反向阻塞真实 provider 网络回调。
  159. artifactWriteQueue = artifactWriteQueue
  160. .catch(() => undefined)
  161. .then(() => writeE2EJsonFileAtomically(artifactPath, artifact))
  162. .catch((error: unknown) => {
  163. const message = error instanceof Error ? error.message : String(error);
  164. console.warn(`[e2e-network-capture] artifact write failed: ${message}`);
  165. });
  166. };
  167. proxy.onError((ctx, error, errorKind) => {
  168. const message = [errorKind, error instanceof Error ? error.message : String(error)]
  169. .filter(Boolean)
  170. .join(": ");
  171. markContextError(ctx, message || "network proxy error");
  172. writeArtifact();
  173. });
  174. proxy.onRequest((ctx, callback) => {
  175. const record = createRecord(ctx);
  176. records.set(record.id, record);
  177. order.push(record.id);
  178. tagContext(ctx, record.id);
  179. writeArtifact();
  180. ctx.onRequestData((requestCtx, chunk, dataCallback) => {
  181. const current = recordForContext(requestCtx);
  182. if (current) {
  183. current.requestBodyBytes += chunk.length;
  184. appendLimitedChunk(current.requestChunks, chunk, requestBodyLimitBytes);
  185. }
  186. dataCallback(null, chunk);
  187. });
  188. ctx.onRequestEnd((requestCtx, endCallback) => {
  189. const current = recordForContext(requestCtx);
  190. if (current) {
  191. applyRequestBody(current, requestBodyLimitBytes);
  192. writeArtifact();
  193. }
  194. endCallback();
  195. });
  196. ctx.onResponse((responseCtx, responseCallback) => {
  197. applyResponseHeaders(responseCtx);
  198. writeArtifact();
  199. responseCallback();
  200. });
  201. ctx.onResponseData((responseCtx, chunk, dataCallback) => {
  202. const current = recordForContext(responseCtx);
  203. if (current) {
  204. current.responseBodyBytes += chunk.length;
  205. appendLimitedChunk(current.responseChunks, chunk, responsePreviewLimitBytes);
  206. // 修复原因:部分接口的 JSON 响应含密钥密文;若录原始 base64 chunk,
  207. // 即使 text preview 已脱敏,密钥材料仍会旁路落盘。chunk timeline 只服务 SSE 回放。
  208. if (
  209. shouldRecordE2ENetworkResponseChunkTimeline(
  210. recordResponseChunkTimeline,
  211. current.responseHeaders,
  212. )
  213. ) {
  214. appendResponseTimelineChunk(current, chunk, responseChunkTimelineLimitBytes);
  215. }
  216. appendSseResponseEvents(current, chunk);
  217. }
  218. dataCallback(null, chunk);
  219. });
  220. ctx.onResponseEnd((responseCtx, endCallback) => {
  221. const current = recordForContext(responseCtx);
  222. if (current) {
  223. applyResponseHeaders(responseCtx);
  224. current.status = "complete";
  225. current.completedAt = new Date().toISOString();
  226. current.durationMs = durationMs(current.startedAt, current.completedAt);
  227. flushPartialSseResponseEvent(current);
  228. applyResponsePreview(current, responsePreviewLimitBytes);
  229. writeArtifact();
  230. }
  231. endCallback();
  232. });
  233. const redirect = options.requestRedirects?.find(
  234. (route) => route.host === record.host && route.path === new URL(record.url).pathname,
  235. );
  236. if (redirect) {
  237. // 账号用例仍请求真实 HTTPS 地址;测试代理只改下游目标,让受控流逐块经过原抓包链。
  238. // 固定 mock body 会提前结束 turn,使排队操作根本没有可观测的 running 窗口。
  239. const target = new URL(redirect.targetUrl);
  240. ctx.isSSL = target.protocol === "https:";
  241. const requestOptions = ctx.proxyToServerRequestOptions;
  242. if (!requestOptions) {
  243. callback(new Error("E2E replay redirect missing upstream request options"));
  244. return;
  245. }
  246. Object.assign(requestOptions, {
  247. host: target.hostname,
  248. port: target.port || (ctx.isSSL ? 443 : 80),
  249. path: `${target.pathname}${target.search}`,
  250. agent: undefined,
  251. headers: { ...requestOptions.headers, host: target.host },
  252. });
  253. callback();
  254. return;
  255. }
  256. const mockResponse = findResponseMock(record, options.responseMocks);
  257. if (mockResponse) {
  258. serveResponseMock(ctx, record, mockResponse);
  259. return;
  260. }
  261. callback();
  262. });
  263. await new Promise<void>((resolveStart, rejectStart) => {
  264. proxy.listen(
  265. {
  266. host,
  267. keepAlive: true,
  268. port: requestedPort,
  269. sslCaDir: caDir,
  270. },
  271. (error?: Error | null) => {
  272. if (error) {
  273. rejectStart(error);
  274. return;
  275. }
  276. resolveStart();
  277. },
  278. );
  279. });
  280. const caCertPath = join(caDir, "certs", "ca.pem");
  281. if (!existsSync(caCertPath)) {
  282. throw new Error(`E2E network capture CA was not generated: ${caCertPath}`);
  283. }
  284. const caBundlePath = writeCombinedCaBundle(caDir, caCertPath);
  285. writeArtifact();
  286. await artifactWriteQueue;
  287. const proxyUrl = buildProxyUrl(host, proxy.httpPort);
  288. const env = buildProxyEnv(proxyUrl, caCertPath, caBundlePath);
  289. return {
  290. artifactPath,
  291. caCertPath,
  292. env,
  293. proxyUrl,
  294. async stop() {
  295. proxy.close();
  296. writeArtifact();
  297. await artifactWriteQueue;
  298. },
  299. };
  300. function recordForContext(ctx: IContext): MutableCaptureRecord | undefined {
  301. const id = stringValue(ctx.tags?.zcodeCaptureId) ?? ctx.uuid;
  302. return records.get(id);
  303. }
  304. function markContextError(ctx: IContext | null, message: string) {
  305. if (!ctx) {
  306. return;
  307. }
  308. const current = recordForContext(ctx);
  309. if (!current) {
  310. return;
  311. }
  312. current.status = "error";
  313. current.error = message;
  314. current.completedAt = new Date().toISOString();
  315. current.durationMs = durationMs(current.startedAt, current.completedAt);
  316. }
  317. function applyResponseHeaders(ctx: IContext) {
  318. const current = recordForContext(ctx);
  319. if (!current || !ctx.serverToProxyResponse) {
  320. return;
  321. }
  322. current.statusCode = ctx.serverToProxyResponse.statusCode;
  323. current.statusMessage = ctx.serverToProxyResponse.statusMessage;
  324. current.responseHeaders = sanitizeE2ENetworkCaptureHeaders(ctx.serverToProxyResponse.headers);
  325. }
  326. function findResponseMock(
  327. record: E2ENetworkCaptureRecord,
  328. responseMocks: readonly E2ENetworkCaptureResponseMock[] | undefined,
  329. ) {
  330. const requestUrl = new URL(record.url);
  331. return responseMocks?.find(
  332. (mock) =>
  333. (mock.host === undefined || mock.host === requestUrl.host) &&
  334. (mock.method === undefined || mock.method === record.method) &&
  335. mock.path === requestUrl.pathname,
  336. );
  337. }
  338. function serveResponseMock(
  339. ctx: IContext,
  340. record: MutableCaptureRecord,
  341. mock: E2ENetworkCaptureResponseMock,
  342. ) {
  343. const requestChunks: Buffer[] = [];
  344. let requestBodyBytes = 0;
  345. const finish = () => {
  346. applyMockRequestBody(record, requestChunks, requestBodyBytes, requestBodyLimitBytes);
  347. const requestBody = Buffer.concat(requestChunks).toString("utf8");
  348. const body = Buffer.from(
  349. typeof mock.body === "function" ? mock.body(requestBody) : mock.body,
  350. "utf-8",
  351. );
  352. const responseHeaders = {
  353. "content-length": String(body.length),
  354. "content-type": "application/json; charset=utf-8",
  355. connection: "close",
  356. // 修复原因:同一模型端点同时处理普通 JSON 标题与 SSE;固定响应头会让 SDK 解析失败。
  357. ...(typeof mock.headers === "function" ? mock.headers(requestBody) : mock.headers),
  358. };
  359. ctx.proxyToClientResponse.writeHead(mock.statusCode ?? 200, responseHeaders);
  360. ctx.proxyToClientResponse.end(body);
  361. record.responseBodyBytes = body.length;
  362. record.responseHeaders = sanitizeE2ENetworkCaptureHeaders(responseHeaders);
  363. record.responseTextPreview = redactE2ENetworkCaptureJsonText(body.toString("utf-8"));
  364. record.status = "complete";
  365. record.statusCode = mock.statusCode ?? 200;
  366. record.statusMessage = mock.statusMessage ?? "OK";
  367. record.completedAt = new Date().toISOString();
  368. record.durationMs = durationMs(record.startedAt, record.completedAt);
  369. writeArtifact();
  370. };
  371. // 未调用 callback() 时 http-mitm-proxy 不会替我们消费请求流;主动 drain,
  372. // 避免客户端在发送控制面 POST body 时因 backpressure 卡住。
  373. ctx.clientToProxyRequest.on("data", (chunk: Buffer) => {
  374. requestBodyBytes += chunk.length;
  375. appendLimitedChunk(requestChunks, chunk, requestBodyLimitBytes);
  376. });
  377. ctx.clientToProxyRequest.once("end", finish);
  378. ctx.clientToProxyRequest.resume();
  379. }
  380. }
  381. function applyMockRequestBody(
  382. record: MutableCaptureRecord,
  383. chunks: Buffer[],
  384. bodyBytes: number,
  385. limitBytes: number,
  386. ) {
  387. record.requestBodyBytes = bodyBytes;
  388. record.requestBodyTruncated = bodyBytes > limitBytes;
  389. const body = Buffer.concat(chunks);
  390. if (body.length === 0) {
  391. return;
  392. }
  393. const text = body.toString("utf-8");
  394. try {
  395. record.requestJson = redactE2ENetworkCaptureJson(JSON.parse(text));
  396. } catch {
  397. record.requestTextPreview = text;
  398. }
  399. }
  400. export async function removeUnusableE2ENetworkCaptureLeafCertificates(
  401. caDir: string,
  402. now = new Date(),
  403. ): Promise<void> {
  404. const certsDir = join(caDir, "certs");
  405. let certificateNames: string[];
  406. try {
  407. certificateNames = await readdir(certsDir);
  408. } catch (error) {
  409. if (isFileSystemError(error, "ENOENT")) {
  410. return;
  411. }
  412. throw error;
  413. }
  414. await Promise.all(
  415. certificateNames
  416. .filter((name) => name.endsWith(".pem") && name !== "ca.pem" && name !== "ca-bundle.pem")
  417. .map(async (name) => {
  418. const certificatePath = join(certsDir, name);
  419. const host = name.slice(0, -".pem".length);
  420. const privateKeyPath = join(caDir, "keys", `${host}.key`);
  421. let usable = false;
  422. try {
  423. const certificate = new X509Certificate(await readFile(certificatePath, "utf8"));
  424. const certificatePublicKey = certificate.publicKey.export({
  425. format: "der",
  426. type: "spki",
  427. });
  428. const privateKeyPublicKey = createPublicKey(
  429. createPrivateKey(await readFile(privateKeyPath)),
  430. ).export({
  431. format: "der",
  432. type: "spki",
  433. });
  434. usable =
  435. Date.parse(certificate.validFrom) <= now.getTime() &&
  436. Date.parse(certificate.validTo) > now.getTime() &&
  437. certificatePublicKey.equals(privateKeyPublicKey);
  438. } catch {
  439. usable = false;
  440. }
  441. if (usable) {
  442. return;
  443. }
  444. // 修复原因:http-mitm-proxy 会长期复用域名叶子证书,过期或并发生成中断后还可能
  445. // 留下证书/私钥不匹配;删除不可用叶子,让下一次 CONNECT 按现有 CA 重新生成。
  446. await Promise.all([
  447. rm(certificatePath, { force: true }),
  448. rm(privateKeyPath, { force: true }),
  449. rm(join(caDir, "keys", `${host}.public.key`), { force: true }),
  450. ]);
  451. }),
  452. );
  453. }
  454. function isFileSystemError(error: unknown, code: string): boolean {
  455. return Boolean(
  456. error &&
  457. typeof error === "object" &&
  458. "code" in error &&
  459. (error as { code?: unknown }).code === code,
  460. );
  461. }
  462. function createRecord(ctx: IContext): MutableCaptureRecord {
  463. const requestUrl = buildRequestUrl(ctx);
  464. return {
  465. host: requestUrl.host,
  466. id: ctx.uuid,
  467. method: ctx.clientToProxyRequest.method ?? "GET",
  468. path: requestUrl.pathname + requestUrl.search,
  469. protocol: ctx.isSSL ? "https" : "http",
  470. requestBodyBytes: 0,
  471. requestChunks: [],
  472. requestHeaders: sanitizeE2ENetworkCaptureHeaders(ctx.clientToProxyRequest.headers),
  473. responseBodyBytes: 0,
  474. responseChunkTimelineBytes: 0,
  475. responseChunks: [],
  476. responseSseBuffer: "",
  477. responseHeaders: {},
  478. startedAt: new Date().toISOString(),
  479. status: "pending",
  480. url: requestUrl.toString(),
  481. };
  482. }
  483. function appendSseResponseEvents(record: MutableCaptureRecord, chunk: Buffer) {
  484. if (!isSseResponse(record)) {
  485. return;
  486. }
  487. // 修复原因:SSE 自动化需要稳定的 event 语义和相对时间,TCP chunk 边界不可复现。
  488. // 这里累积文本后按 SSE 空行分隔符吐出完整 event。
  489. if (record.responseSseStartedAtMs === undefined) {
  490. record.responseSseStartedAtMs = Date.now();
  491. }
  492. record.responseSseBuffer += chunk.toString("utf-8");
  493. drainCompleteSseEvents(record, false);
  494. }
  495. function flushPartialSseResponseEvent(record: MutableCaptureRecord) {
  496. if (!isSseResponse(record) || record.responseSseBuffer.length === 0) {
  497. return;
  498. }
  499. drainCompleteSseEvents(record, true);
  500. }
  501. function drainCompleteSseEvents(record: MutableCaptureRecord, flushPartial: boolean) {
  502. while (record.responseSseBuffer.length > 0) {
  503. const boundary = findSseEventBoundary(record.responseSseBuffer);
  504. if (!boundary) {
  505. if (flushPartial) {
  506. pushSseEvent(record, record.responseSseBuffer, true);
  507. record.responseSseBuffer = "";
  508. }
  509. return;
  510. }
  511. const text = record.responseSseBuffer.slice(0, boundary.endIndex);
  512. record.responseSseBuffer = record.responseSseBuffer.slice(boundary.endIndex);
  513. pushSseEvent(record, text, false);
  514. }
  515. }
  516. function pushSseEvent(record: MutableCaptureRecord, text: string, partial: boolean) {
  517. const startedAtMs = record.responseSseStartedAtMs ?? Date.now();
  518. record.responseEvents ??= [];
  519. record.responseEvents.push({
  520. byteLength: Buffer.byteLength(text, "utf-8"),
  521. offsetMs: Math.max(0, Date.now() - startedAtMs),
  522. ...(partial ? { partial: true } : {}),
  523. sequence: record.responseEvents.length,
  524. text,
  525. });
  526. }
  527. function findSseEventBoundary(text: string): { endIndex: number } | null {
  528. const candidates = ["\r\n\r\n", "\n\n", "\r\r"]
  529. .map((separator) => {
  530. const index = text.indexOf(separator);
  531. return index < 0 ? null : { endIndex: index + separator.length };
  532. })
  533. .filter((candidate): candidate is { endIndex: number } => Boolean(candidate))
  534. .sort((left, right) => left.endIndex - right.endIndex);
  535. return candidates[0] ?? null;
  536. }
  537. function isSseResponse(record: Pick<E2ENetworkCaptureRecord, "responseHeaders">): boolean {
  538. return (
  539. record.responseHeaders["content-type"]?.toLowerCase().includes("text/event-stream") ?? false
  540. );
  541. }
  542. function tagContext(ctx: IContext, id: string) {
  543. // 修复原因:http-mitm-proxy 的同一个请求会跨多个回调阶段流转,e2e 需要用
  544. // 稳定 id 把 request/response 数据合并到同一条 artifact 记录。
  545. const tags = (ctx.tags ?? {}) as IContext["tags"] & { zcodeCaptureId?: string };
  546. tags.zcodeCaptureId = id;
  547. ctx.tags = tags;
  548. }
  549. function buildRequestUrl(ctx: IContext): URL {
  550. const rawUrl = ctx.clientToProxyRequest.url ?? "/";
  551. if (/^https?:\/\//i.test(rawUrl)) {
  552. return new URL(rawUrl);
  553. }
  554. const protocol = ctx.isSSL ? "https" : "http";
  555. const host = stringValue(ctx.clientToProxyRequest.headers.host) ?? "unknown.local";
  556. const path = rawUrl.startsWith("/") ? rawUrl : `/${rawUrl}`;
  557. return new URL(`${protocol}://${host}${path}`);
  558. }
  559. function applyRequestBody(record: MutableCaptureRecord, limitBytes: number) {
  560. const body = Buffer.concat(record.requestChunks);
  561. record.requestBodyTruncated = record.requestBodyBytes > limitBytes;
  562. if (body.length === 0) {
  563. return;
  564. }
  565. const text = body.toString("utf-8");
  566. try {
  567. record.requestJson = redactE2ENetworkCaptureJson(JSON.parse(text));
  568. } catch {
  569. record.requestTextPreview = text;
  570. }
  571. }
  572. function applyResponsePreview(record: MutableCaptureRecord, limitBytes: number) {
  573. const body = Buffer.concat(record.responseChunks);
  574. record.responseBodyTruncated = record.responseBodyBytes > limitBytes;
  575. if (body.length > 0) {
  576. record.responseTextPreview = redactE2ENetworkCaptureJsonText(body.toString("utf-8"));
  577. }
  578. }
  579. function appendLimitedChunk(chunks: Buffer[], chunk: Buffer, limitBytes: number) {
  580. const currentBytes = chunks.reduce((total, item) => total + item.length, 0);
  581. if (currentBytes >= limitBytes) {
  582. return;
  583. }
  584. const remaining = limitBytes - currentBytes;
  585. chunks.push(chunk.length > remaining ? chunk.subarray(0, remaining) : Buffer.from(chunk));
  586. }
  587. function appendResponseTimelineChunk(
  588. record: MutableCaptureRecord,
  589. chunk: Buffer,
  590. limitBytes: number,
  591. ) {
  592. if (!record.responseChunkTimeline) {
  593. record.responseChunkTimeline = [];
  594. }
  595. if (record.responseChunkTimelineBytes >= limitBytes) {
  596. record.responseChunkTimelineTruncated = true;
  597. return;
  598. }
  599. const remainingBytes = limitBytes - record.responseChunkTimelineBytes;
  600. const storedChunk = chunk.length > remainingBytes ? chunk.subarray(0, remainingBytes) : chunk;
  601. record.responseChunkTimeline.push({
  602. base64: Buffer.from(storedChunk).toString("base64"),
  603. byteLength: chunk.length,
  604. offsetMs: Math.max(0, Date.now() - Date.parse(record.startedAt)),
  605. });
  606. record.responseChunkTimelineBytes += storedChunk.length;
  607. if (storedChunk.length < chunk.length) {
  608. record.responseChunkTimelineTruncated = true;
  609. }
  610. }
  611. function serializeRecord(record: MutableCaptureRecord): E2ENetworkCaptureRecord {
  612. const {
  613. requestChunks: _requestChunks,
  614. responseChunkTimelineBytes: _responseChunkTimelineBytes,
  615. responseChunks: _responseChunks,
  616. responseSseBuffer: _responseSseBuffer,
  617. responseSseStartedAtMs: _responseSseStartedAtMs,
  618. ...serialized
  619. } = record;
  620. return serialized;
  621. }
  622. function writeCombinedCaBundle(caDir: string, caCertPath: string): string {
  623. const caBundlePath = join(caDir, "certs", "ca-bundle.pem");
  624. const configuredCaFiles = [
  625. ...new Set(
  626. [process.env.NODE_EXTRA_CA_CERTS, process.env.SSL_CERT_FILE]
  627. .map((path) => path?.trim())
  628. .filter((path): path is string => Boolean(path)),
  629. ),
  630. ].filter((path) => existsSync(path));
  631. const certificates = [
  632. ...rootCertificates,
  633. ...configuredCaFiles.map((path) => readFileSync(path, "utf-8")),
  634. readFileSync(caCertPath, "utf-8"),
  635. ];
  636. // 修复原因:只把 MITM CA 写入 SSL_CERT_FILE 会覆盖 Node 的公共根证书,
  637. // 抓包代理随后访问真实上游时会误报 self-signed certificate in certificate chain。
  638. writeFileSync(
  639. caBundlePath,
  640. `${certificates.map((certificate) => certificate.trim()).join("\n")}\n`,
  641. "utf-8",
  642. );
  643. return caBundlePath;
  644. }
  645. function buildProxyEnv(
  646. proxyUrl: string,
  647. caCertPath: string,
  648. caBundlePath: string,
  649. ): Record<string, string> {
  650. const noProxy = DEFAULT_E2E_NETWORK_CAPTURE_NO_PROXY;
  651. return {
  652. ALL_PROXY: proxyUrl,
  653. all_proxy: proxyUrl,
  654. CURL_CA_BUNDLE: caBundlePath,
  655. GIT_SSL_CAINFO: caBundlePath,
  656. HTTPS_PROXY: proxyUrl,
  657. https_proxy: proxyUrl,
  658. HTTP_PROXY: proxyUrl,
  659. http_proxy: proxyUrl,
  660. NODE_EXTRA_CA_CERTS: caBundlePath,
  661. NO_PROXY: noProxy,
  662. no_proxy: noProxy,
  663. REQUESTS_CA_BUNDLE: caBundlePath,
  664. SSL_CERT_FILE: caBundlePath,
  665. // Bugfix: agent provider fetch 会过滤标准 HTTP_PROXY/HTTPS_PROXY,只认
  666. // ZCode 显式网络出口配置;否则真实模型请求会直连上游,capture artifact 为空。
  667. [ZCODE_AGENT_CA_CERT_ENV_KEY]: caCertPath,
  668. [ZCODE_HTTP_PROXY_ENV_KEY]: proxyUrl,
  669. [ZCODE_NO_PROXY_ENV_KEY]: noProxy,
  670. };
  671. }
  672. function buildProxyUrl(host: string, port: number): string {
  673. return `http://${host}:${port}`;
  674. }
  675. function durationMs(startedAt: string, completedAt: string): number {
  676. return Math.max(0, Date.parse(completedAt) - Date.parse(startedAt));
  677. }
  678. function stringValue(value: string | string[] | number | undefined): string | undefined {
  679. if (Array.isArray(value)) {
  680. return value[0];
  681. }
  682. if (value === undefined) {
  683. return undefined;
  684. }
  685. return String(value);
  686. }