network-capture.ts 13 KB

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