barebox 0.1.0 → 0.3.0

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.
package/src/proxy.js ADDED
@@ -0,0 +1,572 @@
1
+ // Proxy: the front door. Terminates agent TLS with per-host certificates
2
+ // minted on demand, sees every request through a private stdlib http.Server
3
+ // (so HEAD, 204/304, chunked, keep-alive and slow upstreams just work),
4
+ // forwards with https/http.request, and optionally parks matching requests
5
+ // for a human decision. Identity = socket: each agent has its own unix
6
+ // listener, and every log line and hold names the agent, never `c<n>`.
7
+ //
8
+ // Timeout shape: the client idle clock is the server's keep-alive timeout —
9
+ // by construction it only ticks when no request is in flight. The upstream
10
+ // response gets its own much longer clock.
11
+ import net from 'node:net';
12
+ import tls from 'node:tls';
13
+ import http from 'node:http';
14
+ import https from 'node:https';
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ import { ensureCA, certFor, HOST_RE } from './certs.js';
18
+ import { createHolds } from './holds.js';
19
+ import { claimRuntime, runtimePaths } from './runtime.js';
20
+ import { checkUpstream } from './wall.js';
21
+
22
+ const AGENT = Symbol('agent');
23
+ const SECURE = Symbol('secure');
24
+ const IP_RE = /^\d+\.\d+\.\d+\.\d+$/;
25
+ // Hop-by-hop headers must not be forwarded: node's HTTP stack re-frames.
26
+ const HOP_REQ = new Set(['proxy-connection', 'proxy-authorization']);
27
+ const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
28
+ 'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade']);
29
+
30
+ // Secrets never land in the audit log verbatim: Authorization-style header
31
+ // values are replaced with a fixed marker before an entry is written. The
32
+ // user's `redact` hook runs after this scrubbing, so it sees (and further
33
+ // shapes) an already-safe entry. Bodies stay logged as-is.
34
+ const REDACTED = '[redacted]';
35
+ // Interim set (M3 replaces this with bareguard's `secrets` redaction): header names whose values never land verbatim.
36
+ const SENSITIVE_HEADERS = new Set(['authorization', 'proxy-authorization',
37
+ 'cookie', 'set-cookie', 'x-api-key', 'x-auth-token', 'api-key']);
38
+
39
+ /**
40
+ * Copy a log entry with sensitive header values replaced by `[redacted]`.
41
+ * The caller's headers object is never mutated.
42
+ *
43
+ * @param {Record<string, unknown>} entry log entry about to be written
44
+ * @returns {Record<string, unknown>} entry with secrets scrubbed
45
+ */
46
+ function scrubSecrets(entry) {
47
+ const h = entry['headers'];
48
+ if (!h || typeof h !== 'object') return entry;
49
+ const src = /** @type {Record<string, unknown>} */ (h);
50
+ if (!Object.keys(src).some((k) => SENSITIVE_HEADERS.has(k.toLowerCase()))) return entry;
51
+ const headers = { ...src };
52
+ for (const k of Object.keys(headers)) {
53
+ if (SENSITIVE_HEADERS.has(k.toLowerCase())) headers[k] = REDACTED;
54
+ }
55
+ return { ...entry, headers };
56
+ }
57
+
58
+ /**
59
+ * Options for {@link createProxy}.
60
+ *
61
+ * @typedef {object} ProxyOptions
62
+ * @property {string} logFile JSON-lines log path (`req`, `resp`, `deny`, `hold`, `decide`, `hold-abandoned`)
63
+ * @property {string} runtime runtime dir; required. Holds the CA + minted host certs (`certs/`, see `runtime.js`), the agent sockets, and the hold queue files.
64
+ * @property {number} [port] opt-in TCP listener for tests, bound to 127.0.0.1 only (default: none)
65
+ * @property {string} [upstreamCa] extra PEM the proxy trusts for upstream TLS, on top of system roots
66
+ * @property {HoldOptions} [hold] hold queue config, or omit to forward everything
67
+ * @property {number} [upstreamTimeoutMs] give up on an upstream response after this (default 120000)
68
+ * @property {object} [unsafeTestOnly] TEST-ONLY escape hatch: everything under
69
+ * it weakens the sandbox wall, so production omits it and tests name it loudly.
70
+ * @property {boolean} [unsafeTestOnly.allowLoopback] let loopback and unspecified
71
+ * destinations through (default false). Fixture servers listen on 127.0.0.1,
72
+ * so tests pass this; production never should.
73
+ * @property {(host: string) => Promise<string[] | string | null>} [unsafeTestOnly.resolveUpstream]
74
+ * DNS stub: replaces the wall's resolver so rebinding is testable. Production omits it.
75
+ * @property {number} [clientIdleMs] kill a client tunnel idle this long; never fires mid-request (default 60000)
76
+ * @property {number} [maxLogBody] log at most this many request-body bytes, then `truncated: true` (default 1048576)
77
+ * @property {(entry: Record<string, unknown>) => Record<string, unknown>} [redact] log redaction hook, applied after built-in secret scrubbing (default: identity)
78
+ */
79
+
80
+ /**
81
+ * Hold queue options (the decision seam lives in holds.js).
82
+ *
83
+ * @typedef {object} HoldOptions
84
+ * @property {string} [match] path substring that parks a request (default decision)
85
+ * @property {import('./holds.js').ShouldHold} [shouldHold] decision function; overrides `match`
86
+ * @property {number|string} [timeoutMs] hold deadline in ms, or `'never'` (default 120000)
87
+ * @property {number} [maxBody] bodies over this are denied at the door, never queued (default 1048576)
88
+ * @property {import('./holds.js').OnAsk|null} [onAsk] ask seam (bareguard `humanChannel` shape).
89
+ * When present no files are involved; omit it for the default file checkpoint
90
+ * (`<runtime>/asks` + `<runtime>/answers`, `sbx pending/approve/deny`).
91
+ * @property {number} [pollMs] answer poll interval in ms for the file checkpoint (default 250)
92
+ * @property {import('./holds.js').OnEvent} [onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle
93
+ */
94
+
95
+ /**
96
+ * One upstream forwarding: buffered body (approve path) or live stream.
97
+ *
98
+ * @typedef {object} ForwardArgs
99
+ * @property {string} agent agent name (its socket)
100
+ * @property {string} method HTTP method
101
+ * @property {string} url full URL
102
+ * @property {Record<string, string | string[] | undefined>} headers
103
+ * @property {Buffer} [body] buffered body (approve path)
104
+ * @property {import('node:http').IncomingMessage} [stream] live body (direct path)
105
+ * @property {import('node:http').ServerResponse} cres parked or live client response
106
+ */
107
+
108
+ /**
109
+ * Live proxy. Let `tsc` infer the shape; adopters import the name.
110
+ *
111
+ * @typedef {ReturnType<typeof createProxy>} Proxy
112
+ */
113
+
114
+ /**
115
+ * Start the front-door proxy. Every request is logged with its method, URL,
116
+ * headers and body; bytes go upstream untouched. Requests the hold rule
117
+ * flags park for a human decision instead of forwarding.
118
+ *
119
+ * @param {ProxyOptions} opts
120
+ * @returns live proxy: `ready` resolves when listeners + CA are up; the shape is inferred, see `Proxy`
121
+ * @when Reach for this HARNESS-ONLY to run the front door: it terminates agent TLS, sees every request, and parks the ones a human must decide. It decides nothing itself; pair with the launcher for sandboxes and `sbx` for decisions.
122
+ * @fails Throws synchronously on a missing `logFile` or `runtime`. Throws when another live proxy owns the runtime; the claim dies with its process; nothing is ever taken over. At runtime, dead upstreams, malformed input, over-cap and timed-out holds all become loud logged HTTP errors, never silence and never a crash. A second proxy on the same port rejects `ready`, never crashes the process.
123
+ * @example
124
+ * import { createProxy } from "barebox";
125
+ * const proxy = createProxy({ port: 0, runtime: "./sbx-runtime", logFile: "./mitm.log" });
126
+ * const { port } = await proxy.ready;
127
+ * await proxy.close();
128
+ */
129
+ export function createProxy(opts) {
130
+ const { logFile, runtime, port = null,
131
+ upstreamCa = null, hold = null,
132
+ upstreamTimeoutMs = 120000, clientIdleMs = 60000,
133
+ unsafeTestOnly = null,
134
+ maxLogBody = 1048576, redact = (e) => e } = opts ?? {};
135
+ const { allowLoopback = false, resolveUpstream = null } = unsafeTestOnly ?? {};
136
+ const gate = { allowLoopback, resolveUpstream: resolveUpstream ?? undefined };
137
+ if (!logFile) throw new Error('createProxy: logFile is required');
138
+ if (typeof runtime !== 'string' || !runtime) throw new Error('createProxy: runtime is required');
139
+ // One live proxy per runtime, enforced here: claimed before the hold
140
+ // queue clears `asks/` and `answers/`, so that clearing can never wipe a
141
+ // live owner's files — only a dead owner's leftovers can be there.
142
+ const releaseClaim = claimRuntime(runtime);
143
+ // Always `<runtime>/certs`: one layout, owned by runtime.js, so there is
144
+ // nothing to contain and no check to fail.
145
+ const certDir = runtimePaths(runtime).certsDir;
146
+ const holdMaxBody = hold?.maxBody ?? 1048576;
147
+
148
+ const logStream = fs.createWriteStream(logFile, { flags: 'a', mode: 0o600 });
149
+ // `mode` applies only at creation: a 0644 log from an older run would stay
150
+ // world-readable while new lines append, so fix it up on every start. A
151
+ // not-yet-created file throws here and is created 0600 by the stream.
152
+ try { fs.chmodSync(logFile, 0o600); } catch {}
153
+ const log = (o) => { logStream.write(JSON.stringify(redact(scrubSecrets(o))) + '\n'); };
154
+ let trust = null;
155
+ if (upstreamCa) {
156
+ let extra;
157
+ try { extra = fs.readFileSync(upstreamCa, 'utf8'); }
158
+ catch (e) {
159
+ releaseClaim();
160
+ throw new Error(`createProxy: cannot read upstreamCa: ${e.message}`);
161
+ }
162
+ trust = [...tls.rootCertificates, extra];
163
+ }
164
+
165
+ /** @type {Set<import('node:net').Socket>} */
166
+ const clients = new Set();
167
+ /** @type {Set<import('node:http').ClientRequest>} */
168
+ const upstreams = new Set();
169
+ const agentServers = new Map();
170
+ /** @type {import('node:net').Server|null} */
171
+ let tcp = null;
172
+ let closed = false;
173
+
174
+ const agentOf = (sock) => sock[AGENT] ?? 'tcp';
175
+
176
+ // The one writer of a proxied HTTP error: logs it, answers it.
177
+ function denyRes(cres, code, note) {
178
+ const sock = cres.socket;
179
+ log({ ev: 'deny', agent: agentOf(sock), code, note });
180
+ try {
181
+ if (!cres.headersSent && !sock.destroyed) {
182
+ cres.writeHead(code, { 'content-type': 'text/plain', connection: 'close' });
183
+ }
184
+ if (!sock.destroyed) cres.end(`${note}\n`);
185
+ } catch {}
186
+ }
187
+
188
+ // Pre-HTTP raw sockets only (CONNECT line, oversized head, walled CONNECT, cert failure).
189
+ function denyRaw(sock, code, note) {
190
+ log({ ev: 'deny', agent: agentOf(sock), code, note });
191
+ if (sock.destroyed) return;
192
+ try { sock.end(`HTTP/1.1 ${code} ${note}\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n${note}\n`); }
193
+ catch {}
194
+ }
195
+
196
+ // Enforcement sits here (every forward, incl. the approve path) AND at
197
+ // the door (request handler + CONNECT): a parked hold is re-checked on
198
+ // approve, so a DNS change while parked cannot slip through.
199
+ /** @param {ForwardArgs} args */
200
+ async function forward({ agent, method, url, headers, body, stream, cres }) {
201
+ let u;
202
+ try {
203
+ u = new URL(url);
204
+ } catch {
205
+ denyRes(cres, 400, 'bad request target');
206
+ return;
207
+ }
208
+ const verdict = await checkUpstream(u.hostname, gate);
209
+ if (!verdict.ok) {
210
+ try { stream?.resume(); } catch {}
211
+ denyRes(cres, 403, verdict.reason);
212
+ return;
213
+ }
214
+ // Sync from here: forwardInner answers every failure itself, but a
215
+ // throw before it can answer must still be loud, never a floating reject.
216
+ // The dial is pinned to the checked IPs: no second DNS resolution.
217
+ try {
218
+ forwardInner({ agent, method, url, headers, body, stream, cres, u, upstreamIps: verdict.ips });
219
+ } catch (e) {
220
+ // The live stream arrives paused (see handleRequest): unpause so no
221
+ // paused stream leaks on this path.
222
+ try { stream?.resume(); } catch {}
223
+ denyRes(cres, 502, `upstream failed: ${e.message}`);
224
+ }
225
+ }
226
+
227
+ /** @param {ForwardArgs & { u: URL, upstreamIps: string[] }} args */
228
+ function forwardInner({ agent, method, url, headers, body, stream, cres, u, upstreamIps }) {
229
+ const sock = cres.socket;
230
+ if (!sock) return; // no transport left to answer on
231
+ const secure = u.protocol === 'https:';
232
+ /** @type {Record<string, string | string[] | undefined>} */
233
+ const fwdHeaders = {};
234
+ for (const [k, v] of Object.entries(headers)) {
235
+ if (!HOP_REQ.has(k.toLowerCase())) fwdHeaders[k] = v;
236
+ }
237
+ const pinned = (upstreamIps ?? []).filter((ip) => net.isIP(ip));
238
+ const mod = secure ? https : http;
239
+ const up = mod.request({
240
+ host: u.hostname,
241
+ port: u.port ? parseInt(u.port, 10) : (secure ? 443 : 80),
242
+ // Pinned dial: answer from the checked IPs, never DNS again. Node asks
243
+ // with `{ all: true }` and attempts every address (Happy Eyeballs: a
244
+ // refused address falls through to the next, each attempt short-timed);
245
+ // otherwise the first pinned address answers alone. A custom socket
246
+ // cannot serve here: the TLS stack will not handshake over one.
247
+ ...(pinned.length ? { lookup: (h, o, cb) => {
248
+ const done = /** @type {(err: unknown, ...rest: unknown[]) => void} */ (typeof o === 'function' ? o : cb);
249
+ /** @param {string} ip */
250
+ const fam = (ip) => net.isIP(ip);
251
+ try {
252
+ const opts = typeof o === 'function' ? {} : (o ?? {});
253
+ if (opts && /** @type {{ all?: boolean }} */ (opts).all) {
254
+ done(null, pinned.map((address) => ({ address, family: fam(address) })));
255
+ } else {
256
+ const first = /** @type {string} */ (pinned[0]);
257
+ done(null, first, fam(first));
258
+ }
259
+ } catch (e) {
260
+ done(e);
261
+ }
262
+ } } : {}),
263
+ ...(secure && !IP_RE.test(u.hostname) ? { servername: u.hostname } : {}),
264
+ ...(secure && trust ? { ca: trust } : {}),
265
+ method, path: u.pathname + u.search, headers: fwdHeaders,
266
+ });
267
+ upstreams.add(up);
268
+ let done = false;
269
+ const fail = (note) => {
270
+ if (done) return;
271
+ done = true;
272
+ upstreams.delete(up);
273
+ denyRes(cres, 502, note);
274
+ };
275
+ up.setTimeout(upstreamTimeoutMs, () => { up.destroy(new Error(`upstream timeout after ${upstreamTimeoutMs}ms`)); });
276
+ up.on('response', (ures) => {
277
+ /** @type {Record<string, string | string[] | undefined>} */
278
+ const respHeaders = {};
279
+ for (const [k, v] of Object.entries(ures.headers)) {
280
+ if (!HOP_RESP.has(k.toLowerCase()) && v !== undefined) respHeaders[k] = v;
281
+ }
282
+ if (ures.statusCode === undefined) { fail('upstream sent no status'); up.destroy(); return; }
283
+ log({ ev: 'resp', agent, url, status: ures.statusCode });
284
+ try {
285
+ cres.writeHead(ures.statusCode, respHeaders);
286
+ } catch (e) { fail(`cannot frame upstream response: ${e.message}`); up.destroy(); return; }
287
+ ures.on('end', () => {
288
+ if (done) return;
289
+ done = true;
290
+ upstreams.delete(up);
291
+ });
292
+ ures.on('error', (e) => fail(`upstream body failed: ${e.message}`));
293
+ ures.pipe(cres);
294
+ });
295
+ up.on('error', (e) => fail(`upstream ${u.hostname} failed: ${e.message}`));
296
+ // Client went away mid-flight: stop paying for the upstream.
297
+ cres.on('close', () => {
298
+ if (!done && !cres.writableEnded) { done = true; upstreams.delete(up); up.destroy(); }
299
+ });
300
+ if (body) up.end(body);
301
+ else if (stream) stream.pipe(up);
302
+ else up.end();
303
+ }
304
+
305
+ // The rest of setup is infallible synchronously except this call, so a
306
+ // throw here releases the claim before it propagates (like upstreamCa
307
+ // above); async failures release through `ready` and `close()` below.
308
+ let holds = null;
309
+ try {
310
+ holds = hold ? createHolds({
311
+ log,
312
+ shouldHold: hold.shouldHold,
313
+ match: hold.match,
314
+ timeoutMs: hold.timeoutMs,
315
+ maxBody: holdMaxBody,
316
+ runtime,
317
+ onAsk: hold.onAsk,
318
+ pollMs: hold.pollMs,
319
+ onEvent: hold.onEvent,
320
+ onApprove: (h) => forward({ agent: h.agent, method: h.method, url: h.url,
321
+ headers: h.headers, body: h.body, cres: h.cres }),
322
+ onDeny: (h, reason) => denyRes(h.cres, 403, `denied: ${reason}`),
323
+ }) : null;
324
+ } catch (e) {
325
+ releaseClaim();
326
+ throw e;
327
+ }
328
+
329
+ const server = http.createServer((creq, cres) => {
330
+ // Async only for the wall's DNS lookup; no body listener is attached
331
+ // before the check, so nothing is lost while it resolves.
332
+ handleRequest(creq, cres).catch((e) => denyRes(cres, 500, `proxy failed: ${e.message}`));
333
+ });
334
+
335
+ async function handleRequest(creq, cres) {
336
+ const sock = creq.socket;
337
+ const agent = agentOf(sock);
338
+ const secure = sock[SECURE] === true;
339
+ const target = creq.url || '';
340
+ let url;
341
+ try {
342
+ if (/^https?:\/\//i.test(target)) url = new URL(target);
343
+ else {
344
+ const host = creq.headers.host;
345
+ if (!host) throw new Error('no host');
346
+ url = new URL(`${secure ? 'https' : 'http'}://${host}${target}`);
347
+ }
348
+ } catch { denyRes(cres, 400, 'bad request target'); return; }
349
+ const method = creq.method;
350
+ if (!method) { denyRes(cres, 400, 'bad request method'); return; }
351
+ const urlStr = url.toString();
352
+ const verdict = await checkUpstream(url.hostname, gate);
353
+ if (!verdict.ok) {
354
+ try { creq.resume(); } catch {}
355
+ denyRes(cres, 403, verdict.reason);
356
+ return;
357
+ }
358
+ const queue = holds;
359
+ const reason = queue ? queue.decide({ agent, method, url: urlStr, headers: creq.headers }) : null;
360
+
361
+ // Tee the body for the log (capped). A held request buffers it whole —
362
+ // bounded by maxBody — so approve can forward it after the human decides.
363
+ // Anything else streams straight through; the tee only feeds the log.
364
+ const chunks = [];
365
+ let size = 0;
366
+ let over = false;
367
+ const finishLog = () => {
368
+ const body = Buffer.concat(chunks);
369
+ log({ ev: 'req', agent, method: creq.method, url: urlStr,
370
+ headers: creq.headers, body: body.toString('utf8'),
371
+ ...(over ? { truncated: true, bodyBytes: size } : {}) });
372
+ return body;
373
+ };
374
+ if (!reason || !queue) {
375
+ // Pause before any body listener: the tee below would otherwise put
376
+ // the stream in flowing mode, and forward() awaits a second wall
377
+ // check before forwardInner pipes to upstream — body bytes arriving
378
+ // during that wait would go to the tee only, starving upstream
379
+ // against Content-Length. Buffered here, pipe() resumes the flow,
380
+ // so both the tee and upstream see the whole body.
381
+ creq.pause();
382
+ creq.on('data', (c) => {
383
+ size += c.length;
384
+ if (size > maxLogBody || over) { over = true; return; }
385
+ chunks.push(c);
386
+ });
387
+ creq.on('end', finishLog);
388
+ creq.on('error', () => {});
389
+ forward({ agent, method, url: urlStr,
390
+ headers: { ...creq.headers }, stream: creq, cres });
391
+ return;
392
+ }
393
+ creq.on('data', (c) => {
394
+ size += c.length;
395
+ if (size > holdMaxBody) { over = true; return; }
396
+ chunks.push(c);
397
+ });
398
+ creq.on('error', () => denyRes(cres, 502, 'client body failed'));
399
+ creq.on('end', () => {
400
+ if (over) { denyRes(cres, 403, 'body too large to hold'); return; }
401
+ const body = finishLog();
402
+ // Parked: the tunnel stays open until the ask channel decides. The
403
+ // hold reason travels as `note` so the ask file carries its `rule`.
404
+ queue.add({ agent, method, url: urlStr,
405
+ headers: { ...creq.headers }, body, sock, cres, note: reason });
406
+ });
407
+ }
408
+ // Idle tunnels die here; a request in flight is never idle by definition.
409
+ server.keepAliveTimeout = clientIdleMs;
410
+ server.on('clientError', (err, sock) => {
411
+ try { sock.destroy(); } catch {}
412
+ });
413
+
414
+ // Dispatch: one CONNECT line, or plain HTTP straight into the same server.
415
+ function admit(sock, agent) {
416
+ sock[AGENT] = agent;
417
+ clients.add(sock);
418
+ sock.setTimeout(clientIdleMs, () => sock.destroy());
419
+ sock.on('error', () => {});
420
+ sock.on('close', () => {
421
+ clients.delete(sock);
422
+ holds?.abandonSocket(sock);
423
+ });
424
+ let buf = Buffer.alloc(0);
425
+ const onData = (ch) => {
426
+ buf = Buffer.concat([buf, ch]);
427
+ const i = buf.indexOf('\r\n\r\n');
428
+ if (i < 0) {
429
+ if (buf.length > 65536) {
430
+ sock.removeListener('data', onData);
431
+ denyRaw(sock, 400, 'head too large');
432
+ }
433
+ return;
434
+ }
435
+ const line = buf.subarray(0, buf.indexOf('\r\n')).toString('latin1');
436
+ const [method, target] = line.split(' ');
437
+ sock.removeListener('data', onData);
438
+ sock.setTimeout(0); // the http.Server owns idle from here
439
+ if (method === 'CONNECT') {
440
+ handleConnect(sock, target, buf.subarray(i + 4), agent);
441
+ } else {
442
+ // Plain HTTP (absolute- or origin-form): same parser, same handler.
443
+ // Push the bytes back so the http.Server sees the whole stream.
444
+ sock.unshift(buf);
445
+ server.emit('connection', sock);
446
+ }
447
+ buf = Buffer.alloc(0);
448
+ };
449
+ sock.on('data', onData);
450
+ }
451
+
452
+ async function handleConnect(sock, target, rest, agent) {
453
+ const [host, portStr] = String(target || '').split(':');
454
+ const portNum = portStr ? parseInt(portStr, 10) : 443;
455
+ if (!HOST_RE.test(host || '') || !Number.isFinite(portNum) || portNum < 1 || portNum > 65535) {
456
+ denyRaw(sock, 400, 'bad connect line');
457
+ return;
458
+ }
459
+ // Deny the tunnel itself: no cert is minted for a walled destination,
460
+ // and the inner request is checked again on arrival anyway.
461
+ const verdict = await checkUpstream(host, gate);
462
+ if (!verdict.ok) {
463
+ denyRaw(sock, 403, verdict.reason);
464
+ return;
465
+ }
466
+ let creds;
467
+ try {
468
+ creds = await certFor(certDir, host);
469
+ } catch (e) {
470
+ denyRaw(sock, 502, `no cert for ${host}: ${e.message}`);
471
+ return;
472
+ }
473
+ if (closed || sock.destroyed) return;
474
+ try { sock.write('HTTP/1.1 200 Connection established\r\n\r\n'); }
475
+ catch { return; }
476
+ if (rest.length) sock.unshift(rest);
477
+ const st = new tls.TLSSocket(sock, { isServer: true, key: creds.key, cert: creds.cert });
478
+ st[AGENT] = agent;
479
+ st[SECURE] = true;
480
+ clients.add(st);
481
+ st.on('error', () => {});
482
+ st.on('close', () => {
483
+ clients.delete(st);
484
+ holds?.abandonSocket(st);
485
+ });
486
+ server.emit('connection', st);
487
+ }
488
+
489
+ // --- listeners -----------------------------------------------------------
490
+ const ready = (async () => {
491
+ await ensureCA(certDir);
492
+ /** @type {number|null} */
493
+ let bound = null;
494
+ if (port !== null && port !== undefined) {
495
+ /** @type {Promise<number|null>} */
496
+ const boundP = new Promise((resolve, reject) => {
497
+ tcp = net.createServer((sock) => {
498
+ if (closed) { sock.destroy(); return; }
499
+ admit(sock, 'tcp');
500
+ });
501
+ tcp.on('error', reject);
502
+ tcp.listen(port, '127.0.0.1', () => {
503
+ const a = tcp?.address();
504
+ resolve(typeof a === 'object' && a !== null ? a.port : 0);
505
+ });
506
+ });
507
+ bound = await boundP;
508
+ }
509
+ return { port: bound };
510
+ })();
511
+ // A rejected `ready` must never become an uncaught process crash, and it
512
+ // releases the claim before the rejection reaches the caller (attached
513
+ // first, so this runs before any caller reaction).
514
+ ready.catch(() => { releaseClaim(); });
515
+
516
+ function addAgent(name) {
517
+ const sockPath = runtimePaths(runtime).socket(name);
518
+ if (agentServers.has(name)) return sockPath;
519
+ try { fs.unlinkSync(sockPath); } catch {}
520
+ fs.mkdirSync(path.dirname(sockPath), { recursive: true });
521
+ const srv = net.createServer((sock) => {
522
+ if (closed) { sock.destroy(); return; }
523
+ admit(sock, name);
524
+ });
525
+ srv.on('error', (e) => log({ ev: 'deny', agent: name, code: 500, note: `agent listener failed: ${e.message}` }));
526
+ srv.listen(sockPath, () => {
527
+ try { fs.chmodSync(sockPath, 0o600); } catch {}
528
+ });
529
+ agentServers.set(name, srv);
530
+ return sockPath;
531
+ }
532
+
533
+ function removeAgent(name) {
534
+ const srv = agentServers.get(name);
535
+ if (!srv) return;
536
+ agentServers.delete(name);
537
+ srv.close();
538
+ try { fs.unlinkSync(runtimePaths(runtime).socket(name)); } catch {}
539
+ }
540
+
541
+ async function close() {
542
+ closed = true;
543
+ tcp?.close();
544
+ for (const [, srv] of agentServers) srv.close();
545
+ agentServers.clear();
546
+ // Parked holds settle as denied (guarded writes), timers cleared,
547
+ // ask files removed, sweeper stopped — all inside holds.close().
548
+ holds?.close();
549
+ for (const up of upstreams) { try { up.destroy(); } catch {} }
550
+ upstreams.clear();
551
+ for (const s of clients) { try { s.destroy(); } catch {} }
552
+ clients.clear();
553
+ server.close();
554
+ logStream.end();
555
+ /** @type {Promise<void>} */
556
+ const flushed = new Promise((resolve) => {
557
+ if (logStream.writableFinished) resolve();
558
+ else logStream.once('finish', () => resolve());
559
+ });
560
+ await flushed;
561
+ releaseClaim();
562
+ }
563
+
564
+ return {
565
+ ready,
566
+ close,
567
+ addAgent,
568
+ removeAgent,
569
+ pending: () => (holds ? holds.pending() : []),
570
+ get caFile() { return path.join(certDir, 'ca.pem'); },
571
+ };
572
+ }