benignswarm 0.12.145 → 0.12.147

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1312 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { lookup } from "node:dns/promises";
4
+ import { chmodSync, mkdirSync, realpathSync, rmSync } from "node:fs";
5
+ import { createServer as createHttpServer, request as httpRequest } from "node:http";
6
+ import { createConnection, createServer as createNetServer, isIP } from "node:net";
7
+ import { platform, tmpdir } from "node:os";
8
+ import { join, resolve } from "node:path";
9
+ import { domainToASCII, fileURLToPath } from "node:url";
10
+ export const CLAUDE_SECRET_EGRESS_OUTER_BOUNDARY = "bwrap-unshare-net-egress-proxy";
11
+ const EGRESS_RUNNER_CONFIG_ENV = "B9S_CLAUDE_EGRESS_RUNNER_CONFIG";
12
+ const DNS_HOSTNAME_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
13
+ export function isIpv4Literal(host) {
14
+ if (!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(host))
15
+ return false;
16
+ return host.split(".").every((part) => Number(part) <= 255);
17
+ }
18
+ export function isIpv4Alias(host) {
19
+ try {
20
+ const canonical = new URL(`http://${host}`).hostname;
21
+ return canonical !== host && isIpv4Literal(canonical);
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
27
+ export function normalizeEgressHostname(rawHost) {
28
+ if (rawHost !== rawHost.trim() || /[\s/@:#*\\[\]]/.test(rawHost))
29
+ return null;
30
+ const lowered = rawHost.trim().toLowerCase();
31
+ const stripped = lowered.endsWith(".") ? lowered.slice(0, -1) : lowered;
32
+ if (!stripped || stripped.length > 253 || isIpv4Literal(stripped) || isIpv4Alias(stripped) || !DNS_HOSTNAME_RE.test(stripped)) {
33
+ return null;
34
+ }
35
+ const ascii = domainToASCII(stripped);
36
+ if (!ascii || isIP(ascii) !== 0 || ascii.length > 253 || !DNS_HOSTNAME_RE.test(ascii))
37
+ return null;
38
+ return ascii;
39
+ }
40
+ export function isInternalOrLocalHostname(host) {
41
+ return host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal");
42
+ }
43
+ /** Strict host validation shared between project secret host declarations and the outer proxy. */
44
+ export function validateDeclaredSecretHosts(rawHosts, allowEmpty = false) {
45
+ if (!Array.isArray(rawHosts) || (!allowEmpty && rawHosts.length < 1) || rawHosts.length > 50 || rawHosts.some((h) => typeof h !== "string")) {
46
+ throw egressHostError("declared secret hosts must be a list of 1-50 exact hostnames");
47
+ }
48
+ const hosts = [];
49
+ for (const raw of rawHosts) {
50
+ const host = normalizeEgressHostname(raw);
51
+ if (!host) {
52
+ throw egressHostError(`invalid secret declared host ${JSON.stringify(raw)}; expected a DNS hostname without wildcards, schemes, ports, paths, or IP literals`);
53
+ }
54
+ if (isInternalOrLocalHostname(host)) {
55
+ throw egressHostError(`secret declared host ${JSON.stringify(host)} cannot name a local or internal host`);
56
+ }
57
+ if (!hosts.includes(host))
58
+ hosts.push(host);
59
+ }
60
+ return hosts;
61
+ }
62
+ function egressHostError(message) {
63
+ const err = new Error(message);
64
+ err.code = "secret_egress_invalid_hosts";
65
+ return err;
66
+ }
67
+ /** Fail closed unless IPv4 is globally routable; blocks RFC1918, loopback, link-local, IMDS, CGNAT, multicast. */
68
+ export function isPublicIpv4(ip) {
69
+ const parts = ip.split(".");
70
+ if (parts.length !== 4)
71
+ return false;
72
+ let n = 0;
73
+ for (const part of parts) {
74
+ if (!/^(?:0|[1-9]\d{0,2})$/.test(part))
75
+ return false;
76
+ const octet = Number(part);
77
+ if (octet > 255)
78
+ return false;
79
+ n = (n * 256 + octet) >>> 0;
80
+ }
81
+ const inRange = (base, bits) => (n >>> (32 - bits)) === (base >>> (32 - bits));
82
+ return !(inRange(0x00000000, 8) || inRange(0x0a000000, 8) || inRange(0x64400000, 10)
83
+ || inRange(0x7f000000, 8) || inRange(0xa9fe0000, 16) || inRange(0xac100000, 12)
84
+ || inRange(0xc0000000, 24) || inRange(0xc0000200, 24) || inRange(0xc0586300, 24)
85
+ || inRange(0xc0a80000, 16) || inRange(0xc6120000, 15) || inRange(0xc6336400, 24)
86
+ || inRange(0xcb007100, 24) || inRange(0xe0000000, 4) || inRange(0xf0000000, 4));
87
+ }
88
+ function parseIpv6Bytes(rawIp) {
89
+ const withoutZone = rawIp.split("%")[0].toLowerCase();
90
+ const [headPart, tailPart, ...extra] = withoutZone.split("::");
91
+ if (extra.length > 0)
92
+ return null;
93
+ const expandHextets = (segment) => {
94
+ if (!segment)
95
+ return [];
96
+ const parts = segment.split(":");
97
+ const out = [];
98
+ for (let i = 0; i < parts.length; i++) {
99
+ const part = parts[i];
100
+ if (part.includes(".")) {
101
+ if (i !== parts.length - 1 || !isIpv4Literal(part))
102
+ return null;
103
+ const octets = part.split(".").map(Number);
104
+ out.push((octets[0] << 8) | octets[1], (octets[2] << 8) | octets[3]);
105
+ }
106
+ else {
107
+ if (!/^[0-9a-f]{1,4}$/.test(part))
108
+ return null;
109
+ out.push(Number.parseInt(part, 16));
110
+ }
111
+ }
112
+ return out;
113
+ };
114
+ const head = expandHextets(headPart ?? "");
115
+ if (!head)
116
+ return null;
117
+ if (tailPart === undefined) {
118
+ if (head.length !== 8)
119
+ return null;
120
+ const bytes = new Uint8Array(16);
121
+ for (let i = 0; i < 8; i++) {
122
+ bytes[i * 2] = (head[i] >> 8) & 0xff;
123
+ bytes[i * 2 + 1] = head[i] & 0xff;
124
+ }
125
+ return bytes;
126
+ }
127
+ const tail = expandHextets(tailPart);
128
+ if (!tail || head.length + tail.length >= 8)
129
+ return null;
130
+ const zeros = 8 - head.length - tail.length;
131
+ const hextets = [...head, ...new Array(zeros).fill(0), ...tail];
132
+ const bytes = new Uint8Array(16);
133
+ for (let i = 0; i < 8; i++) {
134
+ bytes[i * 2] = (hextets[i] >> 8) & 0xff;
135
+ bytes[i * 2 + 1] = hextets[i] & 0xff;
136
+ }
137
+ return bytes;
138
+ }
139
+ /** Fail closed unless IPv6 is globally routable; blocks loopback, link-local, ULA (IMDS), NAT64/mapped private IPv4. */
140
+ export function isPublicIpv6(rawIp) {
141
+ if (rawIp.includes("%"))
142
+ return false;
143
+ const bytes = parseIpv6Bytes(rawIp);
144
+ if (!bytes)
145
+ return false;
146
+ const isAllZeroExceptLast = bytes.slice(0, 15).every((b) => b === 0);
147
+ if (isAllZeroExceptLast && (bytes[15] === 0 || bytes[15] === 1))
148
+ return false; // :: and ::1
149
+ if (bytes[0] === 0xff)
150
+ return false; // ff00::/8 multicast
151
+ if (bytes[0] === 0xfe && (bytes[1] & 0xc0) === 0x80)
152
+ return false; // fe80::/10 link-local
153
+ if (bytes[0] === 0xfe && (bytes[1] & 0xc0) === 0xc0)
154
+ return false; // fec0::/10 site-local
155
+ if ((bytes[0] & 0xfe) === 0xfc)
156
+ return false; // fc00::/7 ULA (incl. fd00:ec2::254 IMDS)
157
+ if (bytes[0] === 0x20 && bytes[1] === 0x01 && bytes[2] === 0x0d && bytes[3] === 0xb8)
158
+ return false; // 2001:db8::/32
159
+ if (bytes[0] === 0x20 && bytes[1] === 0x01 && bytes[2] === 0x00 && bytes[3] === 0x00)
160
+ return false; // 2001::/32 Teredo
161
+ if (bytes[0] === 0x20 && bytes[1] === 0x02)
162
+ return false; // 2002::/16 6to4
163
+ if (bytes.slice(0, 8).every((b) => b === 0) && bytes[0] === 0 && bytes[1] === 0) {
164
+ // ::/96 compatible and ::ffff:0:0/96 IPv4-mapped
165
+ const isCompat = bytes.slice(0, 12).every((b) => b === 0);
166
+ const isMapped = bytes.slice(0, 10).every((b) => b === 0) && bytes[10] === 0xff && bytes[11] === 0xff;
167
+ if (isCompat || isMapped) {
168
+ return isPublicIpv4(`${bytes[12]}.${bytes[13]}.${bytes[14]}.${bytes[15]}`);
169
+ }
170
+ }
171
+ if (bytes[0] === 0x00 && bytes[1] === 0x64 && bytes[2] === 0xff && bytes[3] === 0x9b && bytes.slice(4, 12).every((b) => b === 0)) {
172
+ return isPublicIpv4(`${bytes[12]}.${bytes[13]}.${bytes[14]}.${bytes[15]}`);
173
+ }
174
+ return true;
175
+ }
176
+ function normalizeLoopbackAddress(hostname) {
177
+ const stripped = hostname.startsWith("[") && hostname.endsWith("]") ? hostname.slice(1, -1) : hostname;
178
+ if (stripped === "127.0.0.1" || stripped === "::1")
179
+ return stripped;
180
+ return null;
181
+ }
182
+ /**
183
+ * Constrain configurable API URL strictly to the enrolled BenignSwarm control plane.
184
+ * Public HTTPS control-plane hostnames must pass full declared-host validation (never IP literals,
185
+ * internal names, wildcards, or plain HTTP). Loopback test origins are permitted ONLY when an exact
186
+ * enrolled control-plane URL or explicit test flag names that single host:port origin.
187
+ */
188
+ export function resolveTrustedControlPlaneOrigin(params) {
189
+ const rawUrl = (params.apiUrl ?? "https://api.benignswarm.org").trim();
190
+ let parsed;
191
+ try {
192
+ parsed = new URL(rawUrl);
193
+ }
194
+ catch {
195
+ throw egressHostError("invalid BenignSwarm API URL for Claude Code egress allowlist");
196
+ }
197
+ if (parsed.username || parsed.password) {
198
+ throw egressHostError("BenignSwarm API URL for Claude Code egress allowlist cannot contain credentials");
199
+ }
200
+ if (parsed.hostname.includes("*")) {
201
+ throw egressHostError("BenignSwarm API host for Claude Code egress allowlist cannot contain wildcards");
202
+ }
203
+ let trustedOrigin = null;
204
+ if (params.trustedControlPlaneUrl !== undefined) {
205
+ let trustedParsed;
206
+ try {
207
+ trustedParsed = new URL(params.trustedControlPlaneUrl.trim());
208
+ }
209
+ catch {
210
+ throw egressHostError("invalid enrolled BenignSwarm control-plane URL");
211
+ }
212
+ if (trustedParsed.origin !== parsed.origin) {
213
+ throw egressHostError(`Claude Code egress API origin ${parsed.origin} does not match enrolled control plane ${trustedParsed.origin}`);
214
+ }
215
+ trustedOrigin = trustedParsed.origin;
216
+ }
217
+ const loopbackIp = normalizeLoopbackAddress(parsed.hostname);
218
+ if (loopbackIp) {
219
+ const explicitPort = parsed.port ? Number(parsed.port) : NaN;
220
+ if (parsed.protocol !== "http:"
221
+ || !Number.isInteger(explicitPort)
222
+ || explicitPort <= 0
223
+ || explicitPort > 65535
224
+ || (trustedOrigin !== parsed.origin && params.allowLoopbackControlPlaneForTests !== true)) {
225
+ throw egressHostError(`loopback control-plane origin ${parsed.origin} is only allowed for an explicitly enrolled test API origin`);
226
+ }
227
+ return {
228
+ origin: parsed.origin,
229
+ protocol: "http:",
230
+ hostname: loopbackIp,
231
+ port: explicitPort,
232
+ isLoopbackTest: true,
233
+ };
234
+ }
235
+ if (parsed.protocol !== "https:") {
236
+ throw egressHostError("BenignSwarm API URL for Claude Code egress allowlist must use https://");
237
+ }
238
+ const normalizedHost = validateDeclaredSecretHosts([parsed.hostname], false)[0];
239
+ const port = parsed.port ? Number(parsed.port) : 443;
240
+ if (!Number.isInteger(port) || port !== 443) {
241
+ throw egressHostError("BenignSwarm control-plane URL for Claude Code egress allowlist must use HTTPS port 443");
242
+ }
243
+ return {
244
+ origin: parsed.origin,
245
+ protocol: "https:",
246
+ hostname: normalizedHost,
247
+ port,
248
+ isLoopbackTest: false,
249
+ };
250
+ }
251
+ function readUint24(buffer, offset) {
252
+ return (buffer[offset] << 16) | (buffer[offset + 1] << 8) | buffer[offset + 2];
253
+ }
254
+ /** Extract the single visible TLS SNI from a complete ClientHello; rejects ECH and malformed frames. */
255
+ export function clientHelloServerName(handshake) {
256
+ if (handshake.length < 4 || handshake[0] !== 1 || readUint24(handshake, 1) !== handshake.length - 4)
257
+ return null;
258
+ const end = handshake.length;
259
+ let offset = 4;
260
+ const take = (length) => {
261
+ if (!Number.isSafeInteger(length) || length < 0 || offset + length > end)
262
+ return null;
263
+ const slice = handshake.subarray(offset, offset + length);
264
+ offset += length;
265
+ return slice;
266
+ };
267
+ if (!take(34))
268
+ return null;
269
+ const sessionLength = take(1)?.[0];
270
+ if (sessionLength === undefined || !take(sessionLength))
271
+ return null;
272
+ const cipherLen = take(2);
273
+ if (!cipherLen)
274
+ return null;
275
+ const cipherBytes = cipherLen.readUInt16BE(0);
276
+ if (cipherBytes < 2 || cipherBytes % 2 !== 0 || !take(cipherBytes))
277
+ return null;
278
+ const compressionLen = take(1)?.[0];
279
+ if (compressionLen === undefined || compressionLen < 1 || !take(compressionLen))
280
+ return null;
281
+ const extLenBytes = take(2);
282
+ if (!extLenBytes)
283
+ return null;
284
+ const extensions = take(extLenBytes.readUInt16BE(0));
285
+ if (!extensions || offset !== end)
286
+ return null;
287
+ let extOffset = 0;
288
+ let sni = null;
289
+ let sawSni = false;
290
+ while (extOffset < extensions.length) {
291
+ if (extOffset + 4 > extensions.length)
292
+ return null;
293
+ const type = extensions.readUInt16BE(extOffset);
294
+ const length = extensions.readUInt16BE(extOffset + 2);
295
+ extOffset += 4;
296
+ if (extOffset + length > extensions.length)
297
+ return null;
298
+ const value = extensions.subarray(extOffset, extOffset + length);
299
+ extOffset += length;
300
+ if (type === 0xfe0d)
301
+ return null; // Encrypted ClientHello hides target hostname.
302
+ if (type !== 0)
303
+ continue;
304
+ if (sawSni || value.length < 5)
305
+ return null;
306
+ sawSni = true;
307
+ const listLen = value.readUInt16BE(0);
308
+ if (listLen !== value.length - 2)
309
+ return null;
310
+ let nameOffset = 2;
311
+ while (nameOffset < value.length) {
312
+ if (nameOffset + 3 > value.length)
313
+ return null;
314
+ const nameType = value[nameOffset];
315
+ const nameLen = value.readUInt16BE(nameOffset + 1);
316
+ nameOffset += 3;
317
+ if (nameLen < 1 || nameOffset + nameLen > value.length)
318
+ return null;
319
+ const nameBytes = value.subarray(nameOffset, nameOffset + nameLen);
320
+ nameOffset += nameLen;
321
+ if (nameType === 0) {
322
+ if (sni || nameBytes.some((b) => b > 0x7f))
323
+ return null;
324
+ sni = normalizeEgressHostname(nameBytes.toString("ascii"));
325
+ if (!sni)
326
+ return null;
327
+ }
328
+ }
329
+ }
330
+ return sni;
331
+ }
332
+ async function readValidatedClientHello(socket, expectedHost, initial = Buffer.alloc(0)) {
333
+ return new Promise((resolveHello) => {
334
+ let data = Buffer.from(initial);
335
+ let handshake = Buffer.alloc(0);
336
+ let recordBytes = Buffer.alloc(0);
337
+ let settled = false;
338
+ const finish = (value) => {
339
+ if (settled)
340
+ return;
341
+ settled = true;
342
+ clearTimeout(timer);
343
+ socket.off("data", onData);
344
+ socket.off("end", onEnd);
345
+ socket.off("error", onError);
346
+ resolveHello(value);
347
+ };
348
+ const processBuffered = () => {
349
+ while (data.length >= 5) {
350
+ if (data[0] !== 22 || data[1] !== 3 || data[2] < 1 || data[2] > 4) {
351
+ finish(null);
352
+ return true;
353
+ }
354
+ const length = data.readUInt16BE(3);
355
+ if (length < 1 || length > 18_432) {
356
+ finish(null);
357
+ return true;
358
+ }
359
+ if (data.length < length + 5)
360
+ return false;
361
+ const record = data.subarray(0, length + 5);
362
+ data = data.subarray(length + 5);
363
+ recordBytes = Buffer.concat([recordBytes, record]);
364
+ handshake = Buffer.concat([handshake, record.subarray(5)]);
365
+ if (handshake.length > 65_539) {
366
+ finish(null);
367
+ return true;
368
+ }
369
+ if (handshake.length < 4)
370
+ continue;
371
+ if (handshake[0] !== 1) {
372
+ finish(null);
373
+ return true;
374
+ }
375
+ const helloLength = readUint24(handshake, 1);
376
+ if (helloLength > 65_535) {
377
+ finish(null);
378
+ return true;
379
+ }
380
+ if (handshake.length < helloLength + 4)
381
+ continue;
382
+ if (handshake.length !== helloLength + 4 || data.length !== 0) {
383
+ finish(null);
384
+ return true;
385
+ }
386
+ const hello = handshake.subarray(0, helloLength + 4);
387
+ if (clientHelloServerName(hello) !== expectedHost) {
388
+ finish(null);
389
+ return true;
390
+ }
391
+ finish(recordBytes);
392
+ return true;
393
+ }
394
+ return false;
395
+ };
396
+ const onData = (chunk) => {
397
+ data = Buffer.concat([data, chunk]);
398
+ if (data.length > 131_072) {
399
+ finish(null);
400
+ return;
401
+ }
402
+ processBuffered();
403
+ };
404
+ const onEnd = () => finish(null);
405
+ const onError = () => finish(null);
406
+ const timer = setTimeout(() => finish(null), 10_000);
407
+ if (data.length > 0 && processBuffered())
408
+ return;
409
+ socket.on("data", onData);
410
+ socket.once("end", onEnd);
411
+ socket.once("error", onError);
412
+ });
413
+ }
414
+ export async function allocateLoopbackPort(exclude) {
415
+ const tryPort = (port) => new Promise((resolveTry, rejectTry) => {
416
+ const srv = createNetServer();
417
+ srv.unref();
418
+ srv.once("error", rejectTry);
419
+ srv.listen(port, "127.0.0.1", () => {
420
+ const addr = srv.address();
421
+ const bound = typeof addr === "object" && addr ? addr.port : 0;
422
+ resolveTry({ port: bound, server: srv });
423
+ });
424
+ });
425
+ for (let i = 0; i < 24; i++) {
426
+ const candidate = 20000 + Math.floor(Math.random() * 10000);
427
+ if (exclude?.has(candidate))
428
+ continue;
429
+ try {
430
+ const { port, server } = await tryPort(candidate);
431
+ await new Promise((r) => server.close(() => r()));
432
+ if (port > 0)
433
+ return port;
434
+ }
435
+ catch {
436
+ /* port busy; try another */
437
+ }
438
+ }
439
+ const { port, server } = await tryPort(0);
440
+ await new Promise((r) => server.close(() => r()));
441
+ if (!port)
442
+ throw new Error("failed to allocate loopback proxy port");
443
+ return port;
444
+ }
445
+ export async function allocateClaudeEgressPortPair() {
446
+ const httpProxyPort = await allocateLoopbackPort();
447
+ const socksProxyPort = await allocateLoopbackPort(new Set([httpProxyPort]));
448
+ return { httpProxyPort, socksProxyPort };
449
+ }
450
+ async function authorizeAndResolveTarget(rawHost, port, policy, isHttpsTunnel) {
451
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) {
452
+ return { ok: false, reason: "blocked-port", normalizedHost: rawHost };
453
+ }
454
+ const loopbackHost = normalizeLoopbackAddress(rawHost);
455
+ if (loopbackHost) {
456
+ if (policy.controlPlane.isLoopbackTest
457
+ && loopbackHost === policy.controlPlane.hostname
458
+ && port === policy.controlPlane.port) {
459
+ return { ok: true, normalizedHost: loopbackHost, ip: loopbackHost, isLoopbackControlPlane: true };
460
+ }
461
+ return { ok: false, reason: "blocked-private-ip", normalizedHost: loopbackHost };
462
+ }
463
+ const normalizedHost = normalizeEgressHostname(rawHost);
464
+ if (!normalizedHost) {
465
+ // Numeric or malformed hosts (including octal/hex/IP literals like 169.254.169.254) stay refused.
466
+ return { ok: false, reason: isIpv4Literal(rawHost.trim()) || isIpv4Alias(rawHost.trim()) ? "blocked-private-ip" : "blocked-by-allowlist", normalizedHost: rawHost.trim().toLowerCase() };
467
+ }
468
+ if (!policy.allowedHosts.has(normalizedHost)) {
469
+ return { ok: false, reason: "blocked-by-allowlist", normalizedHost };
470
+ }
471
+ if (isHttpsTunnel) {
472
+ if (!policy.allowedHttpsPorts.has(port)) {
473
+ return { ok: false, reason: "blocked-port", normalizedHost };
474
+ }
475
+ }
476
+ else if (!policy.allowPlainHttpForTests && !policy.allowedHttpsPorts.has(port)) {
477
+ return { ok: false, reason: "blocked-port", normalizedHost };
478
+ }
479
+ let resolved;
480
+ try {
481
+ resolved = await policy.resolveFn(normalizedHost);
482
+ }
483
+ catch {
484
+ return { ok: false, reason: "dns-failed", normalizedHost };
485
+ }
486
+ if (!Array.isArray(resolved) || resolved.length === 0) {
487
+ return { ok: false, reason: "dns-failed", normalizedHost };
488
+ }
489
+ // Fail closed if ANY DNS answer returns non-public IPv4 or IPv6 (DNS rebinding guard).
490
+ for (const entry of resolved) {
491
+ if (entry.family === 4) {
492
+ if (!isPublicIpv4(entry.address))
493
+ return { ok: false, reason: "blocked-private-ip", normalizedHost };
494
+ }
495
+ else if (entry.family === 6) {
496
+ if (!isPublicIpv6(entry.address))
497
+ return { ok: false, reason: "blocked-private-ip", normalizedHost };
498
+ }
499
+ else {
500
+ return { ok: false, reason: "blocked-private-ip", normalizedHost };
501
+ }
502
+ }
503
+ const preferred = resolved.find((entry) => entry.family === 4) ?? resolved[0];
504
+ return { ok: true, normalizedHost, ip: preferred.address, isLoopbackControlPlane: false };
505
+ }
506
+ function parseAuthority(authority) {
507
+ const bracketed = /^\[([^\]]+)\]:(\d+)$/.exec(authority);
508
+ if (bracketed) {
509
+ const port = Number(bracketed[2]);
510
+ return Number.isInteger(port) && port > 0 && port <= 65535 ? { host: `[${bracketed[1]}]`, port } : null;
511
+ }
512
+ const idx = authority.lastIndexOf(":");
513
+ if (idx <= 0)
514
+ return null;
515
+ const host = authority.slice(0, idx);
516
+ const portRaw = authority.slice(idx + 1);
517
+ if (!/^\d+$/.test(portRaw))
518
+ return null;
519
+ const port = Number(portRaw);
520
+ if (!Number.isInteger(port) || port <= 0 || port > 65535)
521
+ return null;
522
+ return { host, port };
523
+ }
524
+ function sendProxyDenied(res, reason) {
525
+ if (res.headersSent) {
526
+ res.destroy();
527
+ return;
528
+ }
529
+ res.statusCode = 403;
530
+ res.setHeader("content-type", "application/json");
531
+ res.setHeader("x-proxy-error", reason);
532
+ res.end(JSON.stringify({ error: reason }));
533
+ }
534
+ function sendSocketDenied(socket, reason) {
535
+ if (socket.destroyed)
536
+ return;
537
+ socket.end(`HTTP/1.1 403 Forbidden\r\nConnection: close\r\nX-Proxy-Error: ${reason}\r\nContent-Length: 0\r\n\r\n`);
538
+ }
539
+ function handleSocks5Connection(socket, policy, record, activeSockets) {
540
+ activeSockets.add(socket);
541
+ socket.once("close", () => activeSockets.delete(socket));
542
+ let buf = Buffer.alloc(0);
543
+ let stage = "greeting";
544
+ const replySocks = (rep) => {
545
+ if (!socket.destroyed)
546
+ socket.write(Buffer.from([0x05, rep, 0x00, 0x01, 0, 0, 0, 0, 0, 0]));
547
+ };
548
+ const failSocks = (rep, host, port, reason) => {
549
+ stage = "done";
550
+ record({
551
+ protocol: "socks5",
552
+ host,
553
+ port,
554
+ decision: "denied",
555
+ reason,
556
+ statusCode: 403,
557
+ sniVerified: null,
558
+ resolvedIp: null,
559
+ bytesToUpstream: 0,
560
+ bytesFromUpstream: 0,
561
+ });
562
+ replySocks(rep);
563
+ socket.end();
564
+ };
565
+ const cleanupListeners = () => {
566
+ socket.off("data", onData);
567
+ socket.off("error", onError);
568
+ };
569
+ const onError = () => {
570
+ stage = "done";
571
+ cleanupListeners();
572
+ };
573
+ const processBuffer = () => {
574
+ if (stage === "greeting") {
575
+ if (buf.length < 2)
576
+ return;
577
+ if (buf[0] !== 0x05) {
578
+ cleanupListeners();
579
+ socket.destroy();
580
+ return;
581
+ }
582
+ const nMethods = buf[1];
583
+ if (buf.length < 2 + nMethods)
584
+ return;
585
+ const methods = buf.subarray(2, 2 + nMethods);
586
+ buf = buf.subarray(2 + nMethods);
587
+ if (!methods.includes(0x00)) {
588
+ socket.end(Buffer.from([0x05, 0xff]));
589
+ cleanupListeners();
590
+ return;
591
+ }
592
+ socket.write(Buffer.from([0x05, 0x00]));
593
+ stage = "request";
594
+ }
595
+ if (stage === "request") {
596
+ if (buf.length < 4)
597
+ return;
598
+ if (buf[0] !== 0x05) {
599
+ cleanupListeners();
600
+ socket.destroy();
601
+ return;
602
+ }
603
+ const cmd = buf[1];
604
+ const atyp = buf[3];
605
+ let targetHost = "";
606
+ let portOffset = 0;
607
+ if (atyp === 0x01) {
608
+ if (buf.length < 10)
609
+ return;
610
+ targetHost = `${buf[4]}.${buf[5]}.${buf[6]}.${buf[7]}`;
611
+ portOffset = 8;
612
+ const port = buf.readUInt16BE(portOffset);
613
+ cleanupListeners();
614
+ failSocks(0x02, targetHost, port, "blocked-private-ip");
615
+ return;
616
+ }
617
+ if (atyp === 0x04) {
618
+ if (buf.length < 22)
619
+ return;
620
+ portOffset = 20;
621
+ const port = buf.readUInt16BE(portOffset);
622
+ cleanupListeners();
623
+ failSocks(0x02, "ipv6-literal", port, "blocked-private-ip");
624
+ return;
625
+ }
626
+ if (atyp !== 0x03) {
627
+ cleanupListeners();
628
+ failSocks(0x08, "unknown", 0, "blocked-by-allowlist");
629
+ return;
630
+ }
631
+ if (buf.length < 5)
632
+ return;
633
+ const nameLen = buf[4];
634
+ if (buf.length < 5 + nameLen + 2)
635
+ return;
636
+ targetHost = buf.subarray(5, 5 + nameLen).toString("latin1");
637
+ const port = buf.readUInt16BE(5 + nameLen);
638
+ const rest = buf.subarray(5 + nameLen + 2);
639
+ stage = "done";
640
+ cleanupListeners();
641
+ if (cmd !== 0x01) {
642
+ failSocks(0x07, targetHost, port, "blocked-command");
643
+ return;
644
+ }
645
+ void (async () => {
646
+ const auth = await authorizeAndResolveTarget(targetHost, port, policy, true);
647
+ if (!auth.ok) {
648
+ failSocks(0x02, auth.normalizedHost, port, auth.reason);
649
+ return;
650
+ }
651
+ replySocks(0x00);
652
+ let initialHello = null;
653
+ if (!auth.isLoopbackControlPlane) {
654
+ initialHello = await readValidatedClientHello(socket, auth.normalizedHost, rest);
655
+ if (!initialHello) {
656
+ record({
657
+ protocol: "socks5",
658
+ host: auth.normalizedHost,
659
+ port,
660
+ decision: "denied",
661
+ reason: "blocked-sni-mismatch",
662
+ statusCode: 403,
663
+ sniVerified: false,
664
+ resolvedIp: auth.ip,
665
+ bytesToUpstream: 0,
666
+ bytesFromUpstream: 0,
667
+ });
668
+ socket.destroy();
669
+ return;
670
+ }
671
+ }
672
+ const upstream = policy.connectFn(auth.ip, port);
673
+ activeSockets.add(upstream);
674
+ upstream.once("close", () => activeSockets.delete(upstream));
675
+ let bytesToUpstream = 0;
676
+ let bytesFromUpstream = 0;
677
+ let recorded = false;
678
+ const recordAllowed = () => {
679
+ if (recorded)
680
+ return;
681
+ recorded = true;
682
+ record({
683
+ protocol: "socks5",
684
+ host: auth.normalizedHost,
685
+ port,
686
+ decision: "allowed",
687
+ reason: null,
688
+ statusCode: 200,
689
+ sniVerified: !auth.isLoopbackControlPlane,
690
+ resolvedIp: auth.ip,
691
+ bytesToUpstream,
692
+ bytesFromUpstream,
693
+ });
694
+ };
695
+ upstream.once("connect", () => {
696
+ if (initialHello) {
697
+ bytesToUpstream += initialHello.length;
698
+ upstream.write(initialHello);
699
+ }
700
+ else if (rest.length > 0) {
701
+ bytesToUpstream += rest.length;
702
+ upstream.write(rest);
703
+ }
704
+ socket.on("data", (chunk) => { bytesToUpstream += chunk.length; });
705
+ upstream.on("data", (chunk) => { bytesFromUpstream += chunk.length; });
706
+ socket.pipe(upstream);
707
+ upstream.pipe(socket);
708
+ });
709
+ upstream.once("close", recordAllowed);
710
+ upstream.once("error", () => {
711
+ record({
712
+ protocol: "socks5",
713
+ host: auth.normalizedHost,
714
+ port,
715
+ decision: "denied",
716
+ reason: "upstream-connect-failed",
717
+ statusCode: 502,
718
+ sniVerified: !auth.isLoopbackControlPlane,
719
+ resolvedIp: auth.ip,
720
+ bytesToUpstream,
721
+ bytesFromUpstream,
722
+ });
723
+ socket.destroy();
724
+ });
725
+ socket.once("close", () => {
726
+ if (!upstream.destroyed)
727
+ upstream.destroy();
728
+ });
729
+ socket.once("error", () => upstream.destroy());
730
+ })();
731
+ }
732
+ };
733
+ const onData = (chunk) => {
734
+ buf = Buffer.concat([buf, chunk]);
735
+ if (buf.length > 4096) {
736
+ cleanupListeners();
737
+ socket.destroy();
738
+ return;
739
+ }
740
+ processBuffer();
741
+ };
742
+ socket.on("data", onData);
743
+ socket.once("error", onError);
744
+ }
745
+ /**
746
+ * Start an authoritative per-session HTTP/CONNECT + SOCKS5 outer egress proxy bound to owner-only
747
+ * Unix domain sockets outside the sandboxed network namespace.
748
+ */
749
+ export async function startClaudeEgressProxy(opts) {
750
+ const provider = opts.provider ?? "anthropic";
751
+ const providerHost = provider === "deepseek" ? "api.deepseek.com" : "api.anthropic.com";
752
+ const declaredHosts = validateDeclaredSecretHosts(opts.declaredHosts, false);
753
+ const controlPlane = resolveTrustedControlPlaneOrigin({
754
+ apiUrl: opts.apiUrl,
755
+ trustedControlPlaneUrl: opts.trustedControlPlaneUrl,
756
+ allowLoopbackControlPlaneForTests: opts.allowLoopbackControlPlaneForTests,
757
+ });
758
+ const allowedHosts = new Set([providerHost, ...declaredHosts]);
759
+ if (!controlPlane.isLoopbackTest)
760
+ allowedHosts.add(controlPlane.hostname);
761
+ const policy = {
762
+ allowedHosts,
763
+ controlPlane,
764
+ allowedHttpsPorts: new Set([443, ...(opts.allowedPortsForTests ?? [])]),
765
+ allowPlainHttpForTests: opts.allowPlainHttpForTests === true,
766
+ resolveFn: opts.resolve ?? ((host) => lookup(host, { all: true, verbatim: true })),
767
+ connectFn: opts.connect ?? ((address, port) => createConnection({ host: address, port })),
768
+ };
769
+ const socketDir = opts.socketDir ?? join(tmpdir(), `b9s-claude-egress-${process.pid}-${randomBytes(6).toString("hex")}`);
770
+ mkdirSync(socketDir, { recursive: true, mode: 0o700 });
771
+ try {
772
+ chmodSync(socketDir, 0o700);
773
+ }
774
+ catch { /* ignore */ }
775
+ const httpSocketPath = join(socketDir, "http.sock");
776
+ const socksSocketPath = join(socketDir, "socks.sock");
777
+ const { httpProxyPort, socksProxyPort } = opts.httpPort && opts.socksPort
778
+ ? { httpProxyPort: opts.httpPort, socksProxyPort: opts.socksPort }
779
+ : await allocateClaudeEgressPortPair();
780
+ const recorded = [];
781
+ const pushObs = (obs) => {
782
+ recorded.push({ at: new Date().toISOString(), ...obs });
783
+ };
784
+ const activeSockets = new Set();
785
+ const httpServer = createHttpServer((req, res) => {
786
+ void (async () => {
787
+ let targetUrl;
788
+ try {
789
+ targetUrl = new URL(req.url ?? "");
790
+ }
791
+ catch {
792
+ pushObs({ protocol: "http", host: "invalid", port: 0, decision: "denied", reason: "blocked-invalid-url", statusCode: 403, sniVerified: null, resolvedIp: null, bytesToUpstream: 0, bytesFromUpstream: 0 });
793
+ sendProxyDenied(res, "blocked-invalid-url");
794
+ return;
795
+ }
796
+ if (targetUrl.username || targetUrl.password || (targetUrl.protocol !== "http:" && targetUrl.protocol !== "https:")) {
797
+ pushObs({ protocol: "http", host: targetUrl.hostname || "invalid", port: Number(targetUrl.port || 80), decision: "denied", reason: "blocked-by-allowlist", statusCode: 403, sniVerified: null, resolvedIp: null, bytesToUpstream: 0, bytesFromUpstream: 0 });
798
+ sendProxyDenied(res, "blocked-by-allowlist");
799
+ return;
800
+ }
801
+ const targetHostRaw = targetUrl.hostname;
802
+ const targetPort = targetUrl.port ? Number(targetUrl.port) : (targetUrl.protocol === "https:" ? 443 : 80);
803
+ const rawHostHeader = String(req.headers.host ?? "").split(":")[0]?.trim().toLowerCase() ?? "";
804
+ const normReqHost = targetHostRaw.startsWith("[") && targetHostRaw.endsWith("]") ? targetHostRaw.slice(1, -1).toLowerCase() : targetHostRaw.toLowerCase();
805
+ if (rawHostHeader && rawHostHeader !== normReqHost) {
806
+ pushObs({ protocol: "http", host: normReqHost, port: targetPort, decision: "denied", reason: "blocked-host-mismatch", statusCode: 403, sniVerified: null, resolvedIp: null, bytesToUpstream: 0, bytesFromUpstream: 0 });
807
+ sendProxyDenied(res, "blocked-host-mismatch");
808
+ return;
809
+ }
810
+ const auth = await authorizeAndResolveTarget(targetHostRaw, targetPort, policy, targetUrl.protocol === "https:");
811
+ if (!auth.ok) {
812
+ pushObs({ protocol: "http", host: auth.normalizedHost, port: targetPort, decision: "denied", reason: auth.reason, statusCode: 403, sniVerified: null, resolvedIp: null, bytesToUpstream: 0, bytesFromUpstream: 0 });
813
+ sendProxyDenied(res, auth.reason);
814
+ return;
815
+ }
816
+ if (!auth.isLoopbackControlPlane && !policy.allowPlainHttpForTests) {
817
+ pushObs({ protocol: "http", host: auth.normalizedHost, port: targetPort, decision: "denied", reason: "blocked-unencrypted-http", statusCode: 403, sniVerified: null, resolvedIp: auth.ip, bytesToUpstream: 0, bytesFromUpstream: 0 });
818
+ sendProxyDenied(res, "blocked-unencrypted-http");
819
+ return;
820
+ }
821
+ const forwardHeaders = {};
822
+ for (const [k, v] of Object.entries(req.headers)) {
823
+ const lower = k.toLowerCase();
824
+ if (lower === "proxy-connection" || lower === "proxy-authorization")
825
+ continue;
826
+ if (v !== undefined)
827
+ forwardHeaders[k] = v;
828
+ }
829
+ forwardHeaders.host = targetUrl.host;
830
+ forwardHeaders.connection = "close";
831
+ const reqChunks = [];
832
+ let bytesToUpstream = 0;
833
+ req.on("data", (chunk) => {
834
+ bytesToUpstream += chunk.length;
835
+ reqChunks.push(chunk);
836
+ });
837
+ req.on("end", () => {
838
+ const upstreamReq = httpRequest({
839
+ hostname: auth.normalizedHost,
840
+ port: targetPort,
841
+ path: `${targetUrl.pathname}${targetUrl.search}`,
842
+ method: req.method ?? "GET",
843
+ headers: forwardHeaders,
844
+ createConnection: () => policy.connectFn(auth.ip, targetPort),
845
+ }, (upstreamRes) => {
846
+ void (async () => {
847
+ const status = upstreamRes.statusCode ?? 502;
848
+ const location = upstreamRes.headers.location;
849
+ if (status >= 300 && status < 400 && typeof location === "string" && location.trim()) {
850
+ let redirectTarget;
851
+ try {
852
+ redirectTarget = new URL(location, targetUrl);
853
+ }
854
+ catch {
855
+ upstreamRes.destroy();
856
+ pushObs({ protocol: "http", host: auth.normalizedHost, port: targetPort, decision: "denied", reason: "blocked-redirect-target", statusCode: 403, sniVerified: null, resolvedIp: auth.ip, bytesToUpstream, bytesFromUpstream: 0 });
857
+ sendProxyDenied(res, "blocked-redirect-target");
858
+ return;
859
+ }
860
+ if ((redirectTarget.protocol !== "http:" && redirectTarget.protocol !== "https:")
861
+ || (targetUrl.protocol === "https:" && redirectTarget.protocol === "http:")) {
862
+ upstreamRes.destroy();
863
+ pushObs({ protocol: "http", host: redirectTarget.hostname || "invalid", port: Number(redirectTarget.port || 0), decision: "denied", reason: "blocked-redirect-target", statusCode: 403, sniVerified: null, resolvedIp: auth.ip, bytesToUpstream, bytesFromUpstream: 0 });
864
+ sendProxyDenied(res, "blocked-redirect-target");
865
+ return;
866
+ }
867
+ const rPort = redirectTarget.port ? Number(redirectTarget.port) : (redirectTarget.protocol === "https:" ? 443 : 80);
868
+ const rAuth = await authorizeAndResolveTarget(redirectTarget.hostname, rPort, policy, redirectTarget.protocol === "https:");
869
+ if (!rAuth.ok) {
870
+ upstreamRes.destroy();
871
+ pushObs({ protocol: "http", host: rAuth.normalizedHost, port: rPort, decision: "denied", reason: "blocked-redirect-target", statusCode: 403, sniVerified: null, resolvedIp: null, bytesToUpstream, bytesFromUpstream: 0 });
872
+ sendProxyDenied(res, "blocked-redirect-target");
873
+ return;
874
+ }
875
+ }
876
+ let bytesFromUpstream = 0;
877
+ res.statusCode = status;
878
+ for (const [k, v] of Object.entries(upstreamRes.headers)) {
879
+ if (k.toLowerCase() === "transfer-encoding")
880
+ continue;
881
+ if (v !== undefined)
882
+ res.setHeader(k, v);
883
+ }
884
+ upstreamRes.on("data", (chunk) => { bytesFromUpstream += chunk.length; });
885
+ upstreamRes.on("end", () => {
886
+ pushObs({
887
+ protocol: "http",
888
+ host: auth.normalizedHost,
889
+ port: targetPort,
890
+ decision: "allowed",
891
+ reason: null,
892
+ statusCode: status,
893
+ sniVerified: null,
894
+ resolvedIp: auth.ip,
895
+ bytesToUpstream,
896
+ bytesFromUpstream,
897
+ });
898
+ });
899
+ upstreamRes.pipe(res);
900
+ })();
901
+ });
902
+ upstreamReq.on("error", () => {
903
+ pushObs({ protocol: "http", host: auth.normalizedHost, port: targetPort, decision: "denied", reason: "upstream-connect-failed", statusCode: 502, sniVerified: null, resolvedIp: auth.ip, bytesToUpstream, bytesFromUpstream: 0 });
904
+ sendProxyDenied(res, "upstream-connect-failed");
905
+ });
906
+ if (reqChunks.length)
907
+ upstreamReq.write(Buffer.concat(reqChunks));
908
+ upstreamReq.end();
909
+ });
910
+ })();
911
+ });
912
+ httpServer.on("connect", (req, clientSocket, head) => {
913
+ activeSockets.add(clientSocket);
914
+ clientSocket.once("close", () => activeSockets.delete(clientSocket));
915
+ void (async () => {
916
+ const parsed = parseAuthority(req.url ?? "");
917
+ if (!parsed) {
918
+ pushObs({ protocol: "connect", host: req.url ?? "invalid", port: 0, decision: "denied", reason: "blocked-by-allowlist", statusCode: 403, sniVerified: null, resolvedIp: null, bytesToUpstream: 0, bytesFromUpstream: 0 });
919
+ sendSocketDenied(clientSocket, "blocked-by-allowlist");
920
+ return;
921
+ }
922
+ const rawConnectHostHdr = String(req.headers.host ?? "").trim();
923
+ const connectHostWithoutPort = rawConnectHostHdr.startsWith("[")
924
+ ? rawConnectHostHdr.slice(1, rawConnectHostHdr.indexOf("]")).toLowerCase()
925
+ : rawConnectHostHdr.split(":")[0]?.trim().toLowerCase() ?? "";
926
+ const normConnectTarget = parsed.host.startsWith("[") && parsed.host.endsWith("]")
927
+ ? parsed.host.slice(1, -1).toLowerCase()
928
+ : parsed.host.toLowerCase();
929
+ if (connectHostWithoutPort && connectHostWithoutPort !== normConnectTarget) {
930
+ pushObs({ protocol: "connect", host: normConnectTarget, port: parsed.port, decision: "denied", reason: "blocked-host-mismatch", statusCode: 403, sniVerified: null, resolvedIp: null, bytesToUpstream: 0, bytesFromUpstream: 0 });
931
+ sendSocketDenied(clientSocket, "blocked-host-mismatch");
932
+ return;
933
+ }
934
+ const auth = await authorizeAndResolveTarget(parsed.host, parsed.port, policy, true);
935
+ if (!auth.ok) {
936
+ pushObs({ protocol: "connect", host: auth.normalizedHost, port: parsed.port, decision: "denied", reason: auth.reason, statusCode: 403, sniVerified: null, resolvedIp: null, bytesToUpstream: 0, bytesFromUpstream: 0 });
937
+ sendSocketDenied(clientSocket, auth.reason);
938
+ return;
939
+ }
940
+ clientSocket.write("HTTP/1.1 200 Connection Established\r\nProxy-Agent: b9s-claude-egress\r\n\r\n");
941
+ let initialHello = null;
942
+ if (!auth.isLoopbackControlPlane) {
943
+ initialHello = await readValidatedClientHello(clientSocket, auth.normalizedHost, head);
944
+ if (!initialHello) {
945
+ pushObs({ protocol: "connect", host: auth.normalizedHost, port: parsed.port, decision: "denied", reason: "blocked-sni-mismatch", statusCode: 403, sniVerified: false, resolvedIp: auth.ip, bytesToUpstream: 0, bytesFromUpstream: 0 });
946
+ clientSocket.destroy();
947
+ return;
948
+ }
949
+ }
950
+ const upstream = policy.connectFn(auth.ip, parsed.port);
951
+ activeSockets.add(upstream);
952
+ upstream.once("close", () => activeSockets.delete(upstream));
953
+ let bytesToUpstream = 0;
954
+ let bytesFromUpstream = 0;
955
+ let recordedConnect = false;
956
+ const flushConnectObs = () => {
957
+ if (recordedConnect)
958
+ return;
959
+ recordedConnect = true;
960
+ pushObs({
961
+ protocol: "connect",
962
+ host: auth.normalizedHost,
963
+ port: parsed.port,
964
+ decision: "allowed",
965
+ reason: null,
966
+ statusCode: 200,
967
+ sniVerified: !auth.isLoopbackControlPlane,
968
+ resolvedIp: auth.ip,
969
+ bytesToUpstream,
970
+ bytesFromUpstream,
971
+ });
972
+ };
973
+ upstream.once("connect", () => {
974
+ if (initialHello) {
975
+ bytesToUpstream += initialHello.length;
976
+ upstream.write(initialHello);
977
+ }
978
+ else if (head.length > 0) {
979
+ bytesToUpstream += head.length;
980
+ upstream.write(head);
981
+ }
982
+ clientSocket.on("data", (chunk) => { bytesToUpstream += chunk.length; });
983
+ upstream.on("data", (chunk) => { bytesFromUpstream += chunk.length; });
984
+ clientSocket.pipe(upstream);
985
+ upstream.pipe(clientSocket);
986
+ });
987
+ upstream.once("close", flushConnectObs);
988
+ upstream.once("error", () => {
989
+ pushObs({ protocol: "connect", host: auth.normalizedHost, port: parsed.port, decision: "denied", reason: "upstream-connect-failed", statusCode: 502, sniVerified: !auth.isLoopbackControlPlane, resolvedIp: auth.ip, bytesToUpstream, bytesFromUpstream });
990
+ clientSocket.destroy();
991
+ });
992
+ clientSocket.once("close", () => {
993
+ if (!upstream.destroyed)
994
+ upstream.destroy();
995
+ });
996
+ clientSocket.once("error", () => upstream.destroy());
997
+ })();
998
+ });
999
+ const socksServer = createNetServer((socket) => {
1000
+ handleSocks5Connection(socket, policy, pushObs, activeSockets);
1001
+ });
1002
+ rmSync(httpSocketPath, { force: true });
1003
+ rmSync(socksSocketPath, { force: true });
1004
+ await new Promise((resolveListen, reject) => {
1005
+ httpServer.once("error", reject);
1006
+ httpServer.listen(httpSocketPath, () => {
1007
+ try {
1008
+ chmodSync(httpSocketPath, 0o600);
1009
+ }
1010
+ catch { /* ignore */ }
1011
+ resolveListen();
1012
+ });
1013
+ });
1014
+ await new Promise((resolveListen, reject) => {
1015
+ socksServer.once("error", reject);
1016
+ socksServer.listen(socksSocketPath, () => {
1017
+ try {
1018
+ chmodSync(socksSocketPath, 0o600);
1019
+ }
1020
+ catch { /* ignore */ }
1021
+ resolveListen();
1022
+ });
1023
+ });
1024
+ return {
1025
+ socketDir,
1026
+ httpSocketPath,
1027
+ socksSocketPath,
1028
+ httpPort: httpProxyPort,
1029
+ socksPort: socksProxyPort,
1030
+ allowedHosts: [...allowedHosts, ...(controlPlane.isLoopbackTest ? [controlPlane.hostname] : [])],
1031
+ controlPlane,
1032
+ observations: () => [...recorded],
1033
+ async close() {
1034
+ for (const s of activeSockets) {
1035
+ try {
1036
+ s.destroy();
1037
+ }
1038
+ catch { /* ignore */ }
1039
+ }
1040
+ httpServer.closeAllConnections?.();
1041
+ await new Promise((r) => httpServer.close(() => r()));
1042
+ await new Promise((r) => socksServer.close(() => r()));
1043
+ rmSync(socketDir, { recursive: true, force: true });
1044
+ },
1045
+ };
1046
+ }
1047
+ /** Build the inner netns bridge script exposing outer Unix proxy sockets on isolated lo ports. */
1048
+ export function buildClaudeEgressNetnsBridgeScript(params) {
1049
+ const lines = [
1050
+ "set -eu",
1051
+ `HTTP_PORT=${params.httpPort}`,
1052
+ `SOCKS_PORT=${params.socksPort}`,
1053
+ `socat "TCP-LISTEN:${params.httpPort},bind=127.0.0.1,reuseaddr,fork" "UNIX-CONNECT:${params.httpSocketPath}" >/dev/null 2>&1 &`,
1054
+ `HTTP_BRIDGE_PID=$!`,
1055
+ `socat "TCP-LISTEN:${params.socksPort},bind=127.0.0.1,reuseaddr,fork" "UNIX-CONNECT:${params.socksSocketPath}" >/dev/null 2>&1 &`,
1056
+ `SOCKS_BRIDGE_PID=$!`,
1057
+ "cleanup() { kill \"$HTTP_BRIDGE_PID\" \"$SOCKS_BRIDGE_PID\" 2>/dev/null || true; }",
1058
+ "trap cleanup EXIT INT TERM",
1059
+ "i=0",
1060
+ "while [ \"$i\" -lt 100 ]; do",
1061
+ " if socat -T0.05 OPEN:/dev/null \"TCP:127.0.0.1:$HTTP_PORT\" >/dev/null 2>&1 && socat -T0.05 OPEN:/dev/null \"TCP:127.0.0.1:$SOCKS_PORT\" >/dev/null 2>&1; then break; fi",
1062
+ " if ! kill -0 \"$HTTP_BRIDGE_PID\" 2>/dev/null || ! kill -0 \"$SOCKS_BRIDGE_PID\" 2>/dev/null; then exit 125; fi",
1063
+ " i=$((i + 1))",
1064
+ " sleep 0.02",
1065
+ "done",
1066
+ "export HTTP_PROXY=\"http://127.0.0.1:$HTTP_PORT\"",
1067
+ "export HTTPS_PROXY=\"http://127.0.0.1:$HTTP_PORT\"",
1068
+ "export http_proxy=\"http://127.0.0.1:$HTTP_PORT\"",
1069
+ "export https_proxy=\"http://127.0.0.1:$HTTP_PORT\"",
1070
+ "export ALL_PROXY=\"socks5h://127.0.0.1:$SOCKS_PORT\"",
1071
+ "export all_proxy=\"socks5h://127.0.0.1:$SOCKS_PORT\"",
1072
+ "unset NO_PROXY no_proxy || true",
1073
+ "export NODE_USE_ENV_PROXY=1",
1074
+ ];
1075
+ if (params.mode === "shell") {
1076
+ lines.push('/bin/sh -c "$1" &');
1077
+ lines.push("CHILD_PID=$!");
1078
+ lines.push("trap 'kill \"$CHILD_PID\" 2>/dev/null || true; cleanup' INT TERM");
1079
+ lines.push("wait \"$CHILD_PID\"");
1080
+ }
1081
+ else {
1082
+ lines.push("\"$@\" &");
1083
+ lines.push("CHILD_PID=$!");
1084
+ lines.push("trap 'kill \"$CHILD_PID\" 2>/dev/null || true; cleanup' INT TERM");
1085
+ lines.push("wait \"$CHILD_PID\"");
1086
+ }
1087
+ return lines.join("\n");
1088
+ }
1089
+ export function claudeEgressRunnerModulePath() {
1090
+ return fileURLToPath(import.meta.url);
1091
+ }
1092
+ function cleanSandboxParentEnv(baseEnv) {
1093
+ const cleaned = { ...baseEnv };
1094
+ for (const key of ["HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy", "NODE_USE_ENV_PROXY"]) {
1095
+ delete cleaned[key];
1096
+ }
1097
+ return cleaned;
1098
+ }
1099
+ /** Spawn an arbitrary command inside an isolated bwrap --unshare-net + socat + outer b9s proxy session. */
1100
+ export async function spawnInsideClaudeEgressSandbox(params) {
1101
+ if (platform() !== "linux") {
1102
+ throw egressHostError("Claude Code outer netns egress boundary is only supported on Linux");
1103
+ }
1104
+ const bridgeScript = buildClaudeEgressNetnsBridgeScript({
1105
+ httpSocketPath: params.proxy.httpSocketPath,
1106
+ socksSocketPath: params.proxy.socksSocketPath,
1107
+ httpPort: params.proxy.httpPort,
1108
+ socksPort: params.proxy.socksPort,
1109
+ mode: "exec",
1110
+ });
1111
+ return spawn("bwrap", ["--bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--unshare-net", "--die-with-parent", "--", "/bin/sh", "-c", bridgeScript, "b9s-claude-egress", params.bin, ...params.args], {
1112
+ cwd: params.cwd,
1113
+ env: cleanSandboxParentEnv(params.env),
1114
+ detached: params.detached ?? false,
1115
+ stdio: (params.stdio ?? ["ignore", "pipe", "pipe"]),
1116
+ });
1117
+ }
1118
+ function shellQuote(v) {
1119
+ return `'${v.replace(/'/g, "'\\''")}'`;
1120
+ }
1121
+ /** Command line for supervisor entrypoint spawned inside watch.ts shell turn delivery. */
1122
+ export function buildClaudeEgressSupervisedShellCommand() {
1123
+ return `exec ${shellQuote(process.execPath)} ${shellQuote(claudeEgressRunnerModulePath())} --claude-egress-runner`;
1124
+ }
1125
+ export function spawnClaudeEgressSupervised(params) {
1126
+ return spawn(process.execPath, [claudeEgressRunnerModulePath(), "--claude-egress-runner"], {
1127
+ cwd: params.cwd,
1128
+ env: {
1129
+ ...params.env,
1130
+ [EGRESS_RUNNER_CONFIG_ENV]: JSON.stringify(params.config),
1131
+ },
1132
+ stdio: params.stdio,
1133
+ detached: params.detached,
1134
+ });
1135
+ }
1136
+ /** Deterministically test proxy redirect + private-IP enforcement against a local transient target server. */
1137
+ export async function verifyOuterProxyBoundarySelfCheck() {
1138
+ const upstream = createHttpServer((req, res) => {
1139
+ if ((req.url ?? "").startsWith("/redirect-private")) {
1140
+ res.statusCode = 302;
1141
+ res.setHeader("location", "http://169.254.169.254/latest/meta-data/");
1142
+ res.end();
1143
+ return;
1144
+ }
1145
+ if ((req.url ?? "").startsWith("/redirect-undeclared")) {
1146
+ res.statusCode = 302;
1147
+ res.setHeader("location", "https://example.com/");
1148
+ res.end();
1149
+ return;
1150
+ }
1151
+ res.statusCode = 200;
1152
+ res.end("ok");
1153
+ });
1154
+ await new Promise((r) => upstream.listen(0, "127.0.0.1", r));
1155
+ const addr = upstream.address();
1156
+ const upPort = typeof addr === "object" && addr ? addr.port : 0;
1157
+ const controlUrl = `http://127.0.0.1:${upPort}`;
1158
+ let proxy = null;
1159
+ let tcpBridge = null;
1160
+ const bridgeSockets = new Set();
1161
+ try {
1162
+ proxy = await startClaudeEgressProxy({
1163
+ declaredHosts: ["registry.npmjs.org"],
1164
+ apiUrl: controlUrl,
1165
+ trustedControlPlaneUrl: controlUrl,
1166
+ allowLoopbackControlPlaneForTests: true,
1167
+ allowPlainHttpForTests: true,
1168
+ httpPort: 3128,
1169
+ socksPort: 3129,
1170
+ resolve: async (host) => {
1171
+ if (host === "rebind-private.example.org")
1172
+ return [{ address: "10.0.0.1", family: 4 }];
1173
+ if (host === "registry.npmjs.org")
1174
+ return [{ address: "127.0.0.1", family: 4 }]; // triggers private-ip refusal!
1175
+ return [];
1176
+ },
1177
+ });
1178
+ tcpBridge = createNetServer((client) => {
1179
+ const sock = createConnection(proxy.httpSocketPath);
1180
+ bridgeSockets.add(client);
1181
+ bridgeSockets.add(sock);
1182
+ client.once("close", () => bridgeSockets.delete(client));
1183
+ sock.once("close", () => bridgeSockets.delete(sock));
1184
+ client.pipe(sock);
1185
+ sock.pipe(client);
1186
+ client.on("error", () => sock.destroy());
1187
+ sock.on("error", () => client.destroy());
1188
+ });
1189
+ await new Promise((r, reject) => {
1190
+ tcpBridge.once("error", reject);
1191
+ tcpBridge.listen(0, "127.0.0.1", () => r());
1192
+ });
1193
+ const bridgeAddr = tcpBridge.address();
1194
+ const proxyTcpPort = typeof bridgeAddr === "object" && bridgeAddr ? bridgeAddr.port : 0;
1195
+ const proxyGet = (targetUrl) => new Promise((resolveGet, reject) => {
1196
+ const parsed = new URL(targetUrl);
1197
+ const req = httpRequest({
1198
+ host: "127.0.0.1",
1199
+ port: proxyTcpPort,
1200
+ path: targetUrl,
1201
+ method: "GET",
1202
+ agent: false,
1203
+ headers: { host: parsed.host, connection: "close" },
1204
+ }, (res) => {
1205
+ res.resume();
1206
+ res.on("end", () => resolveGet({
1207
+ status: res.statusCode ?? 0,
1208
+ errHeader: typeof res.headers["x-proxy-error"] === "string" ? res.headers["x-proxy-error"] : null,
1209
+ }));
1210
+ });
1211
+ req.on("error", reject);
1212
+ req.end();
1213
+ });
1214
+ const rPrivate = await proxyGet(`${controlUrl}/redirect-private`);
1215
+ const rUndeclared = await proxyGet(`${controlUrl}/redirect-undeclared`);
1216
+ const pLiteral = await proxyGet("http://169.254.169.254/latest/meta-data/");
1217
+ const pDns = await proxyGet("https://registry.npmjs.org/pkg");
1218
+ const redirectBlocked = rPrivate.status === 403 && rPrivate.errHeader === "blocked-redirect-target"
1219
+ && rUndeclared.status === 403 && rUndeclared.errHeader === "blocked-redirect-target";
1220
+ const privateIpBlocked = pLiteral.status === 403 && pDns.status === 403 && pDns.errHeader === "blocked-private-ip";
1221
+ return {
1222
+ redirect_blocked: redirectBlocked,
1223
+ private_ip_blocked: privateIpBlocked,
1224
+ detail: redirectBlocked && privateIpBlocked ? null : "outer proxy self-check did not block every redirect or private-IP target",
1225
+ };
1226
+ }
1227
+ finally {
1228
+ for (const s of bridgeSockets) {
1229
+ try {
1230
+ s.destroy();
1231
+ }
1232
+ catch { /* ignore */ }
1233
+ }
1234
+ if (tcpBridge)
1235
+ await new Promise((r) => tcpBridge.close(() => r()));
1236
+ if (proxy)
1237
+ await proxy.close();
1238
+ upstream.closeAllConnections?.();
1239
+ await new Promise((r) => upstream.close(() => r()));
1240
+ }
1241
+ }
1242
+ async function runSupervisedMain() {
1243
+ const rawCfg = process.env[EGRESS_RUNNER_CONFIG_ENV];
1244
+ delete process.env[EGRESS_RUNNER_CONFIG_ENV];
1245
+ if (!rawCfg) {
1246
+ process.stderr.write("b9s: missing Claude Code outer egress configuration\n");
1247
+ process.exit(125);
1248
+ }
1249
+ let cfg;
1250
+ try {
1251
+ cfg = JSON.parse(rawCfg);
1252
+ }
1253
+ catch {
1254
+ process.stderr.write("b9s: invalid Claude Code outer egress configuration\n");
1255
+ process.exit(125);
1256
+ }
1257
+ const missing = ["bwrap", "socat"].filter((cmd) => spawnSync("/bin/sh", ["-c", `command -v ${cmd}`], { encoding: "utf8" }).status !== 0);
1258
+ if (missing.length) {
1259
+ process.stderr.write(`secret_egress_unenforced_claude-code: ${missing.join(" and ")} unavailable\n`);
1260
+ process.exit(125);
1261
+ }
1262
+ const proxy = await startClaudeEgressProxy({
1263
+ declaredHosts: cfg.declaredHosts,
1264
+ apiUrl: cfg.apiUrl,
1265
+ trustedControlPlaneUrl: cfg.trustedControlPlaneUrl,
1266
+ allowLoopbackControlPlaneForTests: cfg.allowLoopbackControlPlaneForTests,
1267
+ provider: cfg.provider,
1268
+ httpPort: cfg.httpProxyPort,
1269
+ socksPort: cfg.socksProxyPort,
1270
+ });
1271
+ const bridgeScript = buildClaudeEgressNetnsBridgeScript({
1272
+ httpSocketPath: proxy.httpSocketPath,
1273
+ socksSocketPath: proxy.socksSocketPath,
1274
+ httpPort: proxy.httpPort,
1275
+ socksPort: proxy.socksPort,
1276
+ mode: cfg.mode,
1277
+ });
1278
+ const bwrapArgs = cfg.mode === "shell"
1279
+ ? ["--bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--unshare-net", "--die-with-parent", "--", "/bin/sh", "-c", bridgeScript, "b9s-claude-egress", cfg.shellCommand ?? ""]
1280
+ : ["--bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--unshare-net", "--die-with-parent", "--", "/bin/sh", "-c", bridgeScript, "b9s-claude-egress", cfg.bin ?? "claude", ...(cfg.args ?? [])];
1281
+ const child = spawn("bwrap", bwrapArgs, { cwd: process.cwd(), env: cleanSandboxParentEnv(process.env), stdio: "inherit" });
1282
+ const forwardSignal = (sig) => {
1283
+ try {
1284
+ child.kill(sig);
1285
+ }
1286
+ catch { /* ignore */ }
1287
+ };
1288
+ process.on("SIGTERM", () => forwardSignal("SIGTERM"));
1289
+ process.on("SIGINT", () => forwardSignal("SIGINT"));
1290
+ const outcome = await new Promise((resolveExit) => {
1291
+ child.once("error", () => resolveExit({ code: 127, signal: null }));
1292
+ child.once("exit", (code, signal) => resolveExit({ code, signal }));
1293
+ });
1294
+ await proxy.close();
1295
+ if (outcome.signal)
1296
+ process.kill(process.pid, outcome.signal);
1297
+ process.exit(outcome.code ?? 1);
1298
+ }
1299
+ const isEntrypoint = (() => {
1300
+ try {
1301
+ return Boolean(process.argv[1] && process.argv.includes("--claude-egress-runner") && realpathSync(process.argv[1]) === realpathSync(resolve(fileURLToPath(import.meta.url))));
1302
+ }
1303
+ catch {
1304
+ return false;
1305
+ }
1306
+ })();
1307
+ if (isEntrypoint) {
1308
+ void runSupervisedMain().catch((error) => {
1309
+ process.stderr.write(`${error.message || String(error)}\n`);
1310
+ process.exit(125);
1311
+ });
1312
+ }