barebox 0.4.0 → 0.6.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
@@ -1,13 +1,16 @@
1
1
  // Proxy: the front door. Terminates agent TLS with per-host certificates
2
2
  // minted on demand, sees every request through a private stdlib http.Server
3
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>`.
4
+ // forwards with https/http.request, and asks a gate about every request
5
+ // (bareguard, one gate per agent; see `gateFor`). When the gate asks, the
6
+ // hold queue is its human channel: the request parks for a human decision.
7
+ // Identity = socket: each agent has its own unix listener, and every log
8
+ // line and hold names the agent, never `c<n>`.
7
9
  //
8
10
  // Timeout shape: the client idle clock is the server's keep-alive timeout —
9
11
  // by construction it only ticks when no request is in flight. The upstream
10
12
  // response gets its own much longer clock.
13
+ import crypto from 'node:crypto';
11
14
  import net from 'node:net';
12
15
  import tls from 'node:tls';
13
16
  import http from 'node:http';
@@ -15,55 +18,41 @@ import https from 'node:https';
15
18
  import fs from 'node:fs';
16
19
  import path from 'node:path';
17
20
  import { ensureCA, certFor, HOST_RE } from './certs.js';
18
- import { createHolds } from './holds.js';
21
+ import { createCardScanner } from './cardscan.js';
22
+ import { ASK_BODY_LIMIT, DEFAULT_HOLD_MAX_BODY, bodyPreview, createHolds } from './holds.js';
19
23
  import { claimRuntime, ensurePrivateDir, runtimePaths } from './runtime.js';
24
+ import { paymentPath, toolFor, buildTools, emptyMatcher } from './policy.js';
20
25
  import { checkUpstream } from './wall.js';
26
+ import { findPlaceholders, applySecrets } from './secrets.js';
27
+ import { Gate } from 'bareguard';
21
28
 
22
29
  const AGENT = Symbol('agent');
23
30
  const SECURE = Symbol('secure');
24
31
  const IP_RE = /^\d+\.\d+\.\d+\.\d+$/;
25
32
  // Hop-by-hop headers must not be forwarded: node's HTTP stack re-frames.
26
33
  const HOP_REQ = new Set(['proxy-connection', 'proxy-authorization']);
34
+ // Bodies up to this size are read whole (under the agent's working slot) so
35
+ // the card floor can scan them; a bigger body streams on, unchecked.
36
+ const WORK_BODY_LIMIT = 65536;
37
+ // Small teams: one proxy serves at most this many agents (the TCP door's
38
+ // 'tcp' agent is not counted); more agents means another proxy.
39
+ const MAX_AGENTS = 40;
40
+ const EMPTY = Buffer.alloc(0);
27
41
  const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
28
42
  'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade']);
29
43
 
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
44
  /**
59
45
  * Options for {@link createProxy}.
60
46
  *
61
47
  * @typedef {object} ProxyOptions
62
- * @property {string} logFile JSON-lines log path (`req`, `resp`, `deny`, `hold`, `decide`, `hold-abandoned`)
48
+ * @property {string} logFile the runtime's one audit file (`runtimePaths(runtime).audit`), in bareguard's JSON-lines shape: every agent's gate and the runtime's own `sbx` gate append to it. barebox's own facts are `annotate` lines (`verdict` = `resp`, `deny`, `hold`, `decide`, `hold-abandoned`, ...); a response status is a `record` line joined to its request's `check` by `aid`.
63
49
  * @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
50
  * @property {number} [port] opt-in TCP listener for tests, bound to 127.0.0.1 only (default: none)
65
51
  * @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
52
+ * @property {(agent: string, ctx: { humanChannel: (event: any) => Promise<{ decision: 'allow' | 'deny', reason?: string }>, tools: Record<string, any> }) => GateLike | Promise<GateLike>} [gateFor] builds the gate that decides one agent's requests (called once per agent, and once for the TCP door's `tcp` agent); `ctx.humanChannel` is the hold queue and `ctx.tools` the runtime's one tools table, both to hand to a bareguard `Gate`. Omit it to forward everything.
53
+ * @property {{ matcher: { match: (method: string, url: string) => { key: string, source: string } }, tools: Record<string, any> }} [labels] the loaded label files (see `loadLabels`); omitted means no labels, only the built-in model endpoints
54
+ * @property {string[]} [allowLocal] exact `host:port` pairs (the `localLlm` setting) that may pass the wall's private/loopback check; any other local destination is still denied
55
+ * @property {HoldOptions} [hold] hold queue config (deadline, caps, ask seam)
67
56
  * @property {number} [upstreamTimeoutMs] give up on an upstream response after this (default 120000)
68
57
  * @property {object} [unsafeTestOnly] TEST-ONLY escape hatch: everything under
69
58
  * it weakens the sandbox wall, so production omits it and tests name it loudly.
@@ -72,19 +61,24 @@ function scrubSecrets(entry) {
72
61
  * so tests pass this; production never should.
73
62
  * @property {(host: string) => Promise<string[] | string | null>} [unsafeTestOnly.resolveUpstream]
74
63
  * DNS stub: replaces the wall's resolver so rebinding is testable. Production omits it.
64
+ * @property {import('./secrets.js').Secret[]} [secrets] the loaded secrets (`loadSecrets`): a request carrying a secret's placeholder in a header gets the real value there only after the gate allowed it and only for a bound host; for any other host it is refused `403 denied: secret.host`. The value never reaches the audit file, an ask or an error body.
75
65
  * @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)
66
+ * @property {(entry: Record<string, unknown>) => Record<string, unknown>} [redact] log redaction hook, applied after built-in secret scrubbing; its result becomes the `meta` of an `annotate` line (default: identity)
67
+ */
68
+
69
+ /**
70
+ * Anything with bareguard's `check`: a `Gate`, or a plain object for tests. An
71
+ * `askHuman` outcome from a plain object goes to the same human channel.
72
+ *
73
+ * @typedef {{ check: (action: Record<string, unknown>) => Promise<{ outcome: string, rule?: string, reason?: string | null, aid?: string }>, record?: (action: Record<string, unknown>, result: Record<string, unknown>, opts?: { aid?: string }) => Promise<void>, annotate?: (fact: Record<string, unknown>) => Promise<void>, drainAnnotations?: () => unknown[] }} GateLike
78
74
  */
79
75
 
80
76
  /**
81
- * Hold queue options (the decision seam lives in holds.js).
77
+ * Hold queue options (the queue lives in holds.js).
82
78
  *
83
79
  * @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
80
  * @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)
81
+ * @property {number} [maxBody] bodies over this are denied at the door, never queued; held bodies spool to `<runtime>/held` (default 52428800)
88
82
  * @property {import('./holds.js').OnAsk|null} [onAsk] ask seam (bareguard `humanChannel` shape).
89
83
  * When present no files are involved; omit it for the default file checkpoint
90
84
  * (`<runtime>/asks` + `<runtime>/answers`, `sbx pending/approve/deny`).
@@ -100,9 +94,11 @@ function scrubSecrets(entry) {
100
94
  * @property {string} method HTTP method
101
95
  * @property {string} url full URL
102
96
  * @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)
97
+ * @property {Buffer} [body] buffered body
98
+ * @property {Buffer} [prefix] bytes already read from `stream`, written upstream before it
99
+ * @property {import('node:stream').Readable} [stream] live body: the request itself, or a held body's file
105
100
  * @property {import('node:http').ServerResponse} cres parked or live client response
101
+ * @property {{ gate: GateLike, action: Record<string, unknown>, aid: string }} [rec] the deciding gate, the request's action and the decision's aid: the response status is recorded there (absent: it is logged as a `resp` fact)
106
102
  */
107
103
 
108
104
  /**
@@ -112,8 +108,7 @@ function scrubSecrets(entry) {
112
108
  */
113
109
 
114
110
  /**
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
111
+ * Start the front-door proxy. Every request is audited with its method and URL, and a request with a body also with its byte count and SHA-256 (never headers or body text); bytes go upstream untouched. Requests the hold rule
117
112
  * flags park for a human decision instead of forwarding.
118
113
  *
119
114
  * @param {ProxyOptions} opts
@@ -128,12 +123,20 @@ function scrubSecrets(entry) {
128
123
  */
129
124
  export function createProxy(opts) {
130
125
  const { logFile, runtime, port = null,
131
- upstreamCa = null, hold = null,
126
+ upstreamCa = null, hold = null, gateFor = null, allowLocal = [], labels = null,
132
127
  upstreamTimeoutMs = 120000, clientIdleMs = 60000,
133
- unsafeTestOnly = null,
134
- maxLogBody = 1048576, redact = (e) => e } = opts ?? {};
128
+ unsafeTestOnly = null, secrets = [],
129
+ redact = (e) => e } = opts ?? {};
135
130
  const { allowLoopback = false, resolveUpstream = null } = unsafeTestOnly ?? {};
136
- const gate = { allowLoopback, resolveUpstream: resolveUpstream ?? undefined };
131
+ const gate = {
132
+ allowLoopback, resolveUpstream: resolveUpstream ?? undefined,
133
+ allowLocal: new Set(allowLocal.map((e) => String(e).toLowerCase())),
134
+ };
135
+ /** @param {URL} u @returns {number} */
136
+ const portOf = (u) => (u.port ? parseInt(u.port, 10) : (u.protocol === 'https:' ? 443 : 80));
137
+ // One tools table and one matcher per runtime, shared by every gate.
138
+ const matcher = labels?.matcher ?? emptyMatcher;
139
+ const tools = buildTools(labels?.tools, [...allowLocal]);
137
140
  if (!logFile) throw new Error('createProxy: logFile is required');
138
141
  if (typeof runtime !== 'string' || !runtime) throw new Error('createProxy: runtime is required');
139
142
  // One live proxy per runtime, enforced here: claimed before the hold
@@ -143,36 +146,95 @@ export function createProxy(opts) {
143
146
  // Always `<runtime>/certs`: one layout, owned by runtime.js, so there is
144
147
  // nothing to contain and no check to fail.
145
148
  const certDir = runtimePaths(runtime).certsDir;
146
- const holdMaxBody = hold?.maxBody ?? 1048576;
149
+ const holdMaxBody = hold?.maxBody ?? DEFAULT_HOLD_MAX_BODY;
150
+ const heldFile = runtimePaths(runtime).heldFile;
147
151
 
148
- // Open the audit log synchronously: a bad `logFile` (a directory, a
152
+ // Open the audit file synchronously: a bad `logFile` (a directory, a
149
153
  // missing parent, no permission) throws here, where the claim can still
150
- // be released — not later as an uncaught stream error.
151
- let logFd;
154
+ // be released — not later as an uncaught error. bareguard appends to it.
152
155
  try {
153
- logFd = fs.openSync(logFile, 'a', 0o600);
156
+ fs.closeSync(fs.openSync(logFile, 'a', 0o600));
154
157
  } catch (e) {
155
158
  const msg = e instanceof Error ? e.message : String(e);
156
159
  releaseClaim();
157
160
  throw new Error(`createProxy: cannot open logFile ${logFile}: ${msg}`);
158
161
  }
159
- const logStream = fs.createWriteStream(logFile, { fd: logFd });
160
162
  // `openSync`'s mode is masked by the umask and doesn't apply to an
161
163
  // existing file: a 0644 log from an older run would stay world-readable
162
164
  // while new lines append, so fix it up on every start.
163
165
  try { fs.chmodSync(logFile, 0o600); } catch {}
166
+
167
+ // The audit file has one shape: bareguard's. A response status is a
168
+ // `gate.record` joined to its request's `check` by aid; every other fact is
169
+ // an `annotate({ surface: false })` on the agent's gate when it is built, else
170
+ // on the runtime's own `sbx` gate (which never runs `check()`).
171
+ /** @type {GateLike} */
172
+ let sbxGate;
173
+ try {
174
+ sbxGate = /** @type {GateLike} */ (/** @type {unknown} */ (new Gate({ audit: { path: logFile } })));
175
+ } catch (e) {
176
+ releaseClaim();
177
+ throw e;
178
+ }
179
+ const sbxInit = /** @type {{ init: () => Promise<void> }} */ (/** @type {unknown} */ (sbxGate)).init();
180
+ sbxInit.catch(() => {}); // reported by the first line that awaits it
181
+ /** Gates by agent: the only place a gate is kept (see `gateOf`). @type {Map<string, { p: Promise<GateLike>, gate: GateLike|null }>} */
182
+ const gates = new Map();
183
+ /** @type {Set<Promise<void>>} */
184
+ const pendingLog = new Set();
185
+ let logClosing = false;
164
186
  let logFailed = false;
165
- logStream.on('error', (e) => {
187
+ /** @param {unknown} e */
188
+ const logFail = (e) => {
166
189
  if (logFailed) return;
167
190
  logFailed = true;
168
191
  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
192
  };
193
+ /** Track one audit write; a failure is reported once, never thrown. @param {() => Promise<unknown>} fn */
194
+ const track = (fn) => {
195
+ // After close() ends the flush a late line (a socket torn down by close)
196
+ // is dropped on purpose: a write nobody waits for would wedge close().
197
+ if (logClosing) return;
198
+ const p = fn().then(() => {}, logFail).then(() => { pendingLog.delete(p); });
199
+ pendingLog.add(p);
200
+ };
201
+ /** Cut a string field. @param {unknown} v @param {number} n */
202
+ const cut = (v, n) => (typeof v === 'string' ? v.slice(0, n) : v);
203
+ /**
204
+ * barebox's fact as the `meta` of an annotate. The per-field cuts keep audit
205
+ * lines short; bareguard 0.30.0 drops whole keys over its own cap.
206
+ * @param {Record<string, unknown>} o
207
+ * @returns {Record<string, unknown>}
208
+ */
209
+ const metaOf = (o) => {
210
+ const { ev: _ev, ...meta } = redact(o);
211
+ meta['url'] = cut(meta['url'], 400);
212
+ meta['note'] = cut(meta['note'], 200);
213
+ meta['reason'] = cut(meta['reason'], 200);
214
+ return meta;
215
+ };
216
+ /** @param {Record<string, unknown>} o */
217
+ async function writeLog(o) {
218
+ const agent = typeof o['agent'] === 'string' ? o['agent'] : null;
219
+ // Never build a gate from here: a built one, else the sbx gate.
220
+ const entry = agent ? gates.get(agent) : undefined;
221
+ const cand = entry?.gate ?? null;
222
+ const g = cand && typeof cand.annotate === 'function' ? cand : sbxGate;
223
+ if (g === sbxGate) await sbxInit;
224
+ const where = [o['id'], o['agent'], o['code'], o['method'], o['url'] ?? o['note']]
225
+ .filter((x) => x !== undefined && x !== null).join(' ');
226
+ try {
227
+ await /** @type {NonNullable<GateLike['annotate']>} */ (g.annotate)({
228
+ surface: false, verdict: String(o['ev']), where, meta: metaOf(o) });
229
+ } finally {
230
+ // Normal use of bareguard's API for a process with no turns: it keeps memory at zero facts
231
+ // (0.30.0 caps the buffer at 256, which could reach about 350 KB per gate). No upstream ask is pending.
232
+ g.drainAnnotations?.();
233
+ }
234
+ }
235
+ // Synchronous for callers (holds.js shares it); the write is tracked.
236
+ /** @param {Record<string, unknown>} o */
237
+ const log = (o) => { track(() => writeLog(o)); };
176
238
  let trust = null;
177
239
  if (upstreamCa) {
178
240
  let extra;
@@ -218,18 +280,29 @@ export function createProxy(opts) {
218
280
  // Enforcement sits here (every forward, incl. the approve path) AND at
219
281
  // the door (request handler + CONNECT): a parked hold is re-checked on
220
282
  // approve, so a DNS change while parked cannot slip through.
283
+ // A body stream nobody will pipe: a held file is closed (its owner then
284
+ // deletes it); a live request is drained so its response can go out.
285
+ /** @param {import('node:stream').Readable|undefined} stream */
286
+ function discard(stream) {
287
+ try {
288
+ if (stream instanceof fs.ReadStream) stream.destroy();
289
+ else stream?.resume();
290
+ } catch {}
291
+ }
292
+
221
293
  /** @param {ForwardArgs} args */
222
- async function forward({ agent, method, url, headers, body, stream, cres }) {
294
+ async function forward({ agent, method, url, headers, body, prefix, stream, cres, rec }) {
223
295
  let u;
224
296
  try {
225
297
  u = new URL(url);
226
298
  } catch {
299
+ discard(stream);
227
300
  denyRes(cres, 400, 'bad request target');
228
301
  return;
229
302
  }
230
- const verdict = await checkUpstream(u.hostname, gate);
303
+ const verdict = await checkUpstream(u.hostname, gate, portOf(u));
231
304
  if (!verdict.ok) {
232
- try { stream?.resume(); } catch {}
305
+ discard(stream);
233
306
  denyRes(cres, 403, verdict.reason);
234
307
  return;
235
308
  }
@@ -237,19 +310,19 @@ export function createProxy(opts) {
237
310
  // throw before it can answer must still be loud, never a floating reject.
238
311
  // The dial is pinned to the checked IPs: no second DNS resolution.
239
312
  try {
240
- forwardInner({ agent, method, url, headers, body, stream, cres, u, upstreamIps: verdict.ips });
313
+ forwardInner({ agent, method, url, headers, body, prefix, stream, cres, rec, u, upstreamIps: verdict.ips });
241
314
  } catch (e) {
242
315
  // The live stream arrives paused (see handleRequest): unpause so no
243
316
  // paused stream leaks on this path.
244
- try { stream?.resume(); } catch {}
317
+ discard(stream);
245
318
  denyRes(cres, 502, `upstream failed: ${e.message}`);
246
319
  }
247
320
  }
248
321
 
249
322
  /** @param {ForwardArgs & { u: URL, upstreamIps: string[] }} args */
250
- function forwardInner({ agent, method, url, headers, body, stream, cres, u, upstreamIps }) {
323
+ function forwardInner({ agent, method, url, headers, body, prefix, stream, cres, rec, u, upstreamIps }) {
251
324
  const sock = cres.socket;
252
- if (!sock) return; // no transport left to answer on
325
+ if (!sock) { discard(stream); return; } // no transport left to answer on
253
326
  const secure = u.protocol === 'https:';
254
327
  /** @type {Record<string, string | string[] | undefined>} */
255
328
  const fwdHeaders = {};
@@ -302,7 +375,11 @@ export function createProxy(opts) {
302
375
  if (!HOP_RESP.has(k.toLowerCase()) && v !== undefined) respHeaders[k] = v;
303
376
  }
304
377
  if (ures.statusCode === undefined) { fail('upstream sent no status'); up.destroy(); return; }
305
- log({ ev: 'resp', agent, url, status: ures.statusCode });
378
+ const status = ures.statusCode;
379
+ if (rec && typeof rec.gate.record === 'function') {
380
+ const { gate: g, action, aid } = rec;
381
+ track(() => /** @type {NonNullable<GateLike['record']>} */ (g.record)(action, { status }, { aid }));
382
+ } else log({ ev: 'resp', agent, url, status });
306
383
  try {
307
384
  cres.writeHead(ures.statusCode, respHeaders);
308
385
  } catch (e) { fail(`cannot frame upstream response: ${e.message}`); up.destroy(); return; }
@@ -320,28 +397,36 @@ export function createProxy(opts) {
320
397
  if (!done && !cres.writableEnded) { done = true; upstreams.delete(up); up.destroy(); }
321
398
  });
322
399
  if (body) up.end(body);
323
- else if (stream) stream.pipe(up);
324
- else up.end();
400
+ else if (stream) {
401
+ // A held body's file: closed when the request is done with it, and a
402
+ // read failure (the file vanished) fails the request, never crashes.
403
+ if (stream instanceof fs.ReadStream) {
404
+ up.once('close', () => stream.destroy());
405
+ stream.once('error', (e) => up.destroy(e));
406
+ }
407
+ if (prefix?.length) up.write(prefix);
408
+ stream.pipe(up);
409
+ } else up.end();
325
410
  }
326
411
 
327
412
  // The rest of setup is infallible synchronously except this call, so a
328
413
  // throw here releases the claim before it propagates (like upstreamCa
329
414
  // above); async failures release through `ready` and `close()` below.
415
+ // The queue is the gate's human channel, so a gate means a queue.
330
416
  let holds = null;
331
417
  try {
332
- holds = hold ? createHolds({
418
+ holds = (hold || gateFor) ? createHolds({
333
419
  log,
334
- shouldHold: hold.shouldHold,
335
- match: hold.match,
336
- timeoutMs: hold.timeoutMs,
420
+ timeoutMs: hold?.timeoutMs,
337
421
  maxBody: holdMaxBody,
338
422
  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}`),
423
+ onAsk: hold?.onAsk,
424
+ pollMs: hold?.pollMs,
425
+ onEvent: hold?.onEvent,
426
+ // A parked request's pending ask ends here: handleRequest, awaiting
427
+ // its gate, then forwards or refuses.
428
+ onApprove: (h) => h.finish({ decision: 'allow' }),
429
+ onDeny: (h, reason) => h.finish({ decision: 'deny', reason }),
345
430
  }) : null;
346
431
  } catch (e) {
347
432
  releaseClaim();
@@ -351,9 +436,209 @@ export function createProxy(opts) {
351
436
  const server = http.createServer((creq, cres) => {
352
437
  // Async only for the wall's DNS lookup; no body listener is attached
353
438
  // before the check, so nothing is lost while it resolves.
354
- handleRequest(creq, cres).catch((e) => denyRes(cres, 500, `proxy failed: ${e.message}`));
439
+ reqDone.set(creq, handleRequest(creq, cres)
440
+ .catch((e) => denyRes(cres, 500, `proxy failed: ${e.message}`)));
355
441
  });
356
442
 
443
+ /** Each request's handler promise, so `close()` can wait for those inside a gate check. @type {WeakMap<object, Promise<void>>} */
444
+ const reqDone = new WeakMap();
445
+
446
+ /**
447
+ * Gates by agent, built lazily (and at `addAgent`): one per agent, so the
448
+ * grant is the agent's own. `gates` (declared with the log) is the only
449
+ * place a gate is kept; `entry.gate` is set once the build settled.
450
+ *
451
+ * @param {string} agent
452
+ * @returns {Promise<GateLike>}
453
+ */
454
+ function gateOf(agent) {
455
+ let e = gates.get(agent);
456
+ if (!e) {
457
+ if (!gateFor) throw new Error('createProxy: no gateFor');
458
+ const p = Promise.resolve().then(() => gateFor(agent, { humanChannel: askHuman, tools }));
459
+ const entry = { p, gate: /** @type {GateLike|null} */ (null) };
460
+ e = entry;
461
+ gates.set(agent, entry);
462
+ p.then((g) => { entry.gate = g; },
463
+ // A failed build must not stick: the next request tries again, loudly.
464
+ () => { if (gates.get(agent) === entry) gates.delete(agent); });
465
+ }
466
+ return e.p;
467
+ }
468
+
469
+ /**
470
+ * Requests inside `gate.check()`, by `rid`: how the human channel finds
471
+ * the request an ask is about. handleRequest sets and deletes each entry
472
+ * (the one writer); the channel only reads it and sets the fields it owns
473
+ * (`asked`, `status`, `heldId`, `endAsk`).
474
+ *
475
+ * @type {Map<string, RequestCtx>}
476
+ */
477
+ const inflightCtx = new Map();
478
+ let ridN = 0;
479
+
480
+ /**
481
+ * @typedef {object} RequestCtx
482
+ * @property {string} agent agent name
483
+ * @property {string} method HTTP method
484
+ * @property {string} url full URL
485
+ * @property {Record<string, string | string[] | undefined>} headers request headers
486
+ * @property {import('node:http').IncomingMessage} creq the request (paused)
487
+ * @property {import('node:http').ServerResponse} cres the response
488
+ * @property {ReturnType<typeof makeTee>} tee the body tee (masked preview, byte count)
489
+ * @property {boolean} hasBody the request carries a body
490
+ * @property {Buffer[]} chunks the body bytes read so far (up to ~64 KB)
491
+ * @property {boolean} over more body follows `chunks`, unread in `creq`
492
+ * @property {() => void} freeWork release the agent's working slot (idempotent)
493
+ * @property {boolean} asked the human channel took this request
494
+ * @property {number|null} status HTTP status the channel wants for a denial (null: 403)
495
+ * @property {string|null} heldId id of the held body file, once spooled
496
+ * @property {((reason: string) => void)|null} endAsk end a not-yet-parked ask as a denial
497
+ */
498
+
499
+ /**
500
+ * The human channel (bareguard `humanChannel` shape): every gate's asks
501
+ * come here. Finds the request by `event.action.rid`, then holds it.
502
+ *
503
+ * @param {{ action?: { rid?: unknown }, rule?: string, rwxLetter?: string }} event
504
+ * @returns {Promise<{ decision: 'allow' | 'deny', reason?: string }>}
505
+ */
506
+ async function askHuman(event) {
507
+ const ctx = inflightCtx.get(String(event?.action?.rid));
508
+ if (!ctx) return { decision: 'deny', reason: 'request gone' };
509
+ ctx.asked = true;
510
+ return holdRequest(ctx, event);
511
+ }
512
+
513
+ /**
514
+ * Hold one request for the human: reserve the agent's hold slot, spool the
515
+ * body to `<runtime>/held/<id>` (the bytes already read plus the rest of
516
+ * the stream, capped at `holdMaxBody`), free the working slot, park, and
517
+ * wait. The promise settles once: on the queue's decision, on expiry, or
518
+ * when the client or the proxy goes away first.
519
+ *
520
+ * @param {RequestCtx} ctx the request
521
+ * @param {{ rule?: string, rwxLetter?: string }} event the gate's ask
522
+ * @returns {Promise<{ decision: 'allow' | 'deny', reason?: string }>}
523
+ */
524
+ function holdRequest(ctx, event) {
525
+ return new Promise((resolve) => {
526
+ const queue = /** @type {NonNullable<typeof holds>} */ (holds);
527
+ const { agent, cres, creq } = ctx;
528
+ const sock = cres.socket;
529
+ let settled = false;
530
+ let parked = false;
531
+ let dead = false;
532
+ /** @type {import('node:fs').WriteStream|null} */
533
+ let ws = null;
534
+ /** @param {{ decision: 'allow' | 'deny', reason?: string }} d */
535
+ const finish = (d) => {
536
+ if (settled) return;
537
+ settled = true;
538
+ ctx.endAsk = null;
539
+ resolve(d);
540
+ };
541
+ /** @param {string} reason @param {number} [status] */
542
+ const refuse = (reason, status) => {
543
+ if (settled) return; // a late failure must not rewrite the settled deny's status
544
+ if (status) ctx.status = status;
545
+ finish({ decision: 'deny', reason });
546
+ };
547
+ const abort = () => {
548
+ if (dead) return;
549
+ dead = true;
550
+ ws?.destroy();
551
+ queue.dropBody(slot.id);
552
+ };
553
+ /** @param {string} why @param {number} [status] */
554
+ const fail = (why, status) => {
555
+ if (parked) return; // parked: the queue owns the end
556
+ abort();
557
+ slot.cancel();
558
+ refuse(why, status);
559
+ };
560
+ if (closed) { refuse('proxy closing'); return; }
561
+ if (!sock || sock.destroyed) { refuse('client gone'); return; }
562
+ const slot = queue.reserve(agent, {
563
+ onReady: () => stream(),
564
+ onExpire: (why) => { abort(); refuse(why); },
565
+ });
566
+ if (slot.state === 'full') { ctx.freeWork(); refuse('hold queue full', 429); return; }
567
+ ctx.endAsk = (why) => fail(why);
568
+ cres.on('close', () => ctx.endAsk?.('client gone'));
569
+ let size = 0;
570
+ if (ctx.hasBody) {
571
+ // The bytes already read go to the body file at once, so a request
572
+ // waiting in line holds no body in memory.
573
+ try {
574
+ // Open synchronously: a later unlink can then never race the create.
575
+ ws = fs.createWriteStream('', { fd: fs.openSync(heldFile(slot.id), 'wx', 0o600) });
576
+ } catch (e) {
577
+ fail(`cannot hold body: ${e instanceof Error ? e.message : String(e)}`, 500);
578
+ ctx.freeWork();
579
+ return;
580
+ }
581
+ ws.on('error', (e) => fail(`cannot hold body: ${e.message}`, 500));
582
+ for (const c of ctx.chunks) {
583
+ size += c.length;
584
+ ws.write(c);
585
+ }
586
+ ctx.chunks = [];
587
+ ctx.heldId = slot.id;
588
+ if (size > holdMaxBody) fail('body too large to hold');
589
+ }
590
+ // The working slot is released: a queued hold must not stop the
591
+ // agent's next body from being read.
592
+ ctx.freeWork();
593
+ if (slot.state === 'now') stream();
594
+
595
+ // At the front of the line: take the rest of the body, then park.
596
+ function stream() {
597
+ if (settled || dead) return;
598
+ const parkIt = () => {
599
+ if (dead || settled) return;
600
+ // Parked: the tunnel stays open until the ask channel decides.
601
+ // null: the reservation already expired and onExpire refused.
602
+ parked = queue.add({ agent, method: ctx.method, url: ctx.url,
603
+ preview: bodyPreview(ctx.tee.head), bodyBytes: ctx.tee.bytes,
604
+ sock, note: event.rule ?? 'ask', letter: event.rwxLetter, finish,
605
+ slot, arrivedAt: slot.arrivedAt }) !== null;
606
+ };
607
+ const done = () => { if (ws) { ws.once('finish', parkIt); ws.end(); } else parkIt(); };
608
+ if (!ctx.over) { done(); return; }
609
+ creq.on('data', (c) => {
610
+ if (dead) return;
611
+ size += c.length;
612
+ if (size > holdMaxBody) { fail('body too large to hold'); return; }
613
+ if (ws && !ws.write(c)) {
614
+ creq.pause();
615
+ ws.once('drain', () => creq.resume());
616
+ }
617
+ });
618
+ creq.on('error', () => { fail('client body failed', 502); });
619
+ creq.on('end', () => { if (!dead) done(); });
620
+ creq.resume();
621
+ }
622
+ });
623
+ }
624
+
625
+ /**
626
+ * The one decision for a request: the gate's `check`, and, for a plain
627
+ * check object that answers `askHuman`, the same human channel.
628
+ *
629
+ * @param {GateLike} g the agent's gate
630
+ * @param {Record<string, unknown>} action the request as an action
631
+ * @returns {Promise<{ outcome: string, rule?: string, reason?: string | null, aid?: string }>} terminal allow or deny
632
+ */
633
+ async function decideAction(g, action) {
634
+ const d = await g.check(action);
635
+ if (d.outcome !== 'askHuman') return d;
636
+ const h = await askHuman({ action, rule: d.rule });
637
+ return h.decision === 'allow'
638
+ ? { outcome: 'allow', rule: 'humanChannel.allow', aid: d.aid }
639
+ : { outcome: 'deny', rule: d.rule, reason: h.reason ?? 'denied', aid: d.aid };
640
+ }
641
+
357
642
  async function handleRequest(creq, cres) {
358
643
  const sock = creq.socket;
359
644
  const agent = agentOf(sock);
@@ -371,84 +656,215 @@ export function createProxy(opts) {
371
656
  const method = creq.method;
372
657
  if (!method) { denyRes(cres, 400, 'bad request method'); return; }
373
658
  const urlStr = url.toString();
374
- const verdict = await checkUpstream(url.hostname, gate);
659
+ const verdict = await checkUpstream(url.hostname, gate, portOf(url));
375
660
  if (!verdict.ok) {
376
661
  try { creq.resume(); } catch {}
377
662
  denyRes(cres, 403, verdict.reason);
378
663
  return;
379
664
  }
380
- const queue = holds;
381
- const reason = queue ? queue.decide({ agent, method, url: urlStr, headers: creq.headers }) : null;
382
-
383
- // Tee the body for the log (capped). A held request buffers it whole —
384
- // bounded by maxBody — so approve can forward it after the human decides.
385
- // Anything else streams straight through; the tee only feeds the log.
386
- const chunks = [];
387
- let size = 0;
388
- let over = false;
389
- const finishLog = () => {
390
- const body = Buffer.concat(chunks);
391
- log({ ev: 'req', agent, method: creq.method, url: urlStr,
392
- headers: creq.headers, body: body.toString('utf8'),
393
- ...(over ? { truncated: true, bodyBytes: size } : {}) });
394
- return body;
395
- };
396
- if (!reason || !queue) {
397
- // Pause before any body listener: the tee below would otherwise put
398
- // the stream in flowing mode, and forward() awaits a second wall
399
- // check before forwardInner pipes to upstream — body bytes arriving
400
- // during that wait would go to the tee only, starving upstream
401
- // against Content-Length. Buffered here, pipe() resumes the flow,
402
- // so both the tee and upstream see the whole body.
403
- creq.pause();
404
- creq.on('data', (c) => {
405
- size += c.length;
406
- if (size > maxLogBody || over) { over = true; return; }
407
- chunks.push(c);
408
- });
409
- creq.on('end', finishLog);
410
- creq.on('error', () => {});
411
- forward({ agent, method, url: urlStr,
412
- headers: { ...creq.headers }, stream: creq, cres });
665
+ // The request's one id: the audit lines of its secret swap, its body and
666
+ // its gate decision all carry it.
667
+ const rid = `r${++ridN}`;
668
+ // M5: a placeholder is found before the gate and swapped only after it
669
+ // allows (`withSecrets`), so the real value never sits in `ctx.headers`
670
+ // while the request waits for a decision. A placeholder headed for a host
671
+ // its secret is not bound to is refused in every mode.
672
+ const found = secrets.length ? findPlaceholders(creq.headers, url.hostname, secrets) : [];
673
+ const unbound = found.filter((f) => !f.bound);
674
+ if (unbound.length) {
675
+ for (const f of unbound) log({ ev: 'secret', agent, rid, name: f.name, host: url.hostname, swapped: false });
676
+ try { creq.resume(); } catch {}
677
+ denyRes(cres, 403, 'denied: secret.host');
678
+ return;
679
+ }
680
+ // A real value only ever goes upstream over TLS: forwardInner picks
681
+ // https from this same `url.protocol`, so a cleartext hop is refused here.
682
+ if (found.length && url.protocol !== 'https:') {
683
+ for (const f of found) log({ ev: 'secret', agent, rid, name: f.name, host: url.hostname, swapped: false });
684
+ try { creq.resume(); } catch {}
685
+ denyRes(cres, 403, 'denied: secret.scheme');
413
686
  return;
414
687
  }
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.
688
+ /** The headers to forward: the real values in, one audit line per swap. @param {Record<string, string | string[] | undefined>} headers */
689
+ const withSecrets = (headers) => {
690
+ if (!found.length) return headers;
691
+ for (const f of found) log({ ev: 'secret', agent, rid, name: f.name, host: url.hostname, swapped: true });
692
+ return applySecrets(headers, url.hostname, secrets);
693
+ };
694
+ const cl = Number(creq.headers['content-length'] ?? 0);
695
+ const hasBody = creq.headers['transfer-encoding'] !== undefined || cl > 0;
696
+
697
+ // Pause before any body listener: a listener would put the stream in
698
+ // flowing mode and starve whoever reads it next. The tee sees every body
699
+ // byte once, whatever path reads it, and feeds the ask (a masked
700
+ // 4 KB preview) and the audit's `body` fact (byte count and SHA-256).
418
701
  creq.pause();
419
- const readHeld = () => {
420
- creq.on('data', (c) => {
421
- size += c.length;
422
- if (size > holdMaxBody) { over = true; return; }
702
+ const tee = makeTee();
703
+ creq.on('data', (c) => tee.push(c));
704
+ // `end` fires once the whole body was read, whichever path read it (also
705
+ // a streamed body past 64 KB), so the values cover all of it. A client
706
+ // that aborts mid-body never reaches `end`: no line, as before.
707
+ if (hasBody) {
708
+ creq.on('end', () => log({ ev: 'body', agent, rid, bodyBytes: tee.bytes, bodySha256: tee.digest() }));
709
+ }
710
+ creq.on('error', () => {});
711
+
712
+ // No gate: straight through. pipe() resumes the flow.
713
+ if (!gateFor) {
714
+ forward({ agent, method, url: urlStr, headers: withSecrets({ ...creq.headers }), stream: creq, cres });
715
+ return;
716
+ }
717
+
718
+ // One decision path. A body is read first (one body at a time per agent,
719
+ // up to 64 KB, so the card floor can scan it); then the agent's gate
720
+ // decides; a gate that asks runs the human channel inside `check()`.
721
+ let freed = false;
722
+ /** @type {() => void} */
723
+ let free = () => {};
724
+ const freeWork = () => { if (!freed) { freed = true; free(); } };
725
+ try {
726
+ if (hasBody) {
727
+ free = await takeWorkSlot(agent, cres);
728
+ } else creq.resume();
729
+ if (sock.destroyed) return;
730
+ /** @type {RequestCtx} */
731
+ const ctx = { agent, method, url: urlStr, headers: { ...creq.headers }, creq, cres, tee,
732
+ hasBody, chunks: [], over: false, freeWork, asked: false, status: null, heldId: null,
733
+ endAsk: null };
734
+ let cardLike = false;
735
+ if (hasBody) {
736
+ if (await readWorkBody(ctx)) return;
737
+ // Past 64 KB the body streams on unscanned (known gap).
738
+ if (!ctx.over) cardLike = createCardScanner().push(Buffer.concat(ctx.chunks));
739
+ }
740
+ // The body never goes in the action: bareguard writes the action to its audit file.
741
+ const action = { type: 'net', tool: toolFor(matcher, tools, method, urlStr), url: urlStr, method, agent,
742
+ cardLike, paymentPath: paymentPath(urlStr), rid };
743
+ inflightCtx.set(rid, ctx);
744
+ const g = await gateOf(agent);
745
+ const d = await decideAction(g, action);
746
+ if (d.outcome === 'allow') {
747
+ const common = { agent, method, url: urlStr, headers: withSecrets(ctx.headers), cres,
748
+ ...(d.aid ? { rec: { gate: g, action, aid: d.aid } } : {}) };
749
+ if (ctx.heldId) {
750
+ // The file is the exact body; the client's own framing (length or
751
+ // chunked) still describes it. It is deleted once the upstream is done.
752
+ const id = ctx.heldId;
753
+ const rs = fs.createReadStream(heldFile(id));
754
+ rs.on('close', () => holds?.dropBody(id));
755
+ await forward({ ...common, stream: rs });
756
+ } else if (!hasBody) {
757
+ await forward({ ...common, body: EMPTY });
758
+ } else if (ctx.over) {
759
+ // Past 64 KB: send what was read, pipe the rest.
760
+ await forward({ ...common, prefix: Buffer.concat(ctx.chunks), stream: creq });
761
+ } else {
762
+ await forward({ ...common, body: Buffer.concat(ctx.chunks) });
763
+ }
764
+ } else {
765
+ discard(creq);
766
+ const why = ctx.asked
767
+ ? `denied: ${d.reason ?? 'denied'}`
768
+ : `denied: ${d.rule ?? 'gate'}${d.reason ? `: ${d.reason}` : ''}`;
769
+ denyRes(cres, ctx.status ?? 403, why);
770
+ }
771
+ } finally {
772
+ inflightCtx.delete(rid);
773
+ freeWork();
774
+ }
775
+ }
776
+
777
+ /**
778
+ * Constant-memory tee of a request body: the first ASK_BODY_LIMIT bytes,
779
+ * the byte count and a running SHA-256.
780
+ */
781
+ function makeTee() {
782
+ const hash = crypto.createHash('sha256');
783
+ let head = EMPTY;
784
+ let bytes = 0;
785
+ return {
786
+ push(/** @type {Buffer} */ c) {
787
+ hash.update(c);
788
+ bytes += c.length;
789
+ if (head.length < ASK_BODY_LIMIT) head = Buffer.concat([head, c.subarray(0, ASK_BODY_LIMIT - head.length)]);
790
+ },
791
+ get head() { return head; },
792
+ get bytes() { return bytes; },
793
+ digest: () => hash.copy().digest('hex'),
794
+ };
795
+ }
796
+
797
+ // One working slot per agent: a FIFO of body reads. A slot frees when its
798
+ // holder calls the returned function, or when its response closes (a dead
799
+ // client never wedges the line). Waiters stay paused and unread.
800
+ /** @type {Map<string, Promise<void>>} */
801
+ const workTail = new Map();
802
+ /**
803
+ * @param {string} agent agent name
804
+ * @param {import('node:http').ServerResponse} cres the request's response
805
+ * @returns {Promise<() => void>} resolves with `free` once the slot is ours
806
+ */
807
+ function takeWorkSlot(agent, cres) {
808
+ const prev = workTail.get(agent) ?? Promise.resolve();
809
+ /** @type {() => void} */
810
+ let free = () => {};
811
+ const mine = new Promise((resolve) => { free = () => resolve(undefined); });
812
+ const tail = prev.then(() => mine);
813
+ workTail.set(agent, tail);
814
+ void tail.then(() => { if (workTail.get(agent) === tail) workTail.delete(agent); });
815
+ cres.once('close', free);
816
+ return prev.then(() => free);
817
+ }
818
+
819
+ /**
820
+ * Read the working slice of the body into `ctx.chunks` and `ctx.over`. Its
821
+ * own frame, so no reference to the chunks outlives a later spool to disk.
822
+ *
823
+ * @param {RequestCtx} ctx request context
824
+ * @returns {Promise<boolean>} true when the client went away
825
+ */
826
+ async function readWorkBody(ctx) {
827
+ const r = await readBounded(ctx.creq, WORK_BODY_LIMIT);
828
+ if (r.aborted) return true;
829
+ ctx.chunks = r.chunks;
830
+ ctx.over = r.over;
831
+ return false;
832
+ }
833
+
834
+ /**
835
+ * Read a paused request's body until it ends or passes `limit` bytes
836
+ * (then pause again, keeping everything read so far in `chunks`).
837
+ *
838
+ * @param {import('node:http').IncomingMessage} creq paused request
839
+ * @param {number} limit byte limit
840
+ * @returns {Promise<{ chunks: Buffer[], over: boolean, aborted: boolean }>}
841
+ */
842
+ function readBounded(creq, limit) {
843
+ return new Promise((resolve) => {
844
+ /** @type {Buffer[]} */
845
+ const chunks = [];
846
+ let size = 0;
847
+ /** @param {boolean} over @param {boolean} aborted */
848
+ const done = (over, aborted) => {
849
+ creq.off('data', onData);
850
+ creq.off('end', onEnd);
851
+ creq.off('close', onGone);
852
+ creq.off('error', onGone);
853
+ resolve({ chunks, over, aborted });
854
+ };
855
+ const onData = (/** @type {Buffer} */ c) => {
423
856
  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
- });
857
+ size += c.length;
858
+ if (size > limit) { creq.pause(); done(true, false); }
859
+ };
860
+ const onEnd = () => done(false, false);
861
+ const onGone = () => done(false, true);
862
+ creq.on('data', onData);
863
+ creq.on('end', onEnd);
864
+ creq.on('close', onGone);
865
+ creq.on('error', onGone);
436
866
  creq.resume();
437
- };
438
- const slot = queue.reserve(agent, {
439
- onReady: readHeld,
440
- onExpire: (why) => { denyRes(cres, 403, `denied: ${why}`); creq.resume(); },
441
867
  });
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();
452
868
  }
453
869
  // Idle tunnels die here; a request in flight is never idle by definition.
454
870
  server.keepAliveTimeout = clientIdleMs;
@@ -503,7 +919,7 @@ export function createProxy(opts) {
503
919
  }
504
920
  // Deny the tunnel itself: no cert is minted for a walled destination,
505
921
  // and the inner request is checked again on arrival anyway.
506
- const verdict = await checkUpstream(host, gate);
922
+ const verdict = await checkUpstream(host, gate, portNum);
507
923
  if (!verdict.ok) {
508
924
  denyRaw(sock, 403, verdict.reason);
509
925
  return;
@@ -550,6 +966,7 @@ export function createProxy(opts) {
550
966
  });
551
967
  });
552
968
  bound = await boundP;
969
+ if (gateFor) void gateOf('tcp').catch(() => {});
553
970
  }
554
971
  return { port: bound };
555
972
  })();
@@ -561,6 +978,9 @@ export function createProxy(opts) {
561
978
  function addAgent(name) {
562
979
  const sockPath = runtimePaths(runtime).socket(name);
563
980
  if (agentServers.has(name)) return sockPath;
981
+ if (agentServers.size >= MAX_AGENTS) {
982
+ throw new Error(`createProxy: agent limit reached (${MAX_AGENTS} agents per proxy); run another proxy for more`);
983
+ }
564
984
  try { fs.unlinkSync(sockPath); } catch {}
565
985
  ensurePrivateDir(path.dirname(sockPath));
566
986
  const srv = net.createServer((sock) => {
@@ -572,6 +992,7 @@ export function createProxy(opts) {
572
992
  try { fs.chmodSync(sockPath, 0o600); } catch {}
573
993
  });
574
994
  agentServers.set(name, srv);
995
+ if (gateFor) void gateOf(name).catch(() => {});
575
996
  return sockPath;
576
997
  }
577
998
 
@@ -582,12 +1003,15 @@ export function createProxy(opts) {
582
1003
  const srv = agentServers.get(name);
583
1004
  if (!srv) return;
584
1005
  agentServers.delete(name);
1006
+ gates.delete(name);
585
1007
  srv.close();
586
1008
  for (const s of [...clients]) {
587
1009
  if (s[AGENT] !== name) continue;
588
1010
  holds?.abandonSocket(s);
589
1011
  s.destroy();
590
1012
  }
1013
+ // Asks still waiting in line (not parked) end now, as client gone, too.
1014
+ for (const c of inflightCtx.values()) if (c.agent === name) c.endAsk?.('client gone');
591
1015
  try { fs.unlinkSync(runtimePaths(runtime).socket(name)); } catch {}
592
1016
  }
593
1017
 
@@ -599,22 +1023,36 @@ export function createProxy(opts) {
599
1023
  // Parked holds settle as denied (guarded writes), timers cleared,
600
1024
  // ask files removed, sweeper stopped — all inside holds.close().
601
1025
  holds?.close();
1026
+ // Requests inside a gate check now end on their own (holds.close() refused
1027
+ // their asks, parked or waiting): wait for their 403 and last log lines BEFORE the
1028
+ // sockets go, but never forever (a wedged gate must not wedge close).
1029
+ const checking = [...inflightCtx.values()].map((c) => reqDone.get(c.creq)).filter(Boolean);
1030
+ if (checking.length) {
1031
+ /** @type {ReturnType<typeof setTimeout>|undefined} */
1032
+ let cap;
1033
+ await Promise.race([
1034
+ Promise.allSettled(checking),
1035
+ new Promise((resolve) => { cap = setTimeout(resolve, 3000); }),
1036
+ ]);
1037
+ clearTimeout(cap);
1038
+ }
602
1039
  for (const up of upstreams) { try { up.destroy(); } catch {} }
603
1040
  upstreams.clear();
604
1041
  for (const s of clients) { try { s.destroy(); } catch {} }
605
1042
  clients.clear();
606
1043
  server.close();
607
- logStream.end();
608
- /** @type {Promise<void>} */
609
- const flushed = new Promise((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
- }
616
- });
617
- await flushed;
1044
+ // Lines logged from here on are dropped; the ones in flight are awaited,
1045
+ // but never forever (a wedged disk must not wedge close).
1046
+ logClosing = true;
1047
+ if (pendingLog.size) {
1048
+ /** @type {ReturnType<typeof setTimeout>|undefined} */
1049
+ let cap;
1050
+ await Promise.race([
1051
+ Promise.allSettled([...pendingLog]),
1052
+ new Promise((resolve) => { cap = setTimeout(resolve, 3000); }),
1053
+ ]);
1054
+ clearTimeout(cap);
1055
+ }
618
1056
  releaseClaim();
619
1057
  }
620
1058