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(mitm): add types, masking, passthrough, upstream-trust (F1)
diegosouzapw898f2f21c443
diff --git a/src/mitm/maskSecrets.ts b/src/mitm/maskSecrets.tsnew file mode 100644index 0000000000..f0e9f90865--- /dev/null+++ b/src/mitm/maskSecrets.ts@@ -0,0 +1,25 @@+/**+ * Secret masking utilities for MITM traffic inspection.+ * Applied to all headers/bodies before any log or broadcast.+ * Regex patterns are pre-compiled (order matters: BEARER first).+ *+ * Pattern sources: plano 11 §4.8 (origin: llm-interceptor proxy.py:310)+ */++// Pre-compiled regex patterns — ORDER IS SIGNIFICANT (BEARER must run first)+const BEARER = /(authorization:\s*Bearer\s+)[A-Za-z0-9._-]+/gi;+const SK_KEY = /\b(sk|ak|pk)-[A-Za-z0-9_-]{16,}\b/g;+const LONG_TOKEN = /\b[A-Za-z0-9_-]{40,}\b/g;++/**+ * Mask secrets in a string value.+ * - Bearer tokens: replaces token after "Bearer " with "***"+ * - sk-/ak-/pk- keys: keeps first 6 chars + last 2 chars+ * - Long opaque tokens (≥40 chars): keeps first 4 chars + last 2 chars+ */+export function maskSecret(value: string): string {+ return value+ .replace(BEARER, "$1***")+ .replace(SK_KEY, (m) => `${m.slice(0, 6)}…${m.slice(-2)}`)+ .replace(LONG_TOKEN, (m) => `${m.slice(0, 4)}…${m.slice(-2)}`);+}diff --git a/src/mitm/passthrough.ts b/src/mitm/passthrough.tsnew file mode 100644index 0000000000..4d125d408e--- /dev/null+++ b/src/mitm/passthrough.ts@@ -0,0 +1,76 @@+/**+ * Passthrough / bypass logic for the MITM server.+ * Determines which hostnames should be tunneled without TLS decryption.+ *+ * Precedence: bypass list > target match > passthrough default.+ * Source: plano 11 §4.6 (origin: llm-interceptor filters.py::ignore_hosts)+ */++/**+ * Built-in bypass patterns — hosts that must NEVER be TLS-decrypted.+ * Banks, government sites, and corporate SSO providers.+ */+export const DEFAULT_BYPASS_PATTERNS: RegExp[] = [+ /\.bank\./i,+ /(^|\.)gov(\.|$)/i,+ /(^|\.)okta\.com$/i,+ /(^|\.)auth0\.com$/i,+];++/**+ * Match a hostname against a simple glob pattern (only * as wildcard, no ** or ?).+ * Implemented without RegExp to avoid ReDoS on user-supplied patterns (CWE-1333).+ * Uses a linear split-and-check algorithm: split by '*', verify each segment appears+ * in order within the lowercase hostname.+ */+export function globMatch(hostname: string, pattern: string): boolean {+ // Guard: reject patterns with more than 8 segments (after split) to bound complexity+ const segments = pattern.toLowerCase().split("*");+ if (segments.length > 9) return false;++ const h = hostname.toLowerCase();++ // No wildcard — exact match+ if (segments.length === 1) return h === segments[0];++ // Must start with the first segment (if non-empty)+ const first = segments[0];+ if (first && !h.startsWith(first)) return false;++ // Must end with the last segment (if non-empty)+ const last = segments[segments.length - 1];+ if (last && !h.endsWith(last)) return false;++ // Walk through middle segments verifying each appears after the previous match+ let pos = first.length;+ for (let i = 1; i < segments.length - 1; i++) {+ const seg = segments[i];+ if (seg === "") continue; // consecutive wildcards — skip+ const idx = h.indexOf(seg, pos);+ if (idx === -1) return false;+ pos = idx + seg.length;+ }++ // Ensure the last fixed segment doesn't overlap with middle matches+ if (last) {+ const minEnd = pos + last.length;+ if (minEnd > h.length) return false;+ }++ return true;+}++/**+ * Determine if a hostname should be bypassed (tunneled without TLS decryption).+ *+ * @param hostname - The target hostname (SNI or Host header value)+ * @param userBypass - User-configured bypass patterns (glob strings or regexes)+ * @returns true if the hostname should be tunneled without inspection+ */+export function shouldBypass(hostname: string, userBypass: string[]): boolean {+ // Default bypass patterns take precedence+ if (DEFAULT_BYPASS_PATTERNS.some((re) => re.test(hostname))) return true;++ // User-defined bypass patterns (glob strings)+ return userBypass.some((p) => globMatch(hostname, p));+}diff --git a/src/mitm/sanitizeHeaders.ts b/src/mitm/sanitizeHeaders.tsnew file mode 100644index 0000000000..1689841108--- /dev/null+++ b/src/mitm/sanitizeHeaders.ts@@ -0,0 +1,55 @@+import type { IncomingHttpHeaders } from "node:http";+import { isForbiddenUpstreamHeaderName } from "@/shared/constants/upstreamHeaders";+import { maskSecret } from "./maskSecrets";++/**+ * Header names whose values must be masked (case-insensitive).+ * These carry credentials/tokens that must not appear in logs or broadcasts.+ */+const SECRET_HEADER_NAMES = new Set([+ "authorization",+ "cookie",+ "x-api-key",+ "api-key",+ "bearer",+ "proxy-authorization",+]);++function isSecretHeader(name: string): boolean {+ return SECRET_HEADER_NAMES.has(name.toLowerCase());+}++/**+ * Sanitize HTTP headers for safe logging/broadcasting.+ *+ * - Removes headers in the upstream denylist (hop-by-hop, Host, etc.)+ * - Applies maskSecret() to values of authorization/cookie/key headers+ * - Coerces array values to comma-joined strings+ * - Returns a plain Record<string, string> (never undefined values)+ */+export function sanitizeHeaders(+ headers: IncomingHttpHeaders | Record<string, string | string[] | undefined>,+): Record<string, string> {+ const result: Record<string, string> = {};++ for (const [key, value] of Object.entries(headers)) {+ if (value === undefined || value === null) continue;++ const lowerKey = key.toLowerCase();++ // Remove denylist headers (hop-by-hop, framing)+ if (isForbiddenUpstreamHeaderName(lowerKey)) continue;++ // Normalize array values+ const strValue = Array.isArray(value) ? value.join(", ") : String(value);++ // Mask secret header values+ if (isSecretHeader(lowerKey)) {+ result[lowerKey] = maskSecret(strValue);+ } else {+ result[lowerKey] = strValue;+ }+ }++ return result;+}diff --git a/src/mitm/types.ts b/src/mitm/types.tsnew file mode 100644index 0000000000..2ed90b65dc--- /dev/null+++ b/src/mitm/types.ts@@ -0,0 +1,68 @@+import { z } from "zod";++export type AgentId =+ | "antigravity"+ | "kiro"+ | "copilot"+ | "codex"+ | "cursor"+ | "zed"+ | "claude-code"+ | "open-code"+ | "trae";++/**+ * Minimal abstract interface for MitmHandlerBase.+ * Full implementation lives in src/mitm/handlers/base.ts (F3).+ * Used here as a forward reference so MitmTarget.handler can be typed correctly.+ */+export interface MitmHandlerBase {+ readonly agentId: AgentId;+}++export interface MitmTarget {+ id: AgentId;+ name: string;+ icon: string;+ color: string;+ hosts: string[]; // ex.: ["api.githubcopilot.com"]+ port: number; // default 443+ endpointPatterns: string[];+ defaultModels: Array<{ id: string; name: string; alias: string }>;+ setupTutorial: {+ steps: string[];+ detection: { command: string; platform: "linux" | "macos" | "windows" | "all" };+ };+ handler: () => Promise<{ default: new () => MitmHandlerBase }>;+ riskNoticeKey: string; // i18n key+ viability?: "investigating" | "supported" | "deprecated"; // Trae = "investigating"+}++export const MitmTargetSchema = z.object({+ id: z.enum([+ "antigravity", "kiro", "copilot", "codex", "cursor", "zed",+ "claude-code", "open-code", "trae",+ ]),+ name: z.string(),+ icon: z.string(),+ color: z.string().regex(/^#[0-9A-Fa-f]{6}$/),+ hosts: z.array(z.string()).min(1),+ port: z.number().int().positive().max(65535).default(443),+ endpointPatterns: z.array(z.string()).default([]),+ defaultModels: z.array(z.object({ id: z.string(), name: z.string(), alias: z.string() })).default([]),+ setupTutorial: z.object({+ steps: z.array(z.string()),+ detection: z.object({+ command: z.string(),+ platform: z.enum(["linux", "macos", "windows", "all"]),+ }),+ }),+ riskNoticeKey: z.string(),+ viability: z.enum(["investigating", "supported", "deprecated"]).optional(),+});++export type DetectionResult = {+ installed: boolean;+ version?: string;+ path?: string;+};diff --git a/src/mitm/upstreamTrust.ts b/src/mitm/upstreamTrust.tsnew file mode 100644index 0000000000..1837abaf9c--- /dev/null+++ b/src/mitm/upstreamTrust.ts@@ -0,0 +1,31 @@+/**+ * Upstream CA certificate configuration for corporate network environments.+ * Configures undici's global dispatcher to trust a custom CA when connecting+ * to upstream providers through a corporate MITM proxy.+ *+ * Source: plano 11 §4.7 (origin: llm-interceptor --upstream-ca-cert)+ * Hard Rule #12: error message is a safe literal — no stack trace exposed.+ */+import { Agent, setGlobalDispatcher } from "undici";+import { readFileSync, existsSync } from "node:fs";++/**+ * Configure undici's global dispatcher to trust a custom CA certificate.+ *+ * @param pemPath - Absolute path to the PEM file. If undefined/empty, no-op.+ * @throws {Error} With a safe error message (no stack trace) if pemPath is set+ * but the file does not exist.+ */+export function configureUpstreamCa(pemPath?: string): void {+ if (!pemPath) return;++ if (!existsSync(pemPath)) {+ // Safe error: message only contains the user-supplied path (no stack trace).+ throw new Error(+ `AGENTBRIDGE_UPSTREAM_CA_CERT path does not exist: ${pemPath}`,+ );+ }++ const ca = readFileSync(pemPath, "utf8");+ setGlobalDispatcher(new Agent({ connect: { ca } }));+}