// THE PROXY CLIENT behind network exits (lib/networkExits.ts): a preflight // that proves an exit's proxy answers before anything is sent through it, and // a tunnelled GET for the operator's address-echo probe. SOCKS5 (with and // without username/password, `socks5h` handing the hostname to the proxy, // `socks5` resolving it here) and HTTP CONNECT over a plain or TLS connection // to the proxy. No dependency: the handshakes are a few bytes each. // // FAIL CLOSED. Every function here either succeeds through the proxy or // answers why not; none of them ever opens a connection to the target itself. // No error text carries the proxy's credentials. import net from "node:net"; import tls from "node:tls"; import dns from "node:dns/promises"; import { PROXY_SCHEMES, type ProxyScheme } from "./networkExits"; // The URL here is one this repo built (lib/networkExits.ts proxyUrlOf) from a // validated exit and its key-file credentials — never one taken from input. type ParsedProxy = { scheme: ProxyScheme; host: string; port: number; username: string; password: string }; function parseProxyUrl(raw: string): ParsedProxy | { error: string } { const m = /^([a-z0-9]+):\/\/(?:([^:@/]*):([^@/]*)@)?(\[[^\]]+\]|[^:/@]+):(\d+)$/.exec(raw); if (!m || !(PROXY_SCHEMES as readonly string[]).includes(m[1]!)) return { error: "the exit's proxy is not scheme://host:port" }; try { return { scheme: m[1] as ProxyScheme, username: m[2] ? decodeURIComponent(m[2]) : "", password: m[3] ? decodeURIComponent(m[3]) : "", host: m[4]!.replace(/^\[|\]$/g, ""), port: Number(m[5]), }; } catch { return { error: "the exit's credentials are not valid percent-encoding" }; } } export const PROXY_TIMEOUT_MS = 8_000; export type ProxyFailure = { ok: false; reason: string }; class ProxyError extends Error {} function errText(err: unknown): string { const e = err as NodeJS.ErrnoException; if (e?.code === "ECONNREFUSED") return "connection refused"; if (e?.code === "ENOTFOUND" || e?.code === "EAI_AGAIN") return "its host does not resolve"; if (e?.code === "ETIMEDOUT") return "timed out"; if (e?.code === "ECONNRESET") return "the connection was reset"; return e instanceof ProxyError ? e.message : (e?.code ?? (e?.message || String(err))); } // A buffered reader over a socket: `read(n)` resolves with exactly n bytes, // `readUntil(sep)` with everything through the separator. function reader(sock: net.Socket) { let buf = Buffer.alloc(0); let waiter: (() => void) | null = null; let failed: Error | null = null; const wake = () => { const w = waiter; waiter = null; w?.(); }; const onData = (c: Buffer) => { buf = Buffer.concat([buf, c]); wake(); }; const onEnd = () => { failed = failed ?? new ProxyError("the proxy closed the connection"); wake(); }; const onError = (e: Error) => { failed = e; wake(); }; sock.on("data", onData); sock.on("end", onEnd); sock.on("close", onEnd); sock.on("error", onError); const wait = () => new Promise((r) => (waiter = r)); return { async read(n: number): Promise { while (buf.length < n) { if (failed) throw failed; await wait(); } const out = buf.subarray(0, n); buf = buf.subarray(n); return out; }, async readUntil(sep: string, max = 64 * 1024): Promise { for (;;) { const i = buf.indexOf(sep); if (i >= 0) { const out = buf.subarray(0, i + sep.length); buf = buf.subarray(i + sep.length); return out; } if (buf.length > max) throw new ProxyError("the proxy's answer is too long"); if (failed) throw failed; await wait(); } }, async readAll(max = 64 * 1024): Promise { while (!failed && buf.length <= max) await wait(); return buf.subarray(0, max); }, // Hand the socket over: stop listening, give back what was read ahead. release(): Buffer { sock.off("data", onData); sock.off("end", onEnd); sock.off("close", onEnd); sock.off("error", onError); return buf; }, }; } function withTimeout(p: Promise, ms: number, sock: () => net.Socket | null, what: string): Promise { let t: NodeJS.Timeout; return Promise.race([ p, new Promise((_, reject) => { t = setTimeout(() => { sock()?.destroy(); reject(new ProxyError(`${what} timed out after ${Math.round(ms / 1000)} s`)); }, ms); }), ]).finally(() => clearTimeout(t)); } // The TCP (or, for an https:// proxy, TLS) connection to the proxy itself. function connectToProxy(p: ParsedProxy): Promise { return new Promise((resolve, reject) => { const onErr = (e: Error) => reject(e); if (p.scheme === "https") { const s = tls.connect({ host: p.host, port: p.port, servername: net.isIP(p.host) ? undefined : p.host }, () => { s.off("error", onErr); resolve(s); }); s.once("error", onErr); } else { const s = net.connect({ host: p.host, port: p.port }, () => { s.off("error", onErr); resolve(s); }); s.once("error", onErr); } }); } const SOCKS_REPLIES: Record = { 1: "general failure", 2: "connection not allowed by its rules", 3: "network unreachable", 4: "host unreachable", 5: "connection refused by the destination", 6: "TTL expired", 7: "command not supported", 8: "address type not supported", }; async function socksGreeting(sock: net.Socket, r: ReturnType, p: ParsedProxy): Promise { const creds = p.username !== "" || p.password !== ""; sock.write(Buffer.from(creds ? [5, 2, 0, 2] : [5, 1, 0])); const [ver, method] = await r.read(2); if (ver !== 5) throw new ProxyError("it does not speak SOCKS5"); if (method === 0xff) throw new ProxyError("it accepts none of the offered login methods"); if (method === 2) { if (!creds) throw new ProxyError("it wants a username and password, and the exit has none"); const u = Buffer.from(p.username, "utf8"); const pw = Buffer.from(p.password, "utf8"); if (u.length > 255 || pw.length > 255) throw new ProxyError("the exit's username or password is too long for SOCKS5"); sock.write(Buffer.concat([Buffer.from([1, u.length]), u, Buffer.from([pw.length]), pw])); const [, status] = await r.read(2); if (status !== 0) throw new ProxyError("it refused the exit's username and password"); } else if (method !== 0) { throw new ProxyError("it chose a login method this client does not speak"); } } async function socksConnect( sock: net.Socket, r: ReturnType, p: ParsedProxy, host: string, port: number, ): Promise { let addr: Buffer; let target = host; // socks5: the name is resolved HERE; socks5h: the proxy resolves it. if (p.scheme === "socks5" && net.isIP(host) === 0) target = (await dns.lookup(host)).address; const v = net.isIP(target); if (v === 4) addr = Buffer.from([1, ...target.split(".").map(Number)]); else if (v === 6) { const full = expandIpv6(target); addr = Buffer.concat([Buffer.from([4]), full]); } else { const name = Buffer.from(target, "utf8"); if (name.length > 255) throw new ProxyError("the destination's name is too long for SOCKS5"); addr = Buffer.concat([Buffer.from([3, name.length]), name]); } const portBuf = Buffer.from([(port >> 8) & 0xff, port & 0xff]); sock.write(Buffer.concat([Buffer.from([5, 1, 0]), addr, portBuf])); const [ver, rep, , atyp] = await r.read(4); if (ver !== 5) throw new ProxyError("it answered the connect in something other than SOCKS5"); if (rep !== 0) throw new ProxyError(`it could not reach the destination (${SOCKS_REPLIES[rep!] ?? `reply ${rep}`})`); const len = atyp === 1 ? 4 : atyp === 4 ? 16 : (await r.read(1))[0]!; await r.read(len + 2); } function expandIpv6(ip: string): Buffer { const [head, tail] = ip.split("::"); const h = head ? head.split(":") : []; const t = tail !== undefined && tail !== "" ? tail.split(":") : []; const groups = [...h, ...Array(8 - h.length - t.length).fill("0"), ...t]; const out = Buffer.alloc(16); groups.forEach((g, i) => out.writeUInt16BE(parseInt(g || "0", 16), i * 2)); return out; } function basicAuth(p: ParsedProxy): string { if (p.username === "" && p.password === "") return ""; return `Proxy-Authorization: Basic ${Buffer.from(`${p.username}:${p.password}`).toString("base64")}\r\n`; } async function httpConnect(sock: net.Socket, r: ReturnType, p: ParsedProxy, host: string, port: number): Promise { const authority = net.isIP(host) === 6 ? `[${host}]:${port}` : `${host}:${port}`; sock.write(`CONNECT ${authority} HTTP/1.1\r\nHost: ${authority}\r\n${basicAuth(p)}\r\n`); const head = (await r.readUntil("\r\n\r\n")).toString("latin1"); const status = Number(/^HTTP\/1\.[01] (\d{3})/.exec(head)?.[1] ?? 0); if (status === 407) throw new ProxyError("it refused the exit's credentials (HTTP 407)"); if (status !== 200) throw new ProxyError(`it refused the tunnel (HTTP ${status || "?"})`); } // A TUNNEL through the exit's proxy to host:port, or why not. export async function openTunnel( proxyUrl: string, host: string, port: number, timeoutMs = PROXY_TIMEOUT_MS, ): Promise<{ ok: true; socket: net.Socket; head: Buffer } | ProxyFailure> { const p = parseProxyUrl(proxyUrl); if ("error" in p) return { ok: false, reason: p.error }; let sock: net.Socket | null = null; try { return await withTimeout( (async () => { sock = await connectToProxy(p); const r = reader(sock); if (p.scheme === "socks5" || p.scheme === "socks5h") { await socksGreeting(sock, r, p); await socksConnect(sock, r, p, host, port); } else { await httpConnect(sock, r, p, host, port); } const head = r.release(); return { ok: true as const, socket: sock, head }; })(), timeoutMs, () => sock, "the proxy", ); } catch (err) { (sock as net.Socket | null)?.destroy(); return { ok: false, reason: errText(err) }; } } // THE PREFLIGHT: the proxy answers (TCP, or TLS for https://) and, for a // SOCKS proxy, accepts the greeting and the exit's login. Nothing is asked of // any destination. // `connectOnly` (the startup probe): the TCP or TLS connect alone — no // greeting, no login. export async function preflightProxy( proxyUrl: string, timeoutMs = PROXY_TIMEOUT_MS, opts: { connectOnly?: boolean } = {}, ): Promise<{ ok: true; ms: number } | ProxyFailure> { const p = parseProxyUrl(proxyUrl); if ("error" in p) return { ok: false, reason: p.error }; const t0 = Date.now(); let sock: net.Socket | null = null; try { await withTimeout( (async () => { sock = await connectToProxy(p); if (!opts.connectOnly && (p.scheme === "socks5" || p.scheme === "socks5h")) { const r = reader(sock); await socksGreeting(sock, r, p); r.release(); } })(), timeoutMs, () => sock, "the proxy", ); return { ok: true, ms: Date.now() - t0 }; } catch (err) { return { ok: false, reason: errText(err) }; } finally { (sock as net.Socket | null)?.destroy(); } } // ONE GET THROUGH THE EXIT (the address-echo probe): status and the first // 4 KB of the body. http and https destinations; the TLS to an https // destination runs inside the tunnel. export async function getThroughProxy( proxyUrl: string, url: string, timeoutMs = PROXY_TIMEOUT_MS, ): Promise<{ ok: true; status: number; body: string } | ProxyFailure> { let u: URL; try { u = new URL(url); } catch { return { ok: false, reason: "the echo URL does not parse" }; } const secure = u.protocol === "https:"; const port = Number(u.port || (secure ? 443 : 80)); const host = u.hostname.replace(/^\[|\]$/g, ""); const t = await openTunnel(proxyUrl, host, port, timeoutMs); if (!t.ok) return t; let sock: net.Socket = t.socket; try { return await withTimeout( (async () => { if (secure) { sock = await new Promise((resolve, reject) => { const s = tls.connect({ socket: t.socket, servername: net.isIP(host) ? undefined : host }, () => resolve(s)); s.once("error", reject); }); } else if (t.head.length) { sock.unshift(t.head); } const r = reader(sock); sock.write( `GET ${u.pathname || "/"}${u.search} HTTP/1.1\r\nHost: ${u.host}\r\nUser-Agent: archilyzer-network-probe\r\n` + `Accept: text/plain, */*\r\nConnection: close\r\n\r\n`, ); const head = (await r.readUntil("\r\n\r\n")).toString("latin1"); const status = Number(/^HTTP\/1\.[01] (\d{3})/.exec(head)?.[1] ?? 0); const body = (await r.readAll(4096)).toString("utf8"); const chunked = /\r\ntransfer-encoding:\s*chunked/i.test(head); return { ok: true as const, status, body: chunked ? dechunk(body) : body }; })(), timeoutMs, () => sock, "the echo request", ); } catch (err) { return { ok: false, reason: errText(err) }; } finally { sock.destroy(); } } function dechunk(s: string): string { let out = ""; let rest = s; for (;;) { const m = /^([0-9a-f]+)[^\r\n]*\r\n/i.exec(rest); if (!m) break; const n = parseInt(m[1]!, 16); if (n === 0) break; out += rest.slice(m[0].length, m[0].length + n); rest = rest.slice(m[0].length + n + 2); } return out; } // The public address an echo body names (the first IPv4/IPv6 literal in it), // or null. export function addressInEcho(body: string): string | null { const t = body.trim(); if (net.isIP(t)) return t; for (const m of t.matchAll(/[0-9a-fA-F:.]{3,}/g)) { if (net.isIP(m[0])) return m[0]; const c = m[0].replace(/^[.]+|[:.]+$/g, ""); if (net.isIP(c)) return c; } return null; }