barebox 0.2.0 → 0.4.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 CHANGED
@@ -13,19 +13,15 @@ import tls from 'node:tls';
13
13
  import http from 'node:http';
14
14
  import https from 'node:https';
15
15
  import fs from 'node:fs';
16
- import os from 'node:os';
17
16
  import path from 'node:path';
18
- import { lookup as dnsLookup } from 'node:dns/promises';
19
- import { ensureCA, certFor } from './certs.js';
17
+ import { ensureCA, certFor, HOST_RE } from './certs.js';
20
18
  import { createHolds } from './holds.js';
19
+ import { claimRuntime, ensurePrivateDir, runtimePaths } from './runtime.js';
20
+ import { checkUpstream } from './wall.js';
21
21
 
22
22
  const AGENT = Symbol('agent');
23
23
  const SECURE = Symbol('secure');
24
24
  const IP_RE = /^\d+\.\d+\.\d+\.\d+$/;
25
- const HOST_RE = /^[A-Za-z0-9.-]+$/;
26
- const AGENT_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
27
- // Linux sun_path: 108 bytes including the NUL.
28
- const MAX_SOCK_PATH = 107;
29
25
  // Hop-by-hop headers must not be forwarded: node's HTTP stack re-frames.
30
26
  const HOP_REQ = new Set(['proxy-connection', 'proxy-authorization']);
31
27
  const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
@@ -36,7 +32,9 @@ const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
36
32
  // user's `redact` hook runs after this scrubbing, so it sees (and further
37
33
  // shapes) an already-safe entry. Bodies stay logged as-is.
38
34
  const REDACTED = '[redacted]';
39
- const SENSITIVE_HEADERS = new Set(['authorization', 'proxy-authorization']);
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']);
40
38
 
41
39
  /**
42
40
  * Copy a log entry with sensitive header values replaced by `[redacted]`.
@@ -57,222 +55,22 @@ function scrubSecrets(entry) {
57
55
  return { ...entry, headers };
58
56
  }
59
57
 
60
- // --- upstream wall ---------------------------------------------------------
61
- // Default-deny for loopback, link-local (incl. cloud metadata 169.254/16),
62
- // the host's own addresses, and private LAN ranges (RFC 1918, CGNAT
63
- // 100.64/10, IPv6 ULA fc00::/7). The check runs AFTER DNS resolution, so a
64
- // hostname that resolves to 127.0.0.1 is denied exactly like the literal.
65
- // Unresolvable names are denied too (fail closed, never 502-then-dial).
66
- // Only `allowLoopback` (loopback + unspecified) or `allowUpstream(host, ip)`
67
- // lets a denied destination through; only tests pass those. There is no
68
- // allowPrivate flag: a private destination passes only via `allowUpstream`.
69
-
70
- /** Strip brackets/scope, lowercase: one spelling per address. */
71
- function normIp(ip) {
72
- let s = String(ip || '').toLowerCase();
73
- if (s.startsWith('[') && s.endsWith(']')) s = s.slice(1, -1);
74
- const pct = s.indexOf('%');
75
- if (pct >= 0) s = s.slice(0, pct);
76
- return s;
77
- }
78
-
79
- /** Embedded IPv4 in `::ffff:1.2.3.4`, or null. */
80
- function mappedV4(ip) {
81
- const m = ip.match(/^(?:.*:)?(\d+\.\d+\.\d+\.\d+)$/);
82
- return m && net.isIP(m[1]) === 4 ? m[1] : null;
83
- }
84
-
85
- function v4Parts(ip) {
86
- return ip.split('.').map((p) => parseInt(p, 10));
87
- }
88
-
89
- /** This machine's own interface addresses, one spelling (see `normIp`). */
90
- function localIps() {
91
- const out = new Set();
92
- let ifs = {};
93
- // networkInterfaces() can throw where interfaces are hidden (a sandbox is
94
- // exactly where the wall matters most): lose host-local, keep the rest.
95
- try {
96
- ifs = os.networkInterfaces();
97
- } catch {
98
- return out;
99
- }
100
- for (const addrs of Object.values(ifs)) {
101
- for (const a of addrs ?? []) {
102
- if (a && a.address) out.add(normIp(a.address));
103
- }
104
- }
105
- return out;
106
- }
107
-
108
- /**
109
- * Why `ip` (already resolved) is denied, or null when it may go through.
110
- *
111
- * @param {string} rawIp resolved destination IP
112
- * @param {boolean} allowLoopback test-only opt-in for loopback + unspecified
113
- * @returns {string|null} `loopback` / `unspecified` / `link-local` / `host-local` / `private`, or null
114
- */
115
- export function denyReasonForIp(rawIp, allowLoopback) {
116
- const ip = normIp(rawIp);
117
- const v4 = mappedV4(ip) ?? (net.isIP(ip) === 4 ? ip : null);
118
- if (v4) {
119
- const [a, b] = v4Parts(v4);
120
- if (a === 127) return allowLoopback ? null : 'loopback';
121
- if (a === 0) return allowLoopback ? null : 'unspecified';
122
- if (a === 169 && b === 254) return 'link-local';
123
- if (a === 10) return 'private';
124
- if (a === 172 && b >= 16 && b <= 31) return 'private';
125
- if (a === 192 && b === 168) return 'private';
126
- if (a === 100 && b >= 64 && b <= 127) return 'private';
127
- if (localIps().has(v4)) return 'host-local';
128
- return null;
129
- }
130
- if (net.isIP(ip) === 6) {
131
- if (ip === '::1') return allowLoopback ? null : 'loopback';
132
- if (ip === '::') return allowLoopback ? null : 'unspecified';
133
- const first = parseInt(ip.split(':')[0] || '0', 16);
134
- if (first >= 0xfe80 && first <= 0xfebf) return 'link-local';
135
- if (first >= 0xfc00 && first <= 0xfdff) return 'private';
136
- if (localIps().has(ip)) return 'host-local';
137
- return null;
138
- }
139
- return null;
140
- }
141
-
142
- /**
143
- * Resolve `host` to every IP for the wall. Literals need no DNS.
144
- * Fail closed: anything that does not resolve is denied, never dialed.
145
- *
146
- * @param {string} host CONNECT/request hostname
147
- * @param {(host: string) => Promise<string[] | string | null>} [stub] test-only DNS stub
148
- * @returns {Promise<string[] | null>} all resolved IPs, or null when unresolvable
149
- */
150
- async function resolveAllUpstream(host, stub) {
151
- if (net.isIP(host)) return [host];
152
- try {
153
- if (typeof stub === 'function') {
154
- const r = await stub(host);
155
- if (!r) return null;
156
- if (Array.isArray(r)) return r.length ? [...r] : null;
157
- if (typeof r === 'string') return [r];
158
- return null;
159
- }
160
- const all = await dnsLookup(host, { all: true });
161
- if (!all || !all.length) return null;
162
- return all.map((a) => a.address);
163
- } catch {
164
- return null;
165
- }
166
- }
167
-
168
- /**
169
- * The wall: resolve every answer, then default-deny loopback/link-local/
170
- * host-local/private unless the test-only opt-ins allow it. Denies when ANY
171
- * answer is walled, denies unresolvable names, and pins the first checked IP
172
- * so the dial below cannot resolve the name a second time (no rebinding).
173
- *
174
- * @param {string} host CONNECT/request hostname
175
- * @param {{ allowLoopback: boolean, allowUpstream: ((host: string, ip: string) => boolean) | null, resolveUpstream?: (host: string) => Promise<string[] | string | null> }} gate
176
- * @returns {Promise<{ ok: true, ip: string } | { ok: false, ip: string, reason: string }>}
177
- */
178
- async function checkUpstream(host, gate) {
179
- const ips = await resolveAllUpstream(host, gate.resolveUpstream);
180
- if (!ips || !ips.length) {
181
- return { ok: false, ip: host, reason: `unresolvable upstream denied: ${host}` };
182
- }
183
- for (const ip of ips) {
184
- if (typeof gate.allowUpstream === 'function') {
185
- let pass = false;
186
- try { pass = gate.allowUpstream(host, ip) === true; } catch { pass = false; }
187
- if (pass) continue;
188
- }
189
- const kind = denyReasonForIp(ip, gate.allowLoopback);
190
- if (kind) {
191
- const where = ip === host ? host : `${host} (${ip})`;
192
- return { ok: false, ip, reason: `${kind} upstream denied: ${where}` };
193
- }
194
- }
195
- return { ok: true, ip: ips[0] };
196
- }
197
-
198
- /**
199
- * Check an agent name before it reaches the filesystem.
200
- *
201
- * @param {string} name agent name
202
- * @returns {void} throws on `../` and friends
203
- */
204
- export function assertAgentName(name) {
205
- if (!AGENT_RE.test(name || '')) {
206
- throw new Error(`bad agent name ${JSON.stringify(name)}: must match ${AGENT_RE}`);
207
- }
208
- }
209
-
210
- /**
211
- * Resolve symlinks through the nearest existing ancestor: socket paths may
212
- * not exist yet, so `realpathSync` on the full path would throw. Walks up
213
- * to the first existing ancestor, resolves that, then re-attaches the rest.
214
- *
215
- * @param {string} p any path, existing or not
216
- * @returns {string} the real (symlink-free) spelling of `p`
217
- */
218
- export function realPathOf(p) {
219
- const abs = path.resolve(p);
220
- let cur = abs;
221
- /** @type {string[]} */
222
- const rest = [];
223
- while (!fs.existsSync(cur)) {
224
- const parent = path.dirname(cur);
225
- if (parent === cur) break;
226
- rest.unshift(path.basename(cur));
227
- cur = parent;
228
- }
229
- const real = fs.realpathSync(cur);
230
- return rest.length ? path.join(real, ...rest) : real;
231
- }
232
-
233
- /**
234
- * The one path both sides agree on: the proxy listens here, the launcher
235
- * binds it into the sandbox. This function is the single writer of the shape.
236
- *
237
- * @param {string} runtime runtime dir
238
- * @param {string} name agent name
239
- * @returns {string} `<runtime>/socks/<name>.sock`
240
- */
241
- export function socketPathForAgent(runtime, name) {
242
- assertAgentName(name);
243
- const p = path.join(runtime, 'socks', `${name}.sock`);
244
- if (p.length > MAX_SOCK_PATH) {
245
- throw new Error(`agent socket path too long (${p.length} > ${MAX_SOCK_PATH}): ${p}`);
246
- }
247
- return p;
248
- }
249
-
250
58
  /**
251
59
  * Options for {@link createProxy}.
252
60
  *
253
61
  * @typedef {object} ProxyOptions
254
62
  * @property {string} logFile JSON-lines log path (`req`, `resp`, `deny`, `hold`, `decide`, `hold-abandoned`)
255
- * @property {string} [certDir] dir for the CA + minted host certs (default `<runtime>/certs`).
256
- * Must live inside `runtime` (compared via {@link realPathOf}, so symlinks
257
- * cannot smuggle it out): anything else throws before any side effect.
258
- * The CA private key lives here, and the sandbox bind-mounts only the
259
- * runtime dir — an outside certDir would expose `ca.key` through the binds.
260
- * @property {string} [runtime] runtime dir; required for `addAgent`, default parent of `certDir`
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.
261
64
  * @property {number} [port] opt-in TCP listener for tests, bound to 127.0.0.1 only (default: none)
262
65
  * @property {string} [upstreamCa] extra PEM the proxy trusts for upstream TLS, on top of system roots
263
66
  * @property {HoldOptions} [hold] hold queue config, or omit to forward everything
264
- * @property {string|null} [controlSocket] unix socket path for `pending | approve | deny`.
265
- * Must live inside `runtime` (compared via {@link realPathOf}, so symlinks
266
- * cannot smuggle it out): anything else throws before any side effect.
267
- * No default — omit it when no CLI decisions are needed.
268
67
  * @property {number} [upstreamTimeoutMs] give up on an upstream response after this (default 120000)
269
- * @property {boolean} [allowLoopback] TEST-ONLY opt-in: let loopback and unspecified
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
270
71
  * destinations through (default false). Fixture servers listen on 127.0.0.1,
271
72
  * so tests pass this; production never should.
272
- * @property {(host: string, ip: string) => boolean} [allowUpstream] escape hatch,
273
- * consulted after DNS with each resolved IP: return true to let through a
274
- * destination the default wall would deny. Only tests use this.
275
- * @property {(host: string) => Promise<string[] | string | null>} [resolveUpstream] TEST-ONLY
73
+ * @property {(host: string) => Promise<string[] | string | null>} [unsafeTestOnly.resolveUpstream]
276
74
  * DNS stub: replaces the wall's resolver so rebinding is testable. Production omits it.
277
75
  * @property {number} [clientIdleMs] kill a client tunnel idle this long; never fires mid-request (default 60000)
278
76
  * @property {number} [maxLogBody] log at most this many request-body bytes, then `truncated: true` (default 1048576)
@@ -287,6 +85,11 @@ export function socketPathForAgent(runtime, name) {
287
85
  * @property {import('./holds.js').ShouldHold} [shouldHold] decision function; overrides `match`
288
86
  * @property {number|string} [timeoutMs] hold deadline in ms, or `'never'` (default 120000)
289
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
290
93
  */
291
94
 
292
95
  /**
@@ -316,63 +119,68 @@ export function socketPathForAgent(runtime, name) {
316
119
  * @param {ProxyOptions} opts
317
120
  * @returns live proxy: `ready` resolves when listeners + CA are up; the shape is inferred, see `Proxy`
318
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.
319
- * @fails Throws synchronously on a missing `logFile` (or neither `certDir` nor `runtime`). 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.
122
+ * @fails Throws synchronously on a missing or unopenable `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.
320
123
  * @example
321
124
  * import { createProxy } from "barebox";
322
- * const proxy = createProxy({ port: 0, certDir: "./certs", logFile: "./mitm.log" });
125
+ * const proxy = createProxy({ port: 0, runtime: "./sbx-runtime", logFile: "./mitm.log" });
323
126
  * const { port } = await proxy.ready;
324
127
  * await proxy.close();
325
128
  */
326
129
  export function createProxy(opts) {
327
- const { logFile, certDir: certDirOpt, runtime: runtimeOpt, port = null,
328
- upstreamCa = null, hold = null, controlSocket = null,
130
+ const { logFile, runtime, port = null,
131
+ upstreamCa = null, hold = null,
329
132
  upstreamTimeoutMs = 120000, clientIdleMs = 60000,
330
- allowLoopback = false, allowUpstream = null, resolveUpstream = null,
133
+ unsafeTestOnly = null,
331
134
  maxLogBody = 1048576, redact = (e) => e } = opts ?? {};
332
- const gate = { allowLoopback, allowUpstream, resolveUpstream: resolveUpstream ?? undefined };
135
+ const { allowLoopback = false, resolveUpstream = null } = unsafeTestOnly ?? {};
136
+ const gate = { allowLoopback, resolveUpstream: resolveUpstream ?? undefined };
333
137
  if (!logFile) throw new Error('createProxy: logFile is required');
334
- const runtime = runtimeOpt ?? (certDirOpt ? path.dirname(path.resolve(certDirOpt)) : null);
335
- const dirOpt = certDirOpt ?? (runtime ? path.join(runtime, 'certs') : null);
336
- if (!dirOpt) throw new Error('createProxy: certDir or runtime is required');
337
- // The control socket is the approve-payments capability: it must live
338
- // inside the runtime dir (the launcher masks exactly that dir), compared
339
- // on real paths so a symlink cannot smuggle it out. Fail closed here,
340
- // before the log stream, CA read, or any listener exists.
341
- if (controlSocket) {
342
- if (!runtime) {
343
- throw new Error(`createProxy: controlSocket must live inside the runtime, got ${controlSocket} with no runtime`);
344
- }
345
- const realRt = realPathOf(runtime);
346
- const realCtl = realPathOf(controlSocket);
347
- if (!realCtl.startsWith(realRt + path.sep)) {
348
- throw new Error(`createProxy: controlSocket must live inside the runtime: ${realCtl} not under ${realRt}`);
349
- }
350
- }
351
- // The CA private key lives in certDir, and the launcher masks exactly
352
- // the runtime dir: a certDir outside it would expose ca.key through the
353
- // read-only binds. Same containment rule as the control socket above —
354
- // fail closed here, before the log stream, CA read, or any listener.
355
- // The default `<runtime>/certs` passes trivially.
356
- if (!runtime) {
357
- throw new Error(`createProxy: certDir must live inside the runtime, got ${dirOpt} with no runtime`);
358
- }
359
- {
360
- const realRt = realPathOf(runtime);
361
- const realCerts = realPathOf(dirOpt);
362
- if (!realCerts.startsWith(realRt + path.sep)) {
363
- throw new Error(`createProxy: certDir must live inside the runtime: ${realCerts} not under ${realRt}`);
364
- }
365
- }
366
- const certDir = dirOpt;
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;
367
146
  const holdMaxBody = hold?.maxBody ?? 1048576;
368
147
 
369
- const logStream = fs.createWriteStream(logFile, { flags: 'a', mode: 0o600 });
370
- const log = (o) => { logStream.write(JSON.stringify(redact(scrubSecrets(o))) + '\n'); };
148
+ // Open the audit log synchronously: a bad `logFile` (a directory, a
149
+ // missing parent, no permission) throws here, where the claim can still
150
+ // be released — not later as an uncaught stream error.
151
+ let logFd;
152
+ try {
153
+ logFd = fs.openSync(logFile, 'a', 0o600);
154
+ } catch (e) {
155
+ const msg = e instanceof Error ? e.message : String(e);
156
+ releaseClaim();
157
+ throw new Error(`createProxy: cannot open logFile ${logFile}: ${msg}`);
158
+ }
159
+ const logStream = fs.createWriteStream(logFile, { fd: logFd });
160
+ // `openSync`'s mode is masked by the umask and doesn't apply to an
161
+ // existing file: a 0644 log from an older run would stay world-readable
162
+ // while new lines append, so fix it up on every start.
163
+ try { fs.chmodSync(logFile, 0o600); } catch {}
164
+ let logFailed = false;
165
+ logStream.on('error', (e) => {
166
+ if (logFailed) return;
167
+ logFailed = true;
168
+ console.error(`sbx: audit log ${logFile} write failed: ${e instanceof Error ? e.message : String(e)}`);
169
+ });
170
+ // After close() ends the stream a late line (a socket torn down by close)
171
+ // is dropped on purpose: a write after end() would destroy the stream.
172
+ const log = (o) => {
173
+ if (logStream.writableEnded) return;
174
+ logStream.write(JSON.stringify(redact(scrubSecrets(o))) + '\n');
175
+ };
371
176
  let trust = null;
372
177
  if (upstreamCa) {
373
178
  let extra;
374
179
  try { extra = fs.readFileSync(upstreamCa, 'utf8'); }
375
- catch (e) { throw new Error(`createProxy: cannot read upstreamCa: ${e.message}`); }
180
+ catch (e) {
181
+ releaseClaim();
182
+ throw new Error(`createProxy: cannot read upstreamCa: ${e.message}`);
183
+ }
376
184
  trust = [...tls.rootCertificates, extra];
377
185
  }
378
186
 
@@ -387,6 +195,7 @@ export function createProxy(opts) {
387
195
 
388
196
  const agentOf = (sock) => sock[AGENT] ?? 'tcp';
389
197
 
198
+ // The one writer of a proxied HTTP error: logs it, answers it.
390
199
  function denyRes(cres, code, note) {
391
200
  const sock = cres.socket;
392
201
  log({ ev: 'deny', agent: agentOf(sock), code, note });
@@ -398,6 +207,7 @@ export function createProxy(opts) {
398
207
  } catch {}
399
208
  }
400
209
 
210
+ // Pre-HTTP raw sockets only (CONNECT line, oversized head, walled CONNECT, cert failure).
401
211
  function denyRaw(sock, code, note) {
402
212
  log({ ev: 'deny', agent: agentOf(sock), code, note });
403
213
  if (sock.destroyed) return;
@@ -425,20 +235,19 @@ export function createProxy(opts) {
425
235
  }
426
236
  // Sync from here: forwardInner answers every failure itself, but a
427
237
  // throw before it can answer must still be loud, never a floating reject.
428
- // The dial is pinned to the checked IP: no second DNS resolution.
238
+ // The dial is pinned to the checked IPs: no second DNS resolution.
429
239
  try {
430
- forwardInner({ agent, method, url, headers, body, stream, cres, u, upstreamIp: verdict.ip });
240
+ forwardInner({ agent, method, url, headers, body, stream, cres, u, upstreamIps: verdict.ips });
431
241
  } catch (e) {
432
242
  // The live stream arrives paused (see handleRequest): unpause so no
433
243
  // paused stream leaks on this path.
434
244
  try { stream?.resume(); } catch {}
435
- log({ ev: 'deny', agent, code: 502, note: `upstream failed: ${e.message}` });
436
245
  denyRes(cres, 502, `upstream failed: ${e.message}`);
437
246
  }
438
247
  }
439
248
 
440
- /** @param {ForwardArgs & { u: URL, upstreamIp?: string }} args */
441
- function forwardInner({ agent, method, url, headers, body, stream, cres, u, upstreamIp }) {
249
+ /** @param {ForwardArgs & { u: URL, upstreamIps: string[] }} args */
250
+ function forwardInner({ agent, method, url, headers, body, stream, cres, u, upstreamIps }) {
442
251
  const sock = cres.socket;
443
252
  if (!sock) return; // no transport left to answer on
444
253
  const secure = u.protocol === 'https:';
@@ -447,21 +256,31 @@ export function createProxy(opts) {
447
256
  for (const [k, v] of Object.entries(headers)) {
448
257
  if (!HOP_REQ.has(k.toLowerCase())) fwdHeaders[k] = v;
449
258
  }
450
- const pinned = upstreamIp && net.isIP(upstreamIp) ? upstreamIp : null;
259
+ const pinned = (upstreamIps ?? []).filter((ip) => net.isIP(ip));
451
260
  const mod = secure ? https : http;
452
261
  const up = mod.request({
453
262
  host: u.hostname,
454
263
  port: u.port ? parseInt(u.port, 10) : (secure ? 443 : 80),
455
- // Pinned dial: answer from the checked IP, never DNS again. Node asks
456
- // with `{ all: true }`, which wants an array back (not the triple).
457
- ...(pinned ? { lookup: (h, o, cb) => {
458
- const fn = typeof o === 'function' ? o : cb;
459
- const opts = typeof o === 'function' ? {} : (o ?? {});
460
- const fam = net.isIP(pinned);
264
+ // Pinned dial: answer from the checked IPs, never DNS again. Node asks
265
+ // with `{ all: true }` and attempts every address (Happy Eyeballs: a
266
+ // refused address falls through to the next, each attempt short-timed);
267
+ // otherwise the first pinned address answers alone. A custom socket
268
+ // cannot serve here: the TLS stack will not handshake over one.
269
+ ...(pinned.length ? { lookup: (h, o, cb) => {
270
+ const done = /** @type {(err: unknown, ...rest: unknown[]) => void} */ (typeof o === 'function' ? o : cb);
271
+ /** @param {string} ip */
272
+ const fam = (ip) => net.isIP(ip);
461
273
  try {
462
- if (opts && opts.all) fn(null, [{ address: pinned, family: fam }]);
463
- else fn(null, pinned, fam);
464
- } catch (e) { try { /** @type {(err: unknown) => void} */ (fn)(e); } catch {} }
274
+ const opts = typeof o === 'function' ? {} : (o ?? {});
275
+ if (opts && /** @type {{ all?: boolean }} */ (opts).all) {
276
+ done(null, pinned.map((address) => ({ address, family: fam(address) })));
277
+ } else {
278
+ const first = /** @type {string} */ (pinned[0]);
279
+ done(null, first, fam(first));
280
+ }
281
+ } catch (e) {
282
+ done(e);
283
+ }
465
284
  } } : {}),
466
285
  ...(secure && !IP_RE.test(u.hostname) ? { servername: u.hostname } : {}),
467
286
  ...(secure && trust ? { ca: trust } : {}),
@@ -473,13 +292,7 @@ export function createProxy(opts) {
473
292
  if (done) return;
474
293
  done = true;
475
294
  upstreams.delete(up);
476
- log({ ev: 'deny', agent, code: 502, note });
477
- try {
478
- if (!cres.headersSent && !sock.destroyed) {
479
- cres.writeHead(502, { 'content-type': 'text/plain', connection: 'close' });
480
- }
481
- if (!sock.destroyed) cres.end(`${note}\n`);
482
- } catch {}
295
+ denyRes(cres, 502, note);
483
296
  };
484
297
  up.setTimeout(upstreamTimeoutMs, () => { up.destroy(new Error(`upstream timeout after ${upstreamTimeoutMs}ms`)); });
485
298
  up.on('response', (ures) => {
@@ -511,17 +324,29 @@ export function createProxy(opts) {
511
324
  else up.end();
512
325
  }
513
326
 
514
- const holds = hold ? createHolds({
515
- log,
516
- shouldHold: hold.shouldHold,
517
- match: hold.match,
518
- timeoutMs: hold.timeoutMs,
519
- maxBody: holdMaxBody,
520
- controlSocket,
521
- onApprove: (h) => forward({ agent: h.agent, method: h.method, url: h.url,
522
- headers: h.headers, body: h.body, cres: h.cres }),
523
- onDeny: (h, reason) => denyRes(h.cres, 403, `denied: ${reason}`),
524
- }) : null;
327
+ // The rest of setup is infallible synchronously except this call, so a
328
+ // throw here releases the claim before it propagates (like upstreamCa
329
+ // above); async failures release through `ready` and `close()` below.
330
+ let holds = null;
331
+ try {
332
+ holds = hold ? createHolds({
333
+ log,
334
+ shouldHold: hold.shouldHold,
335
+ match: hold.match,
336
+ timeoutMs: hold.timeoutMs,
337
+ maxBody: holdMaxBody,
338
+ runtime,
339
+ onAsk: hold.onAsk,
340
+ pollMs: hold.pollMs,
341
+ onEvent: hold.onEvent,
342
+ onApprove: (h) => forward({ agent: h.agent, method: h.method, url: h.url,
343
+ headers: h.headers, body: h.body, cres: h.cres }),
344
+ onDeny: (h, reason) => denyRes(h.cres, 403, `denied: ${reason}`),
345
+ }) : null;
346
+ } catch (e) {
347
+ releaseClaim();
348
+ throw e;
349
+ }
525
350
 
526
351
  const server = http.createServer((creq, cres) => {
527
352
  // Async only for the wall's DNS lookup; no body listener is attached
@@ -587,19 +412,43 @@ export function createProxy(opts) {
587
412
  headers: { ...creq.headers }, stream: creq, cres });
588
413
  return;
589
414
  }
590
- creq.on('data', (c) => {
591
- size += c.length;
592
- if (size > holdMaxBody) { over = true; return; }
593
- chunks.push(c);
594
- });
595
- creq.on('error', () => denyRes(cres, 502, 'client body failed'));
596
- creq.on('end', () => {
597
- if (over) { denyRes(cres, 403, 'body too large to hold'); return; }
598
- const body = finishLog();
599
- // Parked: the tunnel stays open until a human decides.
600
- queue.add({ agent, method, url: urlStr,
601
- headers: { ...creq.headers }, body, sock, cres });
415
+ // One held request per agent reads its body at a time; the rest wait
416
+ // unread in line. No body listener (it would resume the stream) until
417
+ // `onReady`. A request that never parks frees its slot when `cres` closes.
418
+ creq.pause();
419
+ const readHeld = () => {
420
+ creq.on('data', (c) => {
421
+ size += c.length;
422
+ if (size > holdMaxBody) { over = true; return; }
423
+ chunks.push(c);
424
+ });
425
+ creq.on('error', () => { denyRes(cres, 502, 'client body failed'); });
426
+ creq.on('end', () => {
427
+ if (over) { denyRes(cres, 403, 'body too large to hold'); return; }
428
+ const body = finishLog();
429
+ // Parked: the tunnel stays open until the ask channel decides. The
430
+ // hold reason travels as `note` so the ask file carries its `rule`.
431
+ // null: the reservation already expired and onExpire answered 403.
432
+ queue.add({ agent, method, url: urlStr,
433
+ headers: { ...creq.headers }, body, sock, cres, note: reason,
434
+ slot, arrivedAt: slot.arrivedAt });
435
+ });
436
+ creq.resume();
437
+ };
438
+ const slot = queue.reserve(agent, {
439
+ onReady: readHeld,
440
+ onExpire: (why) => { denyRes(cres, 403, `denied: ${why}`); creq.resume(); },
602
441
  });
442
+ if (slot.state === 'full') {
443
+ denyRes(cres, 429, 'hold queue full');
444
+ creq.resume();
445
+ return;
446
+ }
447
+ // The client may have died during the wall's DNS await, before this
448
+ // listener existed: its 'close' is already past, so release here.
449
+ if (sock.destroyed) { slot.cancel(); return; }
450
+ cres.on('close', () => slot.cancel());
451
+ if (slot.state === 'now') readHeld();
603
452
  }
604
453
  // Idle tunnels die here; a request in flight is never idle by definition.
605
454
  server.keepAliveTimeout = clientIdleMs;
@@ -704,15 +553,16 @@ export function createProxy(opts) {
704
553
  }
705
554
  return { port: bound };
706
555
  })();
707
- // A rejected `ready` must never become an uncaught process crash.
708
- ready.catch(() => {});
556
+ // A rejected `ready` must never become an uncaught process crash, and it
557
+ // releases the claim before the rejection reaches the caller (attached
558
+ // first, so this runs before any caller reaction).
559
+ ready.catch(() => { releaseClaim(); });
709
560
 
710
561
  function addAgent(name) {
711
- if (!runtime) throw new Error('createProxy: addAgent needs the runtime option');
712
- const sockPath = socketPathForAgent(runtime, name);
562
+ const sockPath = runtimePaths(runtime).socket(name);
713
563
  if (agentServers.has(name)) return sockPath;
714
564
  try { fs.unlinkSync(sockPath); } catch {}
715
- fs.mkdirSync(path.join(runtime, 'socks'), { recursive: true });
565
+ ensurePrivateDir(path.dirname(sockPath));
716
566
  const srv = net.createServer((sock) => {
717
567
  if (closed) { sock.destroy(); return; }
718
568
  admit(sock, name);
@@ -725,14 +575,20 @@ export function createProxy(opts) {
725
575
  return sockPath;
726
576
  }
727
577
 
578
+ // Ends the agent's door AND its open connections: its parked holds end
579
+ // synchronously as deny / client gone (no waiting on the socket's async
580
+ // 'close'), then each socket is destroyed.
728
581
  function removeAgent(name) {
729
582
  const srv = agentServers.get(name);
730
583
  if (!srv) return;
731
584
  agentServers.delete(name);
732
585
  srv.close();
733
- if (runtime) {
734
- try { fs.unlinkSync(socketPathForAgent(runtime, name)); } catch {}
586
+ for (const s of [...clients]) {
587
+ if (s[AGENT] !== name) continue;
588
+ holds?.abandonSocket(s);
589
+ s.destroy();
735
590
  }
591
+ try { fs.unlinkSync(runtimePaths(runtime).socket(name)); } catch {}
736
592
  }
737
593
 
738
594
  async function close() {
@@ -741,7 +597,7 @@ export function createProxy(opts) {
741
597
  for (const [, srv] of agentServers) srv.close();
742
598
  agentServers.clear();
743
599
  // Parked holds settle as denied (guarded writes), timers cleared,
744
- // control socket closed — all inside holds.close().
600
+ // ask files removed, sweeper stopped — all inside holds.close().
745
601
  holds?.close();
746
602
  for (const up of upstreams) { try { up.destroy(); } catch {} }
747
603
  upstreams.clear();
@@ -751,10 +607,15 @@ export function createProxy(opts) {
751
607
  logStream.end();
752
608
  /** @type {Promise<void>} */
753
609
  const flushed = new Promise((resolve) => {
754
- if (logStream.writableFinished) resolve();
755
- else logStream.once('finish', () => resolve());
610
+ if (logStream.writableFinished || logStream.destroyed) resolve();
611
+ else {
612
+ // A destroyed stream emits 'close', never 'finish'.
613
+ logStream.once('finish', () => resolve());
614
+ logStream.once('close', () => resolve());
615
+ }
756
616
  });
757
617
  await flushed;
618
+ releaseClaim();
758
619
  }
759
620
 
760
621
  return {