network-capture.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. import { existsSync } from "node:fs";
  2. import type { IncomingHttpHeaders } from "node:http";
  3. import { basename, dirname, join, resolve } from "node:path";
  4. import { fileURLToPath } from "node:url";
  5. import { Proxy } from "http-mitm-proxy";
  6. import type { IContext } from "http-mitm-proxy";
  7. import type {
  8. NetworkCaptureEvent,
  9. NetworkCaptureStatus,
  10. NetworkRequestAttribution,
  11. NetworkRequestRecord,
  12. } from "../src/shared.js";
  13. interface NetworkCaptureServiceOptions {
  14. enabled?: boolean;
  15. host?: string;
  16. port?: number;
  17. caDir?: string;
  18. maxEntries?: number;
  19. }
  20. interface NetworkRequestListOptions {
  21. traceId?: string;
  22. limit?: number;
  23. }
  24. type NetworkCaptureListener = (event: NetworkCaptureEvent) => void;
  25. const DEFAULT_HOST = "127.0.0.1";
  26. const DEFAULT_PORT = 4184;
  27. const DEFAULT_MAX_ENTRIES = 300;
  28. const HEADER_REDACTION_VALUE = "[redacted]";
  29. const traceHeaderNames = ["x-zcode-trace-id", "x-trace-id", "traceparent"];
  30. const redactedHeaderNames = new Set([
  31. "authorization",
  32. "proxy-authorization",
  33. "cookie",
  34. "set-cookie",
  35. "x-api-key",
  36. "api-key",
  37. "openai-api-key",
  38. ]);
  39. export class NetworkCaptureService {
  40. readonly enabled: boolean;
  41. private readonly host: string;
  42. private readonly requestedPort: number;
  43. private readonly caDir: string;
  44. private readonly maxEntries: number;
  45. private readonly records = new Map<string, NetworkRequestRecord>();
  46. private readonly order: string[] = [];
  47. private readonly listeners = new Set<NetworkCaptureListener>();
  48. private proxy: Proxy | undefined;
  49. private running = false;
  50. private actualPort: number | undefined;
  51. private lastError: string | undefined;
  52. constructor(options: NetworkCaptureServiceOptions = {}) {
  53. this.enabled = options.enabled ?? true;
  54. this.host = options.host ?? DEFAULT_HOST;
  55. this.requestedPort = options.port ?? DEFAULT_PORT;
  56. this.caDir = resolve(options.caDir ?? defaultCertificateContainerDir());
  57. this.maxEntries = options.maxEntries ?? DEFAULT_MAX_ENTRIES;
  58. }
  59. async start(): Promise<void> {
  60. if (!this.enabled || this.running || this.proxy) return;
  61. const proxy = new Proxy();
  62. this.proxy = proxy;
  63. proxy.onError((ctx, error, errorKind) => {
  64. const message = [errorKind, error instanceof Error ? error.message : String(error)]
  65. .filter(Boolean)
  66. .join(": ");
  67. this.lastError = message || "network proxy error";
  68. this.markContextError(ctx, this.lastError);
  69. this.emit({ type: "status", status: this.getStatus() });
  70. });
  71. proxy.onRequest((ctx, callback) => {
  72. this.captureRequest(ctx);
  73. callback();
  74. });
  75. await new Promise<void>((resolveStart, rejectStart) => {
  76. proxy.listen(
  77. {
  78. host: this.host,
  79. port: this.requestedPort,
  80. sslCaDir: this.caDir,
  81. keepAlive: true,
  82. },
  83. (error?: Error | null) => {
  84. if (error) {
  85. this.lastError = error.message;
  86. this.proxy = undefined;
  87. rejectStart(error);
  88. return;
  89. }
  90. this.running = true;
  91. this.actualPort = proxy.httpPort;
  92. this.emit({ type: "status", status: this.getStatus() });
  93. resolveStart();
  94. },
  95. );
  96. });
  97. }
  98. async stop(): Promise<void> {
  99. const proxy = this.proxy;
  100. this.proxy = undefined;
  101. this.running = false;
  102. if (proxy) {
  103. await new Promise<void>((resolveStop) => {
  104. proxy.close();
  105. resolveStop();
  106. });
  107. }
  108. this.emit({ type: "status", status: this.getStatus() });
  109. }
  110. getStatus(): NetworkCaptureStatus {
  111. const port = this.actualPort ?? this.requestedPort;
  112. const url = this.enabled ? buildProxyUrl(this.host, port) : undefined;
  113. const caCertPath = join(this.caDir, "certs", "ca.pem");
  114. const env: Record<string, string> = url
  115. ? {
  116. ZCODE_HTTP_PROXY: url,
  117. ZCODE_AGENT_CA_CERT: caCertPath,
  118. }
  119. : {};
  120. return {
  121. enabled: this.enabled,
  122. running: this.running,
  123. host: this.enabled ? this.host : undefined,
  124. port: this.enabled ? port : undefined,
  125. proxyUrl: url,
  126. library: "http-mitm-proxy",
  127. maxEntries: this.maxEntries,
  128. certificate: {
  129. caDir: this.enabled ? this.caDir : undefined,
  130. caCertPath: this.enabled ? caCertPath : undefined,
  131. caPrivateKeyPath: this.enabled ? join(this.caDir, "keys", "ca.private.key") : undefined,
  132. caPublicKeyPath: this.enabled ? join(this.caDir, "keys", "ca.public.key") : undefined,
  133. caCertAvailable: existsSync(caCertPath),
  134. },
  135. env,
  136. lastError: this.lastError,
  137. };
  138. }
  139. listRequests(options: NetworkRequestListOptions = {}): NetworkRequestRecord[] {
  140. const limit = options.limit ?? this.maxEntries;
  141. const records: NetworkRequestRecord[] = [];
  142. for (const id of this.order.toReversed()) {
  143. const record = this.records.get(id);
  144. if (!record) continue;
  145. if (options.traceId && record.traceId !== options.traceId) continue;
  146. records.push(cloneRecord(record));
  147. if (records.length >= limit) break;
  148. }
  149. return records;
  150. }
  151. subscribe(listener: NetworkCaptureListener): () => void {
  152. this.listeners.add(listener);
  153. return () => {
  154. this.listeners.delete(listener);
  155. };
  156. }
  157. clear(): void {
  158. this.records.clear();
  159. this.order.length = 0;
  160. this.emit({ type: "reset" });
  161. }
  162. private captureRequest(ctx: IContext): void {
  163. const id = ctx.uuid;
  164. const requestUrl = buildRequestUrl(ctx);
  165. const attribution = extractAttribution(ctx.clientToProxyRequest.headers, requestUrl);
  166. const record: NetworkRequestRecord = {
  167. id,
  168. startedAt: new Date().toISOString(),
  169. protocol: ctx.isSSL ? "https" : "http",
  170. method: ctx.clientToProxyRequest.method ?? "GET",
  171. host: requestUrl.host,
  172. path: requestUrl.pathname + requestUrl.search,
  173. url: requestUrl.toString(),
  174. status: "pending",
  175. requestHeaders: sanitizeHeaders(ctx.clientToProxyRequest.headers),
  176. responseHeaders: {},
  177. requestHeaderCount: Object.keys(ctx.clientToProxyRequest.headers).length,
  178. responseHeaderCount: 0,
  179. requestBodyBytes: 0,
  180. responseBodyBytes: 0,
  181. ...attribution,
  182. };
  183. this.upsertRecord(record);
  184. if (ctx.tags) {
  185. ctx.tags.zcodeCaptureId = id;
  186. }
  187. ctx.onRequestData((requestCtx, chunk, callback) => {
  188. this.addRequestBytes(requestCtx, chunk.length);
  189. callback(null, chunk);
  190. });
  191. ctx.onResponse((responseCtx, callback) => {
  192. this.applyResponseHeaders(responseCtx);
  193. callback();
  194. });
  195. ctx.onResponseData((responseCtx, chunk, callback) => {
  196. this.addResponseBytes(responseCtx, chunk.length);
  197. callback(null, chunk);
  198. });
  199. ctx.onResponseEnd((responseCtx, callback) => {
  200. this.completeRecord(responseCtx);
  201. callback();
  202. });
  203. }
  204. private addRequestBytes(ctx: IContext, size: number): void {
  205. const record = this.recordForContext(ctx);
  206. if (!record) return;
  207. record.requestBodyBytes += size;
  208. }
  209. private addResponseBytes(ctx: IContext, size: number): void {
  210. const record = this.recordForContext(ctx);
  211. if (!record) return;
  212. record.responseBodyBytes += size;
  213. }
  214. private applyResponseHeaders(ctx: IContext): void {
  215. const record = this.recordForContext(ctx);
  216. if (!record || !ctx.serverToProxyResponse) return;
  217. record.statusCode = ctx.serverToProxyResponse.statusCode;
  218. record.responseHeaders = sanitizeHeaders(ctx.serverToProxyResponse.headers);
  219. record.responseHeaderCount = Object.keys(ctx.serverToProxyResponse.headers).length;
  220. }
  221. private completeRecord(ctx: IContext): void {
  222. const record = this.recordForContext(ctx);
  223. if (!record) return;
  224. this.applyResponseHeaders(ctx);
  225. record.status = "complete";
  226. record.completedAt = new Date().toISOString();
  227. record.durationMs = durationMs(record.startedAt, record.completedAt);
  228. this.upsertRecord(record);
  229. }
  230. private markContextError(ctx: IContext | null, message: string): void {
  231. const record = ctx ? this.recordForContext(ctx) : undefined;
  232. if (!record) return;
  233. record.status = "error";
  234. record.error = message;
  235. record.completedAt = new Date().toISOString();
  236. record.durationMs = durationMs(record.startedAt, record.completedAt);
  237. this.upsertRecord(record);
  238. }
  239. private recordForContext(ctx: IContext): NetworkRequestRecord | undefined {
  240. const id = stringValue(ctx.tags?.zcodeCaptureId) ?? ctx.uuid;
  241. return this.records.get(id);
  242. }
  243. private upsertRecord(record: NetworkRequestRecord): void {
  244. if (!this.records.has(record.id)) {
  245. this.order.push(record.id);
  246. }
  247. this.records.set(record.id, record);
  248. while (this.order.length > this.maxEntries) {
  249. const oldestId = this.order.shift();
  250. if (oldestId) this.records.delete(oldestId);
  251. }
  252. this.emit({ type: "request", request: cloneRecord(record) });
  253. }
  254. private emit(event: NetworkCaptureEvent): void {
  255. for (const listener of this.listeners) {
  256. listener(event);
  257. }
  258. }
  259. }
  260. export function disabledNetworkCaptureStatus(): NetworkCaptureStatus {
  261. return {
  262. enabled: false,
  263. running: false,
  264. library: "http-mitm-proxy",
  265. maxEntries: 0,
  266. certificate: {
  267. caCertAvailable: false,
  268. },
  269. env: {},
  270. };
  271. }
  272. export function createNetworkCaptureServiceFromEnv(
  273. env: NodeJS.ProcessEnv = process.env,
  274. ): NetworkCaptureService | undefined {
  275. if (isDisabled(env.ZCODE_DEBUG_NETWORK_CAPTURE)) return undefined;
  276. return new NetworkCaptureService({
  277. host: env.ZCODE_DEBUG_NETWORK_HOST || undefined,
  278. port: parsePositiveInteger(env.ZCODE_DEBUG_NETWORK_PORT) ?? DEFAULT_PORT,
  279. caDir: env.ZCODE_DEBUG_NETWORK_CA_DIR || undefined,
  280. maxEntries: parsePositiveInteger(env.ZCODE_DEBUG_NETWORK_MAX_ENTRIES) ?? DEFAULT_MAX_ENTRIES,
  281. });
  282. }
  283. function defaultCertificateContainerDir(): string {
  284. const moduleDir = dirname(fileURLToPath(import.meta.url));
  285. const parentDir = dirname(moduleDir);
  286. const debugRoot = basename(parentDir) === "dist-server" ? dirname(parentDir) : parentDir;
  287. return join(debugRoot, "certs", "network-ca");
  288. }
  289. export function extractAttribution(
  290. headers: IncomingHttpHeaders,
  291. url: URL,
  292. ): NetworkRequestAttribution {
  293. const traceId =
  294. firstHeader(headers, traceHeaderNames) ?? queryValue(url, ["traceId", "trace_id"]);
  295. return {
  296. traceId: normalizeTraceparent(traceId),
  297. };
  298. }
  299. export function sanitizeHeaders(headers: IncomingHttpHeaders): Record<string, string> {
  300. const sanitized: Record<string, string> = {};
  301. for (const [name, value] of Object.entries(headers)) {
  302. const normalizedName = name.toLowerCase();
  303. sanitized[normalizedName] = redactedHeaderNames.has(normalizedName)
  304. ? HEADER_REDACTION_VALUE
  305. : headerToString(value);
  306. }
  307. return sanitized;
  308. }
  309. function buildRequestUrl(ctx: IContext): URL {
  310. const request = ctx.clientToProxyRequest;
  311. const rawUrl = request.url ?? "/";
  312. if (/^https?:\/\//i.test(rawUrl)) {
  313. return new URL(rawUrl);
  314. }
  315. const protocol = ctx.isSSL ? "https" : "http";
  316. const host = stringValue(request.headers.host) ?? "unknown.local";
  317. const path = rawUrl.startsWith("/") ? rawUrl : `/${rawUrl}`;
  318. return new URL(`${protocol}://${host}${path}`);
  319. }
  320. function firstHeader(headers: IncomingHttpHeaders, names: string[]): string | undefined {
  321. for (const name of names) {
  322. const value = stringValue(headers[name]);
  323. if (value) return value;
  324. }
  325. return undefined;
  326. }
  327. function queryValue(url: URL, names: string[]): string | undefined {
  328. for (const name of names) {
  329. const value = url.searchParams.get(name);
  330. if (value) return value;
  331. }
  332. return undefined;
  333. }
  334. function normalizeTraceparent(value?: string): string | undefined {
  335. if (!value) return undefined;
  336. const parts = value.split("-");
  337. if (
  338. parts.length === 4 &&
  339. /^[\da-f]{2}$/i.test(parts[0] ?? "") &&
  340. /^[\da-f]{32}$/i.test(parts[1] ?? "") &&
  341. /^[\da-f]{16}$/i.test(parts[2] ?? "") &&
  342. /^[\da-f]{2}$/i.test(parts[3] ?? "")
  343. ) {
  344. return parts[1];
  345. }
  346. return value;
  347. }
  348. function headerToString(value: IncomingHttpHeaders[string]): string {
  349. if (Array.isArray(value)) return value.join(", ");
  350. return value === undefined ? "" : String(value);
  351. }
  352. function stringValue(value: unknown): string | undefined {
  353. if (Array.isArray(value)) return stringValue(value[0]);
  354. return typeof value === "string" && value.trim() ? value.trim() : undefined;
  355. }
  356. function durationMs(start: string, end: string): number {
  357. return Math.max(0, new Date(end).getTime() - new Date(start).getTime());
  358. }
  359. function parsePositiveInteger(value?: string): number | undefined {
  360. if (!value) return undefined;
  361. const parsed = Number(value);
  362. return Number.isInteger(parsed) && parsed > 0 ? parsed : undefined;
  363. }
  364. function isDisabled(value?: string): boolean {
  365. if (!value) return false;
  366. return ["0", "false", "off", "no"].includes(value.toLowerCase());
  367. }
  368. function buildProxyUrl(host: string, port: number): string {
  369. const formattedHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
  370. return `http://${formattedHost}:${port}`;
  371. }
  372. function cloneRecord(record: NetworkRequestRecord): NetworkRequestRecord {
  373. return {
  374. ...record,
  375. requestHeaders: { ...record.requestHeaders },
  376. responseHeaders: { ...record.responseHeaders },
  377. };
  378. }