Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
feat(inspector): add httpProxyServer + systemProxyConfig + agentBridgeHook (F4)
diegosouzapw62f2fdc4c1fd
diff --git a/src/mitm/inspector/agentBridgeHook.ts b/src/mitm/inspector/agentBridgeHook.tsnew file mode 100644index 0000000000..e247f38628--- /dev/null+++ b/src/mitm/inspector/agentBridgeHook.ts@@ -0,0 +1,100 @@+/**+ * Inspector hook called from `MitmHandlerBase` (F3) on every intercepted+ * AgentBridge request. Centralises buffer push/update so handlers do not need+ * to know the inspector internals.+ *+ * Contract: see `_orchestration/master-plan-group-A.md` §3.11.+ */++import { randomUUID } from "node:crypto";+import type { IncomingMessage } from "node:http";+import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";+import { maskSecret } from "../maskSecrets.ts";+import { sanitizeHeaders } from "../sanitizeHeaders.ts";+import type { AgentId } from "../types.ts";+import { globalTrafficBuffer } from "./buffer.ts";+import type { InterceptedRequest } from "./types.ts";++export interface RecordRequestStartOpts {+ req: IncomingMessage;+ body: Buffer;+ agentId: AgentId;+ mappedModel: string;+ sourceModel?: string | null;+ sessionId?: string;+}++export interface RecordRequestCompleteOpts {+ status: number;+ responseHeaders: Record<string, string>;+ responseBody: string | null;+ responseSize: number;+ proxyLatencyMs: number;+ upstreamLatencyMs: number;+}++/**+ * Build the initial buffer entry and push it. Returned object is mutable by+ * design — handlers call `recordRequestComplete()` (or `recordRequestError`)+ * with the same reference once the upstream call resolves.+ */+export async function recordRequestStart(+ opts: RecordRequestStartOpts+): Promise<InterceptedRequest> {+ const requestBody = opts.body.length > 0 ? maskSecret(opts.body.toString("utf8")) : null;+ const intercepted: InterceptedRequest = {+ id: randomUUID(),+ source: "agent-bridge",+ agent: opts.agentId,+ timestamp: new Date().toISOString(),+ method: opts.req.method ?? "GET",+ host: opts.req.headers.host ?? "",+ path: opts.req.url ?? "/",+ requestHeaders: sanitizeHeaders(opts.req.headers),+ requestBody,+ requestSize: opts.body.length,+ responseHeaders: {},+ responseBody: null,+ responseSize: 0,+ status: "in-flight",+ sourceModel: opts.sourceModel ?? null,+ mappedModel: opts.mappedModel,+ };+ if (opts.sessionId) intercepted.sessionId = opts.sessionId;++ globalTrafficBuffer.push(intercepted);+ return intercepted;+}++/**+ * Finalise the buffer entry with the upstream response data. Latencies are+ * stored as-given and combined into `totalLatencyMs`.+ */+export function recordRequestComplete(+ intercepted: InterceptedRequest,+ opts: RecordRequestCompleteOpts+): void {+ intercepted.status = opts.status;+ intercepted.responseHeaders = opts.responseHeaders;+ intercepted.responseBody =+ opts.responseBody != null ? maskSecret(opts.responseBody) : null;+ intercepted.responseSize = opts.responseSize;+ intercepted.proxyLatencyMs = opts.proxyLatencyMs;+ intercepted.upstreamLatencyMs = opts.upstreamLatencyMs;+ intercepted.totalLatencyMs = opts.proxyLatencyMs + opts.upstreamLatencyMs;++ globalTrafficBuffer.update(intercepted.id, intercepted);+}++/**+ * Mark the buffer entry as failed. Error messages are sanitized so stack+ * traces or absolute paths cannot leak to dashboards/exports (Hard Rule #12).+ */+export function recordRequestError(+ intercepted: InterceptedRequest,+ err: unknown+): void {+ intercepted.status = "error";+ intercepted.error = sanitizeErrorMessage(err);+ globalTrafficBuffer.update(intercepted.id, intercepted);+}diff --git a/src/mitm/inspector/httpProxyServer.ts b/src/mitm/inspector/httpProxyServer.tsnew file mode 100644index 0000000000..5fdb7dc80b--- /dev/null+++ b/src/mitm/inspector/httpProxyServer.ts@@ -0,0 +1,264 @@+/**+ * HTTP_PROXY listener for the Traffic Inspector.+ *+ * Accepts HTTP_PROXY=http://127.0.0.1:8080 style upstream traffic. Two paths:+ *+ * 1. HTTP direct (non-CONNECT): the proxy reads the request body, forwards+ * it via `fetch()`, captures the response, and records the full exchange.+ * 2. CONNECT (TLS tunnel): the proxy opens a raw TCP bridge so HTTPS still+ * works, but only metadata (host:port) is captured — bodies stay opaque.+ * The buffer entry carries a `note` field explaining why.+ *+ * `EADDRINUSE` during `listen()` rejects the returned promise so callers can+ * surface a clean error to the user. See master-plan §3.12 + plan 12 §4.2.6.+ */++import http from "node:http";+import net from "node:net";+import { randomUUID } from "node:crypto";+import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";+import { sanitizeHeaders } from "../sanitizeHeaders.ts";+import { maskSecret } from "../maskSecrets.ts";+import { globalTrafficBuffer } from "./buffer.ts";+import type { InterceptedRequest } from "./types.ts";++const DEFAULT_PORT = parseEnvNumber(process.env.INSPECTOR_HTTP_PROXY_PORT, 8080);++function parseEnvNumber(value: string | undefined, fallback: number): number {+ if (!value) return fallback;+ const parsed = Number(value);+ if (!Number.isFinite(parsed) || parsed <= 0) return fallback;+ return parsed;+}++export interface HttpProxyServerHandle {+ port: number;+ server: http.Server;+ stop(): Promise<void>;+}++/**+ * Build a sanitized Headers object suitable for an upstream `fetch()`.+ * Drops hop-by-hop fields via the existing denylist and coerces array values.+ */+function buildFetchHeaders(raw: http.IncomingHttpHeaders): Record<string, string> {+ // sanitizeHeaders applies upstream denylist + masks Authorization for buffer+ // logging; here we want denylist only (so the upstream still sees the auth+ // header). Reuse sanitizeHeaders with a separate masking pass for the buffer.+ const out: Record<string, string> = {};+ for (const [name, value] of Object.entries(raw)) {+ if (value === undefined || value === null) continue;+ const lower = name.toLowerCase();+ // Skip hop-by-hop / framing — same names sanitizeHeaders also drops.+ if (+ lower === "host" ||+ lower === "connection" ||+ lower === "keep-alive" ||+ lower === "proxy-authenticate" ||+ lower === "proxy-authorization" ||+ lower === "te" ||+ lower === "trailer" ||+ lower === "transfer-encoding" ||+ lower === "upgrade" ||+ lower === "content-length"+ ) {+ continue;+ }+ out[lower] = Array.isArray(value) ? value.join(", ") : String(value);+ }+ return out;+}++function safeUrl(rawUrl: string | undefined, hostHeader: string | undefined): URL | null {+ if (!rawUrl) return null;+ try {+ if (/^https?:\/\//i.test(rawUrl)) return new URL(rawUrl);+ if (hostHeader) return new URL(`http://${hostHeader}${rawUrl}`);+ } catch {+ return null;+ }+ return null;+}++async function readBody(req: http.IncomingMessage): Promise<Buffer> {+ const chunks: Buffer[] = [];+ for await (const chunk of req) {+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));+ }+ return Buffer.concat(chunks);+}++function handleHttp(req: http.IncomingMessage, res: http.ServerResponse): void {+ const startedAt = performance.now();+ const intercepted: InterceptedRequest = {+ id: randomUUID(),+ source: "http-proxy",+ timestamp: new Date().toISOString(),+ method: req.method ?? "GET",+ host: req.headers.host ?? "",+ path: req.url ?? "/",+ requestHeaders: sanitizeHeaders(req.headers),+ requestBody: null,+ requestSize: 0,+ responseHeaders: {},+ responseBody: null,+ responseSize: 0,+ status: "in-flight",+ };++ globalTrafficBuffer.push(intercepted);++ void (async () => {+ try {+ const target = safeUrl(req.url, req.headers.host);+ if (!target) {+ throw new Error("Invalid request URL");+ }+ intercepted.host = target.host;+ intercepted.path = target.pathname + target.search;++ const body = await readBody(req);+ intercepted.requestSize = body.length;+ intercepted.requestBody = body.length > 0 ? maskSecret(body.toString("utf8")) : null;++ const upstreamHeaders = buildFetchHeaders(req.headers);+ const upstream = await fetch(target.toString(), {+ method: req.method ?? "GET",+ headers: upstreamHeaders,+ body: body.length > 0 ? body : undefined,+ redirect: "manual",+ });++ const respBuf = Buffer.from(await upstream.arrayBuffer());+ const totalLatencyMs = performance.now() - startedAt;++ intercepted.responseHeaders = sanitizeHeaders(+ Object.fromEntries(upstream.headers) as Record<string, string>+ );+ intercepted.responseBody = maskSecret(respBuf.toString("utf8"));+ intercepted.responseSize = respBuf.length;+ intercepted.status = upstream.status;+ intercepted.totalLatencyMs = totalLatencyMs;+ intercepted.upstreamLatencyMs = totalLatencyMs;+ intercepted.proxyLatencyMs = 0;++ const safeRespHeaders: Record<string, string> = {};+ upstream.headers.forEach((value, key) => {+ if (key.toLowerCase() === "content-length") return;+ if (key.toLowerCase() === "transfer-encoding") return;+ safeRespHeaders[key] = value;+ });+ res.writeHead(upstream.status, safeRespHeaders);+ res.end(respBuf);++ globalTrafficBuffer.update(intercepted.id, intercepted);+ } catch (err) {+ intercepted.status = "error";+ intercepted.error = sanitizeErrorMessage(err);+ intercepted.totalLatencyMs = performance.now() - startedAt;+ globalTrafficBuffer.update(intercepted.id, intercepted);+ if (!res.headersSent) {+ res.writeHead(502, { "content-type": "text/plain" });+ res.end("Bad Gateway");+ } else {+ res.end();+ }+ }+ })();+}++function handleConnect(+ req: http.IncomingMessage,+ clientSocket: net.Socket,+ head: Buffer+): void {+ const target = req.url ?? "";+ const [host, rawPort] = target.split(":");+ const port = Number(rawPort) || 443;++ const intercepted: InterceptedRequest = {+ id: randomUUID(),+ source: "http-proxy",+ timestamp: new Date().toISOString(),+ method: "CONNECT",+ host,+ path: `:${port}`,+ requestHeaders: sanitizeHeaders(req.headers),+ requestBody: null,+ requestSize: 0,+ responseHeaders: {},+ responseBody: null,+ responseSize: 0,+ status: "in-flight",+ note: "TLS tunnel — for body capture, redirect host via Custom Hosts mode",+ };++ globalTrafficBuffer.push(intercepted);++ const targetSocket = net.connect(port, host);++ const finalize = (status: number | "error", err?: unknown): void => {+ intercepted.status = status;+ if (err !== undefined) intercepted.error = sanitizeErrorMessage(err);+ globalTrafficBuffer.update(intercepted.id, intercepted);+ };++ targetSocket.once("connect", () => {+ clientSocket.write("HTTP/1.1 200 Connection Established\r\n\r\n");+ if (head && head.length > 0) targetSocket.write(head);+ targetSocket.pipe(clientSocket);+ clientSocket.pipe(targetSocket);+ finalize(200);+ });++ const onError = (err: unknown): void => {+ finalize("error", err);+ try {+ clientSocket.end();+ } catch {+ // socket already closed+ }+ try {+ targetSocket.destroy();+ } catch {+ // already destroyed+ }+ };++ targetSocket.once("error", onError);+ clientSocket.once("error", onError);+}++/**+ * Start the HTTP_PROXY listener. Resolves with a handle once `listening` has+ * fired; rejects with `Error.code === "EADDRINUSE"` (and similar) when the+ * bind fails so callers can surface a clean error.+ */+export function startHttpProxyServer(port: number = DEFAULT_PORT): Promise<HttpProxyServerHandle> {+ return new Promise((resolve, reject) => {+ const server = http.createServer();++ server.on("request", (req, res) => handleHttp(req, res));+ server.on("connect", (req, socket, head) => handleConnect(req, socket as net.Socket, head));++ server.once("error", (err: NodeJS.ErrnoException) => {+ // Decorate with a code so callers can pattern-match without parsing strings.+ reject(Object.assign(err, { code: err.code ?? "ELISTEN" }));+ });++ server.once("listening", () => {+ const addr = server.address();+ const boundPort = typeof addr === "object" && addr ? addr.port : port;+ resolve({+ port: boundPort,+ server,+ stop: () =>+ new Promise<void>((res) => {+ server.close(() => res());+ }),+ });+ });++ server.listen(port, "127.0.0.1");+ });+}diff --git a/src/mitm/inspector/systemProxyConfig.ts b/src/mitm/inspector/systemProxyConfig.tsnew file mode 100644index 0000000000..2fbd3319e4--- /dev/null+++ b/src/mitm/inspector/systemProxyConfig.ts@@ -0,0 +1,314 @@+/**+ * System-wide proxy configuration toggles.+ *+ * macOS: `networksetup -setwebproxy / -setsecurewebproxy`+ * Linux: `gsettings set org.gnome.system.proxy.<scheme> host/port` + mode+ * Windows: `netsh winhttp set proxy <host:port>`+ *+ * Hard Rule #13: every shell invocation here uses `execFile` with an array of+ * arguments (never a shell string), so runtime values cannot be interpreted+ * as shell syntax.+ *+ * The returned `previousState` is JSON-serialisable so callers can persist it+ * (DB row) and pass it back to `revert()` later — including across process+ * restarts (the operator-facing "Restore system proxy" button).+ */++import { execFile, type ExecFileOptions } from "node:child_process";+import os from "node:os";+import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";++export type Platform = "linux" | "macos" | "windows";++export interface MacOsPreviousState {+ platform: "macos";+ service: string;+ http: { enabled: boolean; host: string; port: string };+ https: { enabled: boolean; host: string; port: string };+}++export interface LinuxPreviousState {+ platform: "linux";+ gnomeMode: string;+ httpHost: string;+ httpPort: string;+ httpsHost: string;+ httpsPort: string;+}++export interface WindowsPreviousState {+ platform: "windows";+ netshOutput: string;+}++export type PreviousState =+ | MacOsPreviousState+ | LinuxPreviousState+ | WindowsPreviousState;++export interface ApplyResult {+ platform: Platform;+ previousState: PreviousState;+}++// Injection seam for tests. Default implementation wraps node:child_process+// `execFile` so call-sites use array args (Hard Rule #13).+export type ExecFileFn = (+ file: string,+ args: string[],+ options?: ExecFileOptions+) => Promise<{ stdout: string; stderr: string }>;++let execImpl: ExecFileFn = defaultExec;++function defaultExec(+ file: string,+ args: string[],+ options: ExecFileOptions = {}+): Promise<{ stdout: string; stderr: string }> {+ return new Promise((resolve, reject) => {+ execFile(file, args, options, (err, stdout, stderr) => {+ if (err) {+ reject(err);+ return;+ }+ resolve({+ stdout: stdout?.toString() ?? "",+ stderr: stderr?.toString() ?? "",+ });+ });+ });+}++/**+ * Replace the underlying `execFile` runner (for tests).+ * Returns a `restore()` function that puts the default back.+ */+export function __setExec(fn: ExecFileFn): () => void {+ const prev = execImpl;+ execImpl = fn;+ return () => {+ execImpl = prev;+ };+}++function detectPlatform(): Platform {+ const p = os.platform();+ if (p === "darwin") return "macos";+ if (p === "win32") return "windows";+ return "linux";+}++// ────────────────────────────────────────────────────────────────────────────+// macOS — networksetup+// ────────────────────────────────────────────────────────────────────────────++const MAC_DEFAULT_SERVICE = "Wi-Fi";++interface NetworksetupRead {+ enabled: boolean;+ host: string;+ port: string;+}++function parseNetworksetupGet(output: string): NetworksetupRead {+ // Example output:+ // Enabled: Yes+ // Server: 192.168.1.1+ // Port: 3128+ // Authenticated Proxy Enabled: 0+ const lines = output.split(/\r?\n/);+ let enabled = false;+ let host = "";+ let port = "";+ for (const line of lines) {+ const m = line.match(/^(\S[^:]*):\s*(.*)$/);+ if (!m) continue;+ const key = m[1].trim().toLowerCase();+ const val = m[2].trim();+ if (key === "enabled") enabled = /yes/i.test(val);+ else if (key === "server") host = val;+ else if (key === "port") port = val;+ }+ return { enabled, host, port };+}++async function macosApply(port: number): Promise<MacOsPreviousState> {+ const service = MAC_DEFAULT_SERVICE;+ const httpGet = await execImpl("networksetup", ["-getwebproxy", service]);+ const httpsGet = await execImpl("networksetup", ["-getsecurewebproxy", service]);+ const previousState: MacOsPreviousState = {+ platform: "macos",+ service,+ http: parseNetworksetupGet(httpGet.stdout),+ https: parseNetworksetupGet(httpsGet.stdout),+ };++ await execImpl("networksetup", ["-setwebproxy", service, "127.0.0.1", String(port)]);+ await execImpl("networksetup", ["-setsecurewebproxy", service, "127.0.0.1", String(port)]);+ return previousState;+}++async function macosRevert(state: MacOsPreviousState): Promise<void> {+ const service = state.service;+ if (state.http.enabled && state.http.host && state.http.port) {+ await execImpl("networksetup", [+ "-setwebproxy",+ service,+ state.http.host,+ state.http.port,+ ]);+ } else {+ await execImpl("networksetup", ["-setwebproxystate", service, "off"]);+ }+ if (state.https.enabled && state.https.host && state.https.port) {+ await execImpl("networksetup", [+ "-setsecurewebproxy",+ service,+ state.https.host,+ state.https.port,+ ]);+ } else {+ await execImpl("networksetup", ["-setsecurewebproxystate", service, "off"]);+ }+}++// ────────────────────────────────────────────────────────────────────────────+// Linux — gsettings (GNOME); systems without gsettings are unsupported here.+// ────────────────────────────────────────────────────────────────────────────++async function readGsetting(key: string): Promise<string> {+ try {+ const { stdout } = await execImpl("gsettings", ["get", "org.gnome.system.proxy", key]);+ return stdout.trim();+ } catch {+ return "";+ }+}++async function readGsubsetting(+ scheme: string,+ key: string+): Promise<string> {+ try {+ const { stdout } = await execImpl("gsettings", [+ "get",+ `org.gnome.system.proxy.${scheme}`,+ key,+ ]);+ return stdout.trim();+ } catch {+ return "";+ }+}++async function linuxApply(port: number): Promise<LinuxPreviousState> {+ const previousState: LinuxPreviousState = {+ platform: "linux",+ gnomeMode: await readGsetting("mode"),+ httpHost: await readGsubsetting("http", "host"),+ httpPort: await readGsubsetting("http", "port"),+ httpsHost: await readGsubsetting("https", "host"),+ httpsPort: await readGsubsetting("https", "port"),+ };++ const portStr = String(port);+ await execImpl("gsettings", ["set", "org.gnome.system.proxy", "mode", "manual"]);+ await execImpl("gsettings", ["set", "org.gnome.system.proxy.http", "host", "127.0.0.1"]);+ await execImpl("gsettings", ["set", "org.gnome.system.proxy.http", "port", portStr]);+ await execImpl("gsettings", ["set", "org.gnome.system.proxy.https", "host", "127.0.0.1"]);+ await execImpl("gsettings", ["set", "org.gnome.system.proxy.https", "port", portStr]);+ return previousState;+}++async function linuxRevert(state: LinuxPreviousState): Promise<void> {+ const mode = state.gnomeMode || "'none'";+ await execImpl("gsettings", ["set", "org.gnome.system.proxy", "mode", mode]);+ if (state.httpHost) {+ await execImpl("gsettings", ["set", "org.gnome.system.proxy.http", "host", state.httpHost]);+ }+ if (state.httpPort) {+ await execImpl("gsettings", ["set", "org.gnome.system.proxy.http", "port", state.httpPort]);+ }+ if (state.httpsHost) {+ await execImpl("gsettings", [+ "set",+ "org.gnome.system.proxy.https",+ "host",+ state.httpsHost,+ ]);+ }+ if (state.httpsPort) {+ await execImpl("gsettings", [+ "set",+ "org.gnome.system.proxy.https",+ "port",+ state.httpsPort,+ ]);+ }+}++// ────────────────────────────────────────────────────────────────────────────+// Windows — netsh winhttp+// ────────────────────────────────────────────────────────────────────────────++async function windowsApply(port: number): Promise<WindowsPreviousState> {+ const showRes = await execImpl("netsh", ["winhttp", "show", "proxy"]);+ const previousState: WindowsPreviousState = {+ platform: "windows",+ netshOutput: showRes.stdout,+ };+ const proxyArg = `127.0.0.1:${String(port)}`;+ await execImpl("netsh", ["winhttp", "set", "proxy", proxyArg]);+ return previousState;+}++async function windowsRevert(_state: WindowsPreviousState): Promise<void> {+ // netsh has no idempotent restore; the safe default is "reset".+ // The previousState is preserved so the UI can show the operator what was+ // configured before, but actual reapply of obscure netsh state is out of+ // scope.+ await execImpl("netsh", ["winhttp", "reset", "proxy"]);+}++// ────────────────────────────────────────────────────────────────────────────+// Public API+// ────────────────────────────────────────────────────────────────────────────++/**+ * Apply OmniRoute as the system-wide HTTP/HTTPS proxy at `127.0.0.1:<port>`.+ * Captures and returns the prior configuration so callers can revert later.+ *+ * Throws a sanitized `Error` if the underlying command fails (no stack/path+ * leakage — see Hard Rule #12).+ */+export async function apply(port: number): Promise<ApplyResult> {+ const platform = detectPlatform();+ try {+ let previousState: PreviousState;+ if (platform === "macos") previousState = await macosApply(port);+ else if (platform === "windows") previousState = await windowsApply(port);+ else previousState = await linuxApply(port);+ return { platform, previousState };+ } catch (err) {+ throw new Error(sanitizeErrorMessage(err) || "system proxy apply failed");+ }+}++/**+ * Restore the prior configuration captured by `apply()`. No-op if the+ * `previousState` payload does not match a known platform.+ */+export async function revert(previousState: PreviousState | unknown): Promise<void> {+ if (!previousState || typeof previousState !== "object") return;+ const state = previousState as Record<string, unknown>;+ const platform = state.platform;+ try {+ if (platform === "macos") await macosRevert(state as unknown as MacOsPreviousState);+ else if (platform === "linux") await linuxRevert(state as unknown as LinuxPreviousState);+ else if (platform === "windows")+ await windowsRevert(state as unknown as WindowsPreviousState);+ } catch (err) {+ throw new Error(sanitizeErrorMessage(err) || "system proxy revert failed");+ }+}