network-capture-proxy.ts 23 KB

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