import { lookup } from "node:dns/promises"; import { BlockList, isIP, connect, createServer, type Server, type Socket } from "node:net"; /** * The only way out for the local worker's commands when `local.bash_network` is on (issue #65): an HTTP CONNECT proxy * on loopback that opens tunnels to allowlisted hosts only. CONNECT only, so TLS stays end to end; plain HTTP is * refused. A name that resolves to a loopback, private or link-local address is refused unless it is listed as an * address: claude-mem and the Codex app-server listen on loopback without auth. */ /** What a project gets unless `local.network_allow` says otherwise: package registries and code hosts. */ export const DEFAULT_NETWORK_ALLOW = [ "registry.npmjs.org", "registry.yarnpkg.com", "pypi.org", "files.pythonhosted.org", "github.com", "codeload.github.com", "objects.githubusercontent.com", "raw.githubusercontent.com", "crates.io", "static.crates.io", "index.crates.io", "proxy.golang.org", "sum.golang.org", ]; export interface EgressProxy { port: number; url: string; close(): Promise; } import { allowed } from "./web-fetch-config.ts"; export { allowed }; // Parsed, not prefix-matched: an IPv4-mapped IPv6 address in any spelling (`::ffff:7f00:1`) checks as its IPv4 address. const INTERNAL = new BlockList(); // IPv4 nets as leading octets: the package check refuses private address literals in published files. for (const [a, b, bits] of [[0, 0, 8], [10, 0, 8], [100, 64, 10], [127, 0, 8], [169, 254, 16], [172, 16, 12], [192, 168, 16], [198, 18, 15], [224, 0, 3]] as const) INTERNAL.addSubnet(`${a}.${b}.0.0`, bits, "ipv4"); // RFC 8215's local-use NAT64 prefix puts the IPv4 address where the operator's prefix length says: refused outright. for (const [net, bits] of [["::", 96], ["fc00::", 7], ["fe80::", 10], ["fec0::", 10], ["ff00::", 8], ["64:ff9b:1::", 48]] as const) INTERNAL.addSubnet(net, bits, "ipv6"); // The well-known NAT64 prefix (issue #82): with DNS64, a name whose only record is an internal IPv4 address comes back // as 64:ff9b::, and the NAT64 gateway carries the connection there. Its IPv4 address is what counts. const NAT64 = new BlockList(); NAT64.addSubnet("64:ff9b::", 96, "ipv6"); /** The IPv4 address in the last 32 bits of an IPv6 address, whatever its spelling. */ function lastIPv4(v6: string): string { const [head = "", tail] = new URL(`http://[${v6}]`).hostname.slice(1, -1).split("::"); const h = head ? head.split(":") : []; const t = tail ? tail.split(":") : []; const all = tail === undefined ? h : [...h, ...Array(8 - h.length - t.length).fill("0"), ...t]; const [a = 0, b = 0] = all.slice(6).map((g) => parseInt(g, 16)); return `${a >> 8}.${a & 255}.${b >> 8}.${b & 255}`; } /** Loopback, private, link-local, site-local, unspecified, carrier-grade NAT, benchmark, multicast or reserved. */ export function isInternal(address: string): boolean { // Only a non-global address carries a zone (`fe80::1%en0`, `::1%lo0`), and BlockList cannot parse one: internal. if (address.includes("%")) return true; const family = isIP(address); if (family === 6 && NAT64.check(address, "ipv6")) return isInternal(lastIPv4(address)); return family !== 0 && INTERNAL.check(address, family === 6 ? "ipv6" : "ipv4"); } const hostOf = (target: string) => { try { return ` ${new URL(target).host}`; } catch { return ""; } }; export function startEgressProxy(opts: { allow: string[]; log: (line: string) => void; /** Read at each CONNECT instead of `allow`, so a reloaded allowlist applies to the next request (the `web_fetch` proxy uses it). */ allowFn?: () => readonly string[] }): Promise { const sockets = new Set(); // Half-open on both sides: a client that sends its request and shuts its write side still gets the answer. const server: Server = createServer({ allowHalfOpen: true }, (client) => { sockets.add(client); client.on("close", () => sockets.delete(client)); client.on("error", () => client.destroy()); let head = Buffer.alloc(0); const onData = (chunk: Buffer) => { head = Buffer.concat([head, chunk]); const end = head.indexOf("\r\n\r\n"); if (end < 0) { // Once: later chunks of the same request must not refuse (and log) again. Nothing of the header is logged. if (head.length > 8192) client.off("data", onData), refuse(client, 431, "request header too large", "a request"); return; } client.off("data", onData); client.pause(); const rest = head.subarray(end + 4); const [method = "", target = "", version = ""] = head.subarray(0, end).toString("latin1").split("\r\n")[0]!.split(" "); // Answer in the version asked (macOS nc wants HTTP/1.0 back); curl and git take either. void tunnel(client, method, target, rest, version === "HTTP/1.0" ? "HTTP/1.0" : "HTTP/1.1"); }; client.on("data", onData); }); const refuse = (client: Socket, code: number, why: string, target = "") => { if (target) opts.log(`network: refused ${target} (${why})`); client.end(`HTTP/1.1 ${code} ${code === 403 ? "Forbidden" : "Bad Request"}\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nagent-hub: ${why}\n`); }; const tunnel = async (client: Socket, method: string, target: string, rest: Buffer, http: string) => { // The log gets a method and a host, never a path, a query or userinfo: those carry tokens. if (method.toUpperCase() !== "CONNECT") return refuse(client, 403, "only CONNECT (https) goes through this proxy", `${/^[A-Za-z]{1,16}$/.test(method) ? method : "a request"}${hostOf(target)}`); const m = /^(\[[^\]]+\]|[^:]+):(\d{1,5})$/.exec(target); const host = m?.[1]!.replace(/^\[|\]$/g, "") ?? ""; if (!m || !(isIP(host) || /^[a-z0-9.-]+$/i.test(host))) return refuse(client, 400, "bad CONNECT target", "a CONNECT request"); const port = Number(m[2]); if (!allowed([...(opts.allowFn ? opts.allowFn() : opts.allow)], host, port)) return refuse(client, 403, `${host}:${port} is not in local.network_allow`, `${host}:${port}`); let address = host; if (!isIP(host)) { try { address = (await lookup(host)).address; } catch { return refuse(client, 403, `${host} does not resolve`, `${host}:${port}`); } // A listed name must not lead back into this machine or its network (DNS can say anything). if (isInternal(address)) return refuse(client, 403, `${host} resolves to an internal address`, `${host}:${port}`); } const upstream = connect({ host: address, port, allowHalfOpen: true }); sockets.add(upstream); upstream.on("close", () => sockets.delete(upstream)); let open = false; upstream.once("connect", () => { open = true; client.write(`${http} 200 Connection Established\r\n\r\n`); if (rest.length) upstream.write(rest); client.pipe(upstream); upstream.pipe(client); client.resume(); }); // Before the tunnel opens a failure is a refusal, logged with the error code only (never its text). After, the // stream is the client's TLS: an HTTP answer would corrupt it, so the client is just closed. upstream.on("error", (e: NodeJS.ErrnoException) => { if (open || !client.writable || client.destroyed) return void client.destroy(); const code = /^E[A-Z]{2,20}$/.test(e.code ?? "") ? `, ${e.code}` : ""; refuse(client, 403, `${host}:${port} is unreachable${code}`, `${host}:${port}`); }); client.on("close", () => upstream.destroy()); }; return new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", () => { const port = (server.address() as { port: number }).port; resolve({ port, url: `http://127.0.0.1:${port}`, close: () => new Promise((done) => { for (const s of sockets) s.destroy(); server.close(() => done()); }), }); }); }); }