presentation.html (published copy) is a 7-slide deck in the style of Lab 01's deck, covering the per-agent config, routing, streaming redaction and how the web tools plug into a DurableHabitat. Open it in a browser and use the arrow keys, N for speaker notes, G for the slide grid.
Agents call the real API URLs (https://api.exa.ai/search, https://api.firecrawl.dev/v2/scrape, …) with ordinary clients: SDKs, fetch, curl, or MCP clients. They hold no API key. The only thing in their environment is a proxy address with their own agent id and token, plus the proxy's CA:
HTTPS_PROXY=http://researcher:<proxy-token>@127.0.0.1:7453
NODE_EXTRA_CA_CERTS=/path/to/proxy-ca.pem # curl: --cacert; Python: SSL_CERT_FILE / REQUESTS_CA_BUNDLE
NODE_USE_ENV_PROXY=1 # Node >= 24: make built-in fetch honor HTTPS_PROXY
For each CONNECT host:443, the proxy:
- Authenticates the agent from
Proxy-Authorization. - Tunnels hosts with no key for this agent untouched.
- For a host with a key, terminates TLS with a per-host certificate signed by its own CA.
For each request inside a keyed tunnel, it:
- Strips any credentials the agent sent.
- Injects that agent's own key for that API, in the header style the API expects.
- Streams the response back through a redactor that masks every vault key: raw, base64, base64url, or percent-encoded, even when split across chunks.
Run
pnpm exec tsx examples/05-zero-key-agents/run.ts --smoke # offline mocks, PASS table, exit 0/1
pnpm exec tsx examples/05-zero-key-agents/run.ts --port 7453 # interactive; prints agent env + curl lines, live audit
pnpm exec tsx examples/05-zero-key-agents/run.ts --smoke --live # web APIs hit the real services (keys from proxy env)
Each smoke check runs a separate agent process (agent.ts) whose environment is only agentProxyEnv() plus PATH/HOME. In offline mode, upstreamOrigins points the real hostnames at loopback mocks. The agent still sees https://api.exa.ai and a valid certificate. In --port mode, SIGHUP rotates the REST key in-process.
Per-agent config
const proxy = await startMitmProxy({
agents: {
researcher: {
token: "ag_researcher_9f", // proxy password for this agent
apis: {
...webApis({ // Exa/Firecrawl/Parallel with the right auth style
exa: { env: "EXA_API_KEY_RESEARCHER" }, // this agent's own Exa key
firecrawl: { env: "FIRECRAWL_API_KEY" },
}),
"api.github.com": {
key: { env: "GITHUB_RO_TOKEN" },
auth: { style: "bearer" },
},
},
},
scout: { token: "ag_scout_2c", apis: webApis({ exa: { env: "EXA_API_KEY_SCOUT" } }) },
},
}, { port: 7453, ca, auditFile: "audit.jsonl" });
API
// proxy.ts
startMitmProxy(config: MitmProxyConfig, options?: MitmProxyOptions): Promise<MitmProxyHandle>
// options: { host?="127.0.0.1", port?=0, ca?, auditFile?, onAudit?(r), upstreamOrigins?, maxRequestBytes?=5MB }
// handle: { url, port, caCertPem, audit(), reload(config), close() }
agentProxyEnv({ proxyUrl, agentId, token, caCertPath }) // -> HTTPS_PROXY, HTTP_PROXY, NO_PROXY, NODE_USE_ENV_PROXY, NODE_EXTRA_CA_CERTS
createProxyCa(commonName?) -> { certPem, keyPem } // persist and pass as options.ca to keep agents' trust
createStreamRedactor(secrets) / redactString(text, secrets)
interface MitmProxyConfig { agents: Record<string /*agentId*/, AgentConfig> }
interface AgentConfig { token: string; apis: Record<string /*host*/, AgentApi> }
interface AgentApi {
key: { value: string } | { env: string }; // env is read from the PROXY's environment
auth: { style: "bearer" } | { style: "header"; header: string; prefix?: string };
}
// services.ts
WEB_SERVICES // exa | firecrawl | parallel -> host, auth, envVar
webApis({ exa?, firecrawl?, parallel? }: SecretSource per service) -> Record<host, AgentApi>
servicesWithEnvKeys(env?)
// tools.ts — the agent side; knows nothing about the proxy
createWebTools({ searchProvider?="exa", fetchProvider?="firecrawl", habitatId?, traceId? })
// -> { web_search, web_fetch } as @umwelten/pi ExecutableTools, for DurableHabitat.open({ tools })
webSearch(opts, { query, numResults? }) -> { provider, query, results: { title, url, snippet }[] }
webFetch(opts, { url, objective? }) -> { provider, url, title, content }
| Service | Host | Auth injected | Conventional env |
|---|---|---|---|
| exa | api.exa.ai | x-api-key | EXA_API_KEY |
| firecrawl | api.firecrawl.dev | Authorization: Bearer | FIRECRAWL_API_KEY |
| parallel | api.parallel.ai | x-api-key | PARALLEL_API_KEY |
Each audit record is one JSON line with these fields: timestamp, agentId, method, upstream (host), path, status, latencyMs, redactions, decision, reason?, keySource?, keyFingerprint? (sha256 prefix), traceId?, habitatId?.
What the proxy does
The proxy blocks nothing. The only thing it checks is who the agent is, so it knows whose keys to inject.
- Authentication: missing or wrong
agentId:token→ 407. That is the only refusal. - Host with a key for this agent (
CONNECT host:443): the proxy terminates TLS, then for every request, whatever the method or path:- Removes
authorization,x-api-key,cookieand hop-by-hop headers, and passes everything else, including allmcp-*headers. - Forces
accept-encoding: identity, so the redactor sees plaintext. - Injects the agent's key.
- Streams the response back with
set-cookieandwww-authenticatedropped and the rest redacted. The body goes through the streaming redactor, which masks every key loaded for any agent, including keys rotated out since.
- Removes
- Anything else (other hosts, other ports, plain HTTP): passed through untouched as a plain tunnel or forward, with the agent's own headers. The audit records it as
passthrough.
Caveats
- Bypass: an agent that ignores
HTTPS_PROXY, or uses a client that doesn't honor it, goes direct. The agent network must therefore block direct egress. This is already required by thezero-secret-habitat-runtimerule indocs/specs/orchestration/durable-habitats.md. - Implicit
.envloading: importing@umwelten/piloads the nearest.envabove the process cwd (packages/pi/src/models.ts,loadEnv()). Start agents in a directory with no.envabove it, or they'll pick up keys regardless of their environment.run.tsstarts them in a temp dir for this reason. - TLS: the proxy handles HTTP/1.1 only and doesn't do certificate pinning. Clients that pin certificates fail closed.
Prompt
Build a self-contained lab under `examples/05-zero-key-agents/`: a per-agent HTTPS man-in-the-middle forward proxy that lets agents call real API URLs (https://api.exa.ai, https://api.firecrawl.dev, https://api.parallel.ai, any MCP server) while holding no API keys.
Read first: `packages/protocols/src/mcp/client/remote.ts`, `packages/habitat/src/durable/durable-habitat.ts`, `packages/pi/src/models.ts` (note `loadEnv()`), and the "zero-secret-habitat-runtime" rule in `docs/specs/orchestration/durable-habitats.md`.
Requirements:
1. `proxy.ts` exports `startMitmProxy(config, options)`. Config is keyed by agent id: `{ token, apis: { [host]: { key: {value}|{env}, auth: {style:"bearer"}|{style:"header", header, prefix?} } } }`. Keys are read from the proxy's environment, never the agent's. Bind 127.0.0.1.
2. Authenticate `agentId:token` from Proxy-Authorization (constant-time compare) else 407. That is the only refusal: the proxy blocks nothing. For `CONNECT host:443` to a host with a key in that agent's config, terminate TLS with a per-host certificate from the proxy's own CA (`createProxyCa`). Every other host, port and plain-HTTP request passes through untouched with the agent's own headers.
3. Inside a keyed tunnel, any method and path is forwarded.
4. Strip authorization, x-api-key, cookie and hop-by-hop headers; pass every other header including all `mcp-*`; force `accept-encoding: identity`; inject that agent's own key.
5. Stream responses back (SSE and MCP Streamable HTTP must not buffer) through a streaming redactor that masks every loaded key, including rotated-out keys, in raw, base64, base64url and percent-encoded forms, even split across chunks. Drop set-cookie and www-authenticate.
6. One JSON audit line per request: timestamp, agentId, method, upstream host, path, status, latencyMs, redactions, decision, reason, keyFingerprint (sha256 prefix), traceId, habitatId.
7. `services.ts` with `webApis({ exa?, firecrawl?, parallel? })` giving each service's host and auth style; `tools.ts` with `createWebTools()` returning `web_search` and `web_fetch` as @umwelten/pi ExecutableTools that call the real URLs and know nothing about the proxy; `agentProxyEnv()` returning HTTPS_PROXY, HTTP_PROXY, NO_PROXY, NODE_USE_ENV_PROXY=1 and NODE_EXTRA_CA_CERTS.
8. `run.ts --smoke` starts the proxy with offline mocks behind the real hostnames (`upstreamOrigins`), runs each check in a separate agent process whose env is only `agentProxyEnv()` plus PATH/HOME, started in a temp dir with no `.env` above it, and checks: zero keys in the agent env, 407, passthrough for hosts without a key (CONNECT and plain HTTP), any method and path with the agent's key, header-echo redaction, SSE split-secret redaction, MCP listTools + callTool on the current protocol version, web tools via all three services, per-agent key fingerprints, a `DurableHabitat` (faux model) calling web_search with no key, key rotation without restarts, and a final scan of all output for key strings. Print a PASS table and exit 0 only if all pass. `--live` uses real services where keys are set and reports SKIP otherwise; `--port 7453` runs interactively and rotates a key on SIGHUP.
Strict TypeScript, no `any`, everything closed in `finally`.
--live opt-in
What we learned
Why MITM instead of a reverse proxy
The first build was a reverse proxy (/egress/<service>/*, 16/16 checks). It had two problems:
- Agents had to know about it. Only tools written against the proxy's own URL went through it. An unmodified SDK, or
curl https://api.exa.aifrombash, went around it. - Keys were per route, not per agent. Every agent that could use Exa shared one key, so there was no per-agent billing or rate limiting.
With MITM, agents call the real URLs with ordinary clients. Their environment holds only HTTPS_PROXY=http://<agentId>:<token>@…, NODE_EXTRA_CA_CERTS and NODE_USE_ENV_PROXY=1. The proxy config is keyed by agent, so each agent gets its own keys.
Answers
- Secret isolation: Each check runs a separate agent process. A scan of 14 key forms (7 keys, each raw and base64) across 18,546 bytes of agent output, runner output and audit log found 0 hits. An upstream that echoes the auth header it received gets
[REDACTED_VAULT_SECRET]in place of raw and base64, and the audit record carriesredactions: 2and an ALERT. - No blocking (changed 2026-11-30): The first build also enforced per-agent host, method and path rules (403) and rejected path-traversal variants (400). Those came from the lab's own prompt, not a requirement, and were removed. Now the only refusal is bad proxy credentials (407, before any upstream contact). Hosts with no key for the agent pass through untouched, over CONNECT or plain HTTP. Two agents still reach Exa with different keys.
- SSE and MCP: SSE streams through TLS: the first frame arrived about 234 ms before the upstream finished. The redactor caught a key split at every point, across 2,460 split combinations. MCP
listToolsandcallToolran through the proxy on protocol2026-07-28, and an echoed MCP bearer was masked. - Rotation:
reload(config)(orSIGHUPin--portmode) swapped the REST key while the agent kept its token. Rotated-out keys stay in the redactor.
Gotchas
- A plain-HTTP proxy request for an
https://URL crashed the proxy.http.requestthrows synchronously on a non-http:URL, which killed the process for every agent. It now answers 400 with an audit record, and failed or aborted plain-HTTP forwards are audited too. The smoke checks the proxy still serves afterwards.
@umwelten/piloads.envon import. The first MITM smoke failed "agent env holds zero upstream keys" even with a clean child environment: importing@umwelten/pirunsloadEnv(), which loaded~/.envand gave the agentMYCEL_API_KEY. The lab now starts agents in a temp directory.loadEnv()inpackages/piis unchanged, so any agent started under a directory with a.envabove it still picks up keys.- Forward every
mcp-*header. Forwarding a fixed header list droppedMcp-Method,Mcp-NameandMcp-Param-*. MCP still worked, but silently downgraded to protocol2025-11-25. The smoke now fails on a downgrade. - Force
accept-encoding: identity. The redactor can only match plaintext, so the proxy asks upstreams for uncompressed responses. - Don't block the proxy's event loop. A test that ran
curlwithspawnSyncin the proxy's own process hung, because the proxy couldn't answer. Use asyncexecFile. - Certificates:
@peculiar/x509needed areflect-metadatapolyfill and churned the lockfile;node-forgeworked with no extra setup.
Not tested
- Real Exa, Firecrawl and Parallel. No keys were set, so
--smoke --liveskips those 3 checks. Request and response shapes follow the services' current docs. - A real model. The
DurableHabitatcheck uses a faux model that callsweb_search. Lab 02 covers the Mycel model path. - Known limits: an agent that ignores
HTTPS_PROXYgoes direct, so the network must block direct egress. The proxy speaks HTTP/1.1 only, and clients that pin certificates fail closed.