barebox 0.14.0 → 0.16.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
@@ -18,19 +18,34 @@ import https from 'node:https';
18
18
  import fs from 'node:fs';
19
19
  import path from 'node:path';
20
20
  import { ensureCA, certFor, HOST_RE } from './certs.js';
21
- import { createCardScanner } from './cardscan.js';
21
+ import { createCardScanner, maskCards } from './cardscan.js';
22
22
  import { ASK_BODY_LIMIT, DEFAULT_HOLD_MAX_BODY, bodyPreview, createHolds } from './holds.js';
23
23
  import { viewBody } from './bodyview.js';
24
24
  import { claimRuntime, ensurePrivateDir, runtimePaths } from './runtime.js';
25
- import { paymentPath, toolFor, buildTools, modelTools, modelList, emptyMatcher } from './policy.js';
25
+ import { paymentPath, toolFor, buildTools, modelTools, modelList, emptyMatcher, MODEL_HOSTS } from './policy.js';
26
26
  import { checkUpstream } from './wall.js';
27
- import { floorList } from './lists.js';
27
+ import { floorList, stripDot } from './lists.js';
28
28
  import { findEffect } from './effect.js';
29
29
  import { findPlaceholders, urlPlaceholders, applySecrets } from './secrets.js';
30
- import { Gate } from 'bareguard';
30
+ import { Gate, hostMatcher } from 'bareguard';
31
31
 
32
32
  const AGENT = Symbol('agent');
33
33
  const SECURE = Symbol('secure');
34
+
35
+ /** The URL a proxied request targets (absolute-form, else built from Host), or null when it has none. @param {import('node:http').IncomingMessage} creq */
36
+ function targetUrl(creq) {
37
+ const target = creq.url || '';
38
+ try {
39
+ if (/^https?:\/\//i.test(target)) return new URL(target);
40
+ const host = creq.headers.host;
41
+ if (!host) return null;
42
+ return new URL(`${/** @type {any} */ (creq.socket)[SECURE] === true ? 'https' : 'http'}://${host}${target}`);
43
+ } catch { return null; }
44
+ }
45
+ /** The url as the audit may show it: userinfo whole to `***`, then card numbers masked (a string with no scheme gets the card mask only). @param {string} url */
46
+ function maskUrl(url) {
47
+ return maskCards(url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@]*@/i, '$1***@'));
48
+ }
34
49
  const IP_RE = /^\d+\.\d+\.\d+\.\d+$/;
35
50
  // Hop-by-hop headers must not be forwarded: node's HTTP stack re-frames.
36
51
  const HOP_REQ = new Set(['proxy-connection', 'proxy-authorization']);
@@ -60,6 +75,7 @@ const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
60
75
  * @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
61
76
  * @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
62
77
  * @property {{ pay?: string[], send?: string[] }} [floor] the config `floor` key (M11): a write to a listed host or `*.domain`, or a request matching a listed `"METHOD host/path"`, asks in every mode (the gate flag `floor`); the question shows the recipient, amount and currency found in the body. Omitted means no floor lists.
78
+ * @property {{ allow?: string[], deny?: string[], unknown?: 'ask' | 'deny' | 'allow' }} [hosts] M14: `deny` hosts (exact or `*.domain`) are refused before DNS in every mode; `allow` hosts never get the first-contact ask; any other host follows `unknown`: `'ask'` asks once per host (allow for this run, or deny), `'deny'` refuses it at once, `'allow'` (the default here) lets it through. Model endpoint hosts, each secret's hosts and the `allowLocal` hosts are never asked. Needs `gateFor` for `'ask'`; without it `'ask'` refuses.
63
79
  * @property {HoldOptions} [hold] hold queue config (deadline, caps, ask seam)
64
80
  * @property {number} [upstreamTimeoutMs] give up on an upstream response after this (default 120000)
65
81
  * @property {object} [unsafeTestOnly] TEST-ONLY escape hatch: everything under
@@ -71,7 +87,7 @@ const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
71
87
  * DNS stub: replaces the wall's resolver so rebinding is testable. Production omits it.
72
88
  * @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.
73
89
  * @property {number} [clientIdleMs] kill a client tunnel idle this long; never fires mid-request (default 60000)
74
- * @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)
90
+ * @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, and the `url` it sees already has userinfo and card numbers masked (default: identity)
75
91
  */
76
92
 
77
93
  /**
@@ -116,7 +132,7 @@ const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
116
132
  */
117
133
 
118
134
  /**
119
- * 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
135
+ * 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); barebox's own audit lines mask userinfo and card numbers in the URL, the gate's decision lines keep it as sent; bytes go upstream untouched. Requests the hold rule
120
136
  * flags park for a human decision instead of forwarding.
121
137
  *
122
138
  * @param {ProxyOptions} opts
@@ -134,7 +150,7 @@ export function createProxy(opts) {
134
150
  upstreamCa = null, hold = null, gateFor = null, allowLocal = [], floor = null, labels = null,
135
151
  upstreamTimeoutMs = 120000, clientIdleMs = 60000,
136
152
  unsafeTestOnly = null, secrets = [],
137
- redact = (e) => e } = opts ?? {};
153
+ redact = (e) => e, hosts = {} } = opts ?? {};
138
154
  const { allowLoopback = false, resolveUpstream = null } = unsafeTestOnly ?? {};
139
155
  const gate = {
140
156
  allowLoopback, resolveUpstream: resolveUpstream ?? undefined,
@@ -150,6 +166,13 @@ export function createProxy(opts) {
150
166
  const builtinModels = modelTools(labels?.tools, []);
151
167
  const modelEndpoints = modelList([...allowLocal]);
152
168
  const floors = floorList(floor ?? {});
169
+ const hostDeny = hosts.deny?.length ? hostMatcher(hosts.deny) : null;
170
+ const hostAllow = hosts.allow?.length ? hostMatcher(hosts.allow) : null;
171
+ const hostUnknown = hosts.unknown ?? 'allow';
172
+ if (!['ask', 'deny', 'allow'].includes(hostUnknown)) throw new Error(`createProxy: hosts.unknown must be ask|deny|allow, got ${JSON.stringify(hostUnknown)}`);
173
+ // Never a first-contact ask (M14): the model endpoints, each secret's hosts and the local model servers.
174
+ const hostExempt = new Set([...MODEL_HOSTS, ...secrets.flatMap((x) => x.hosts.map((h) => h.toLowerCase())),
175
+ ...allowLocal.map((e) => String(e).toLowerCase().replace(/:\d+$/, ''))]);
153
176
  if (!logFile) throw new Error('createProxy: logFile is required');
154
177
  if (typeof runtime !== 'string' || !runtime) throw new Error('createProxy: runtime is required');
155
178
  // One live proxy per runtime, enforced here: claimed before the hold
@@ -226,8 +249,10 @@ export function createProxy(opts) {
226
249
  meta['reason'] = cut(meta['reason'], 200);
227
250
  return meta;
228
251
  };
229
- /** @param {Record<string, unknown>} o */
230
- async function writeLog(o) {
252
+ /** @param {Record<string, unknown>} o0 */
253
+ async function writeLog(o0) {
254
+ // One writer of the masked url: `where` and `meta` both read `o`.
255
+ const o = typeof o0['url'] === 'string' ? { ...o0, url: maskUrl(o0['url']) } : o0;
231
256
  const agent = typeof o['agent'] === 'string' ? o['agent'] : null;
232
257
  // Never build a gate from here: a built one, else the sbx gate.
233
258
  const entry = agent ? gates.get(agent) : undefined;
@@ -277,7 +302,9 @@ export function createProxy(opts) {
277
302
  // The one writer of a proxied HTTP error: logs it, answers it.
278
303
  function denyRes(cres, code, note) {
279
304
  const sock = cres.socket;
280
- log({ ev: 'deny', agent: agentOf(sock), code, note });
305
+ const req = cres.req;
306
+ const url = req ? (targetUrl(req)?.toString() ?? req.url) : undefined;
307
+ log({ ev: 'deny', agent: agentOf(sock), code, note, ...(req?.method ? { method: req.method } : {}), ...(url ? { url } : {}) });
281
308
  try {
282
309
  if (!cres.headersSent && !sock.destroyed) {
283
310
  cres.writeHead(code, { 'content-type': 'text/plain', connection: 'close' });
@@ -287,9 +314,10 @@ export function createProxy(opts) {
287
314
  }
288
315
 
289
316
  // Raw sockets: pre-HTTP (CONNECT line, oversized head, walled CONNECT, cert failure) and the
290
- // upgrade / inner CONNECT refusals below. `url` is the target, for the proxy log only.
291
- function denyRaw(sock, code, note, url) {
292
- log({ ev: 'deny', agent: agentOf(sock), code, note, ...(url ? { url } : {}) });
317
+ // upgrade / inner CONNECT refusals below. `url` and `method` are the target and method the proxy
318
+ // saw, for the proxy log only.
319
+ function denyRaw(sock, code, note, url, method) {
320
+ log({ ev: 'deny', agent: agentOf(sock), code, note, ...(url ? { url } : {}), ...(method ? { method } : {}) });
293
321
  if (sock.destroyed) return;
294
322
  try { sock.end(`HTTP/1.1 ${code} ${note}\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n${note}\n`); }
295
323
  catch {}
@@ -444,7 +472,7 @@ export function createProxy(opts) {
444
472
  // A parked request's pending ask ends here: handleRequest, awaiting
445
473
  // its gate, then forwards or refuses.
446
474
  onApprove: (h) => h.finish({ decision: 'allow' }),
447
- onDeny: (h, reason, answered) => h.finish({ decision: 'deny', reason, answered }),
475
+ onDeny: (h, reason, answered, timedOut) => h.finish({ decision: 'deny', reason, answered, timedOut }),
448
476
  }) : null;
449
477
  } catch (e) {
450
478
  releaseClaim();
@@ -500,6 +528,82 @@ export function createProxy(opts) {
500
528
  */
501
529
  const keyAsks = new Map();
502
530
 
531
+ /**
532
+ * M14: what a person decided about each host in this run, shared by every agent of the proxy.
533
+ * `rememberHost` is the one writer; the Map is gone with the proxy.
534
+ *
535
+ * @type {Map<string, 'allow'|'deny'>}
536
+ */
537
+ const runHosts = new Map();
538
+ /** @param {string} host @param {'allow'|'deny'} d */
539
+ const rememberHost = (host, d) => { runHosts.set(host, d); };
540
+ /** Hosts refused by `unknown: 'deny'` this run. @type {Set<string>} */
541
+ const refusedHosts = new Set();
542
+ /**
543
+ * M14: one open ask per unknown host; parallel requests wait on it instead of asking again. It settles with
544
+ * the leader's outcome: `'timeout'` (the hold timeout) denies the waiters at once, as M12's `settleKey`;
545
+ * any other value sends a waiter back to `hostDecision`.
546
+ *
547
+ * @type {Map<string, Promise<'allow'|'deny'|'timeout'|'none'>>}
548
+ */
549
+ const hostAsks = new Map();
550
+
551
+ /**
552
+ * M14: the one host decision, on the name alone (before any DNS). In order: the deny list, a
553
+ * person's earlier deny, the allow list / a person's earlier allow / an exempt host, then `unknown`.
554
+ * A host the matchers cannot check is refused (fail closed).
555
+ *
556
+ * @param {string} rawHost a request or CONNECT host name
557
+ * @returns {{ d: 'allow'|'deny'|'unknown', host: string, reason?: string, entry?: string }}
558
+ */
559
+ function hostDecision(rawHost) {
560
+ const host = stripDot(rawHost.toLowerCase());
561
+ try {
562
+ const entry = hostDeny?.match(host);
563
+ if (entry) return { d: 'deny', host, reason: 'denied: host', entry };
564
+ if (runHosts.get(host) === 'deny') return { d: 'deny', host, reason: 'denied: host' };
565
+ if (runHosts.get(host) === 'allow' || hostExempt.has(host) || hostAllow?.match(host)) return { d: 'allow', host };
566
+ } catch {
567
+ return { d: 'deny', host, reason: 'denied: host not checkable' };
568
+ }
569
+ if (hostUnknown === 'allow') return { d: 'allow', host };
570
+ if (hostUnknown === 'ask' && gateFor) return { d: 'unknown', host };
571
+ return { d: 'deny', host, reason: 'denied: host not in hosts.allow' };
572
+ }
573
+
574
+ /** M14: the audit line and run report for a host refused with no gate call. @param {string} agent @param {{ host: string, reason?: string, entry?: string }} hd */
575
+ function hostRefusal(agent, hd) {
576
+ if (hd.reason === 'denied: host not in hosts.allow') refusedHosts.add(hd.host);
577
+ log({ ev: 'host', agent, host: hd.host, decision: 'deny', reason: hd.reason, ...(hd.entry ? { entry: hd.entry } : {}) });
578
+ }
579
+
580
+ /**
581
+ * M14: the first request to a host nobody decided yet asks the person (the `newHost` flag on a
582
+ * `net.host` action, run on this agent's own gate). The body stays unread. A person's answer is
583
+ * remembered for the run; a hold timeout, a cancel, a close or a failure is not.
584
+ *
585
+ * @param {import('node:http').ServerResponse} cres @param {string} agent @param {string} method @param {string} urlStr @param {string} host
586
+ * @param {import('node:http').IncomingMessage} creq
587
+ * @returns {Promise<{ outcome: string, reason?: string|null, rule?: string, asked: boolean, status: number|null, timedOut: boolean }>}
588
+ */
589
+ async function askHost(creq, cres, agent, method, urlStr, host) {
590
+ const rid = `r${++ridN}`;
591
+ /** @type {RequestCtx} */
592
+ const ctx = { agent, method, url: urlStr, headers: { ...creq.headers }, creq, cres, tee: makeTee(),
593
+ hasBody: false, chunks: [], over: false, freeWork: () => {}, asked: false, status: null, heldId: null,
594
+ endAsk: null, decodedHead: null, effect: null, keyLast4: '', modelKey: '', askRule: null, answered: false, timedOut: false };
595
+ inflightCtx.set(rid, ctx);
596
+ try {
597
+ const g = await gateOf(agent);
598
+ const d = await decideAction(g, { type: 'net', tool: 'net.host', url: urlStr, method, agent, rid, newHost: true });
599
+ if (d.outcome === 'allow') rememberHost(host, 'allow');
600
+ else if (ctx.asked && ctx.answered && !ctx.timedOut) rememberHost(host, 'deny');
601
+ return { ...d, asked: ctx.asked, status: ctx.status, timedOut: ctx.timedOut };
602
+ } finally {
603
+ inflightCtx.delete(rid);
604
+ }
605
+ }
606
+
503
607
  /**
504
608
  * The model key of a header: `x-api-key`, or `Authorization` without a leading `Bearer `.
505
609
  * @param {Record<string, string | string[] | undefined>} headers @param {string} name @returns {string}
@@ -564,6 +668,7 @@ export function createProxy(opts) {
564
668
  * @property {string} keyLast4 last 4 characters of a model key that is not this run's ('' when none): shown in the ask, never the key
565
669
  * @property {string|null} askRule the rule the human channel was asked about (null: not asked)
566
670
  * @property {boolean} answered a person's answer or the hold timeout ended the ask (set by the hold's `finish`); false for a cancel, a close or a failure
671
+ * @property {boolean} timedOut the hold timeout ended the ask (so `answered && !timedOut` is a person's answer)
567
672
  * @property {import('./effect.js').Effect|null} effect the recipient/amount/currency fields found in the body of a floor request (ask file only, never the audit); null when there is none
568
673
  */
569
674
 
@@ -603,20 +708,21 @@ export function createProxy(opts) {
603
708
  let dead = false;
604
709
  /** @type {import('node:fs').WriteStream|null} */
605
710
  let ws = null;
606
- /** @param {{ decision: 'allow' | 'deny', reason?: string, answered?: boolean }} d */
711
+ /** @param {{ decision: 'allow' | 'deny', reason?: string, answered?: boolean, timedOut?: boolean }} d */
607
712
  const finish = (d) => {
608
713
  if (settled) return;
609
714
  settled = true;
610
715
  ctx.endAsk = null;
611
- const { answered, ...rest } = d; // the one place `answered` is set: present only when true
716
+ const { answered, timedOut, ...rest } = d; // the one place `answered` and `timedOut` are set: present only when true
612
717
  ctx.answered = answered === true;
718
+ ctx.timedOut = timedOut === true;
613
719
  resolve(ctx.answered ? d : rest);
614
720
  };
615
- /** @param {string} reason @param {number} [status] @param {boolean} [answered] the hold timeout ended it */
616
- const refuse = (reason, status, answered) => {
721
+ /** @param {string} reason @param {number} [status] @param {boolean} [answered] the hold timeout ended it @param {boolean} [timedOut] */
722
+ const refuse = (reason, status, answered, timedOut) => {
617
723
  if (settled) return; // a late failure must not rewrite the settled deny's status
618
724
  if (status) ctx.status = status;
619
- finish({ decision: 'deny', reason, answered });
725
+ finish({ decision: 'deny', reason, answered, timedOut });
620
726
  };
621
727
  const abort = () => {
622
728
  if (dead) return;
@@ -635,7 +741,7 @@ export function createProxy(opts) {
635
741
  if (!sock || sock.destroyed) { refuse('client gone'); return; }
636
742
  const slot = queue.reserve(agent, {
637
743
  onReady: () => stream(),
638
- onExpire: (why, answered) => { abort(); refuse(why, undefined, answered); },
744
+ onExpire: (why, answered, timedOut) => { abort(); refuse(why, undefined, answered, timedOut); },
639
745
  });
640
746
  if (slot.state === 'full') { ctx.freeWork(); refuse('hold queue full', 429); return; }
641
747
  ctx.endAsk = (why) => fail(why);
@@ -720,26 +826,11 @@ export function createProxy(opts) {
720
826
  async function handleRequest(creq, cres) {
721
827
  const sock = creq.socket;
722
828
  const agent = agentOf(sock);
723
- const secure = sock[SECURE] === true;
724
- const target = creq.url || '';
725
- let url;
726
- try {
727
- if (/^https?:\/\//i.test(target)) url = new URL(target);
728
- else {
729
- const host = creq.headers.host;
730
- if (!host) throw new Error('no host');
731
- url = new URL(`${secure ? 'https' : 'http'}://${host}${target}`);
732
- }
733
- } catch { denyRes(cres, 400, 'bad request target'); return; }
829
+ const url = targetUrl(creq);
830
+ if (!url) { denyRes(cres, 400, 'bad request target'); return; }
734
831
  const method = creq.method;
735
832
  if (!method) { denyRes(cres, 400, 'bad request method'); return; }
736
833
  const urlStr = url.toString();
737
- const verdict = await checkUpstream(url.hostname, gate, portOf(url));
738
- if (!verdict.ok) {
739
- try { creq.resume(); } catch {}
740
- denyRes(cres, 403, verdict.reason);
741
- return;
742
- }
743
834
  // The request's one id: the audit lines of its secret swap, its body and
744
835
  // its gate decision all carry it.
745
836
  const rid = `r${++ridN}`;
@@ -772,6 +863,69 @@ export function createProxy(opts) {
772
863
  denyRes(cres, 403, 'denied: secret.url');
773
864
  return;
774
865
  }
866
+ // The secret refusals above need only the host name. Pause before the host decision and the
867
+ // wall: neither may lose body bytes while they wait.
868
+ creq.pause();
869
+ // M14: the host decision comes before any DNS (`checkUpstream`).
870
+ let hd = hostDecision(url.hostname);
871
+ while (hd.d === 'unknown') {
872
+ const open = hostAsks.get(hd.host);
873
+ if (open) {
874
+ // Wait for the open ask on this host; hold a place among the agent's waiters while we do.
875
+ const release = holds ? holds.wait(agent) : () => {};
876
+ if (!release) {
877
+ discard(creq);
878
+ denyRes(cres, 429, 'denied: hold queue full');
879
+ return;
880
+ }
881
+ /** @type {() => void} */
882
+ let onGone = () => {};
883
+ const gone = new Promise((r) => { onGone = () => r('gone'); cres.once('close', onGone); });
884
+ const r = await Promise.race([open, gone]);
885
+ cres.off('close', onGone);
886
+ release();
887
+ if (r === 'gone') { discard(creq); return; }
888
+ if (r === 'timeout') {
889
+ // The hold timeout denies every waiter at once; nothing is remembered, so the next new request asks again.
890
+ discard(creq);
891
+ denyRes(cres, 403, 'denied: hold timeout');
892
+ return;
893
+ }
894
+ hd = hostDecision(url.hostname);
895
+ continue;
896
+ }
897
+ /** @type {(r: 'allow'|'deny'|'timeout'|'none') => void} */
898
+ let endAsk = () => {};
899
+ hostAsks.set(hd.host, new Promise((r) => { endAsk = r; }));
900
+ let d;
901
+ let settled = /** @type {'allow'|'deny'|'timeout'|'none'} */ ('none');
902
+ try {
903
+ d = await askHost(creq, cres, agent, method, urlStr, hd.host);
904
+ // A person's answer is remembered, so the waiters re-decide; the hold timeout denies them. A cancel or a close settles 'deny' without remembering, and a failure leaves 'none'; either way the waiters re-decide, find the host still unknown, and the next one asks.
905
+ settled = d.timedOut ? 'timeout' : d.outcome === 'allow' ? 'allow' : 'deny';
906
+ } finally {
907
+ hostAsks.delete(hd.host);
908
+ endAsk(settled);
909
+ }
910
+ if (d.outcome !== 'allow') {
911
+ discard(creq);
912
+ denyRes(cres, d.status ?? 403, d.asked ? `denied: ${d.reason ?? 'denied'}` : `denied: ${d.rule ?? 'gate'}${d.reason ? `: ${d.reason}` : ''}`);
913
+ return;
914
+ }
915
+ hd = hostDecision(url.hostname);
916
+ }
917
+ if (hd.d === 'deny') {
918
+ hostRefusal(agent, hd);
919
+ discard(creq);
920
+ denyRes(cres, 403, /** @type {string} */ (hd.reason));
921
+ return;
922
+ }
923
+ const verdict = await checkUpstream(url.hostname, gate, portOf(url));
924
+ if (!verdict.ok) {
925
+ try { creq.resume(); } catch {}
926
+ denyRes(cres, 403, verdict.reason);
927
+ return;
928
+ }
775
929
  /** The headers to forward: the real values in, one audit line per swap. @param {Record<string, string | string[] | undefined>} headers */
776
930
  const withSecrets = (headers) => {
777
931
  if (!found.length) return headers;
@@ -785,7 +939,6 @@ export function createProxy(opts) {
785
939
  // flowing mode and starve whoever reads it next. The tee sees every body
786
940
  // byte once, whatever path reads it, and feeds the ask (a masked
787
941
  // 4 KB preview) and the audit's `body` fact (byte count and SHA-256).
788
- creq.pause();
789
942
  const tee = makeTee();
790
943
  creq.on('data', (c) => tee.push(c));
791
944
  // `end` fires once the whole body was read, whichever path read it (also
@@ -870,7 +1023,7 @@ export function createProxy(opts) {
870
1023
  /** @type {RequestCtx} */
871
1024
  const ctx = { agent, method, url: urlStr, headers: { ...creq.headers }, creq, cres, tee,
872
1025
  hasBody, chunks: [], over: false, freeWork, asked: false, status: null, heldId: null,
873
- endAsk: null, decodedHead: null, effect: null, keyLast4: unknownKey?.last4 ?? '', modelKey: unknownKey ? (unknownKey.hash ? 'other' : 'none') : '', askRule: null, answered: false };
1026
+ endAsk: null, decodedHead: null, effect: null, keyLast4: unknownKey?.last4 ?? '', modelKey: unknownKey ? (unknownKey.hash ? 'other' : 'none') : '', askRule: null, answered: false, timedOut: false };
874
1027
  let cardLike = false;
875
1028
  if (hasBody) {
876
1029
  if (await readWorkBody(ctx)) return;
@@ -1052,10 +1205,9 @@ export function createProxy(opts) {
1052
1205
  // listeners node would forward the upgrade as a GET, or close the socket with no reason.
1053
1206
  server.on('upgrade', (creq, sock) => {
1054
1207
  const t = creq.url || '';
1055
- const host = creq.headers.host ?? '';
1056
- denyRaw(sock, 403, 'denied: upgrade', /^https?:\/\//i.test(t) ? t : `${sock[SECURE] === true ? 'https' : 'http'}://${host}${t}`);
1208
+ denyRaw(sock, 403, 'denied: upgrade', targetUrl(creq)?.toString() ?? t, creq.method);
1057
1209
  });
1058
- server.on('connect', (creq, sock) => { denyRaw(sock, 403, 'denied: connect', creq.url || ''); });
1210
+ server.on('connect', (creq, sock) => { denyRaw(sock, 403, 'denied: connect', creq.url || '', 'CONNECT'); });
1059
1211
 
1060
1212
  // Dispatch: one CONNECT line, or plain HTTP straight into the same server.
1061
1213
  function admit(sock, agent) {
@@ -1102,16 +1254,26 @@ export function createProxy(opts) {
1102
1254
  const [host, portStr] = String(target || '').split(':');
1103
1255
  const portNum = portStr ? parseInt(portStr, 10) : 443;
1104
1256
  if (!HOST_RE.test(host || '') || !Number.isFinite(portNum) || portNum < 1 || portNum > 65535) {
1105
- denyRaw(sock, 400, 'bad connect line');
1257
+ denyRaw(sock, 400, 'bad connect line', target, 'CONNECT');
1106
1258
  return;
1107
1259
  }
1108
1260
  // Deny the tunnel itself: no cert is minted for a walled destination,
1109
1261
  // and the inner request is checked again on arrival anyway.
1110
- const verdict = await checkUpstream(host, gate, portNum);
1111
- if (!verdict.ok) {
1112
- denyRaw(sock, 403, verdict.reason);
1262
+ // M14: the host decision first. A host nobody decided opens its tunnel with no DNS: the first
1263
+ // request inside it asks (`handleRequest`), and `forward` resolves only after the allow.
1264
+ const hd = hostDecision(host);
1265
+ if (hd.d === 'deny') {
1266
+ hostRefusal(agentOf(sock), hd);
1267
+ denyRaw(sock, 403, /** @type {string} */ (hd.reason), target, 'CONNECT');
1113
1268
  return;
1114
1269
  }
1270
+ if (hd.d === 'allow') {
1271
+ const verdict = await checkUpstream(host, gate, portNum);
1272
+ if (!verdict.ok) {
1273
+ denyRaw(sock, 403, verdict.reason, target, 'CONNECT');
1274
+ return;
1275
+ }
1276
+ }
1115
1277
  if (closed || sock.destroyed) return;
1116
1278
  try { sock.write('HTTP/1.1 200 Connection established\r\n\r\n'); }
1117
1279
  catch { return; }
@@ -1279,6 +1441,8 @@ export function createProxy(opts) {
1279
1441
  addAgent,
1280
1442
  removeAgent,
1281
1443
  pending: () => (holds ? holds.pending() : []),
1444
+ /** M14: hosts a person allowed this run, and hosts refused by `unknown: 'deny'`; each sorted and unique. @returns {{ allowed: string[], refused: string[] }} */
1445
+ hostsReport: () => ({ allowed: [...runHosts].filter(([, d]) => d === 'allow').map(([h]) => h).sort(), refused: [...refusedHosts].sort() }),
1282
1446
  get caFile() { return path.join(certDir, 'ca.pem'); },
1283
1447
  };
1284
1448
  }
package/src/run.js CHANGED
@@ -66,6 +66,7 @@ import { loadSecrets } from './secrets.js';
66
66
  * @property {{ matcher: any, tools: Record<string, any>, dirs?: string[] }} [labels] the loaded label files (`loadLabels`); their folders are masked from the sandbox
67
67
  * @property {string[]} [allowLocal] exact `host:port` pairs (for example a local model server) that may pass the wall's private/loopback check (the `localLlm` setting)
68
68
  * @property {{ pay?: string[], send?: string[] }} [floor] the config `floor` key (M11): hosts, `*.domain` or `"METHOD host/path"` entries that ask in every mode, `trust` included (see `createProxy`)
69
+ * @property {{ allow?: string[], deny?: string[], unknown?: 'ask'|'deny' }} [hosts] the config `hosts` key (M14): `deny` hosts are refused before DNS in every mode; `allow` hosts never get the first-contact ask; any other host asks once (`unknown` `ask`, the default) or is refused (`deny`). `trust` lets other hosts through, a `deny` host still refused (see `createProxy`)
69
70
  * @property {object} [unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`): everything under it weakens the sandbox wall
70
71
  * @property {NodeJS.WritableStream} [stdout] where the agent's stdout goes (default process.stdout)
71
72
  * @property {NodeJS.WritableStream} [stderr] where the agent's stderr goes (default process.stderr)
@@ -91,6 +92,7 @@ import { loadSecrets } from './secrets.js';
91
92
  * @param {{ matcher: any, tools: Record<string, any>, dirs?: string[] }|null} [opts.labels] the loaded label files (`loadLabels`); their folders are masked from the sandbox
92
93
  * @param {string[]} [opts.allowLocal] exact `host:port` pairs (for example a local model server) that may pass the wall's private/loopback check (the `localLlm` setting)
93
94
  * @param {{ pay?: string[], send?: string[] }|null} [opts.floor] the config `floor` key (M11): hosts, `*.domain` or `"METHOD host/path"` entries that ask in every mode, `trust` included (see `createProxy`)
95
+ * @param {{ allow?: string[], deny?: string[], unknown?: 'ask'|'deny' }|null} [opts.hosts] the config `hosts` key (M14); see {@link RunOptions}
94
96
  * @param {object|null} [opts.unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`)
95
97
  * @param {NodeJS.WritableStream|null} [opts.stdout] where the agent's stdout goes (default process.stdout)
96
98
  * @param {NodeJS.WritableStream|null} [opts.stderr] where the agent's stderr goes (default process.stderr)
@@ -98,7 +100,7 @@ import { loadSecrets } from './secrets.js';
98
100
  * @param {{ pass?: string[], set?: Record<string, string> }|null} [opts.env] the sandbox's environment (M5), the config `env` shape; see {@link RunOptions}
99
101
  * @param {boolean} [opts.overlay] when true, mount a per-run overlay upper over the project instead of binding it read-only; the result's `diff` lists the run's changes for commit/rollback
100
102
  * @param {string[]} [opts.overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
101
- * @returns {Promise<{ exit: number, asks: AskRecord[], audit: string, diff: import('./overlay.js').OverlayChange[], runtime: string }>} the agent process exit code, the collected ask records, the JSONL audit log path, the run's overlay diff (M4), and the runtime dir addressing it
103
+ * @returns {Promise<{ exit: number, asks: AskRecord[], audit: string, diff: import('./overlay.js').OverlayChange[], runtime: string, hosts: { allowed: string[], refused: string[] } }>} the agent process exit code, the collected ask records, the JSONL audit log path, the run's overlay diff (M4), the runtime dir addressing it, and the hosts a person allowed or `unknown: 'deny'` refused (M14)
102
104
  * @when Reach for this to HARNESS-ONLY run one sandboxed agent start-to-finish in a single call: it starts the proxy, sandboxes the command, answers holds, and returns the exit code with the ask and audit trail (plus the overlay diff once M4 exists).
103
105
  * @fails Rejects on a missing/unreadable `proj`, an empty `command`, a bad `mode`, a misshapen `onAsk`, a `secrets` entry with no value (a `fromEnv` variable missing from this process's environment; the message names the secret, never a value), a proxy that never becomes ready, a `launch` that throws (uncommitted overlay changes, a runtime inside the project — the proxy is closed first), or an overlay diff that cannot be read. The agent's own nonzero exit is returned as `exit`, never thrown.
104
106
  * @example
@@ -107,7 +109,7 @@ import { loadSecrets } from './secrets.js';
107
109
  */
108
110
  export async function run({ proj, command, mode = 'auto', onAsk = null,
109
111
  onEvent = null, runtime = null, agent = 'agent', timeoutMs, heldBodyMaxBytes,
110
- allowLocal = [], floor = null, labels = null, unsafeTestOnly = null, stdout = null, stderr = null,
112
+ allowLocal = [], floor = null, hosts = null, labels = null, unsafeTestOnly = null, stdout = null, stderr = null,
111
113
  overlay = false, overlayIgnore, secrets = null, env = null }) {
112
114
  if (typeof proj !== 'string' || !proj) throw new Error('run: proj must be a non-empty string');
113
115
  if (!fs.existsSync(proj)) throw new Error(`run: proj does not exist: ${proj}`);
@@ -145,7 +147,9 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
145
147
  : recordEvent;
146
148
 
147
149
  const proxy = createProxy({
148
- runtime: rt, logFile: audit, allowLocal, ...(floor ? { floor } : {}), unsafeTestOnly, secrets: loaded,
150
+ runtime: rt, logFile: audit, allowLocal, ...(floor ? { floor } : {}),
151
+ hosts: { allow: hosts?.allow, deny: hosts?.deny, unknown: mode === 'trust' ? 'allow' : (hosts?.unknown ?? 'ask') },
152
+ unsafeTestOnly, secrets: loaded,
149
153
  ...(labels ? { labels } : {}),
150
154
  gateFor: (name, { humanChannel, tools }) => gateFor({ agent: name, mode, auditPath: audit, humanChannel, tools }),
151
155
  hold: { onAsk, timeoutMs, maxBody: heldBodyMaxBytes, onEvent: holdOnEvent },
@@ -164,6 +168,7 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
164
168
  // sockets keep this process alive forever.
165
169
  /** @type {number} */
166
170
  let exit;
171
+ let hostsSeen = { allowed: /** @type {string[]} */ ([]), refused: /** @type {string[]} */ ([]) };
167
172
  try {
168
173
  sock = proxy.addAgent(agent);
169
174
  const child = launch({
@@ -184,6 +189,7 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
184
189
  // The sandbox is gone: end the agent's holds as client gone now, not
185
190
  // as 'proxy closing' if close() beats the sockets' async 'close'.
186
191
  if (sock) proxy.removeAgent(agent);
192
+ hostsSeen = proxy.hostsReport();
187
193
  await proxy.close();
188
194
  }
189
195
  // M2.5 item 4: the result carries the M4 diff. Without overlay there is no
@@ -199,5 +205,5 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
199
205
  throw new Error(`run: overlay diff failed after exit ${exit}: ${err.message}`);
200
206
  }
201
207
  }
202
- return { exit, asks: [...seen.values()], audit, diff, runtime: rt };
208
+ return { exit, asks: [...seen.values()], audit, diff, runtime: rt, hosts: hostsSeen };
203
209
  }
package/types/config.d.ts CHANGED
@@ -5,48 +5,42 @@
5
5
  * @returns {string} absolute path of `config.json`
6
6
  */
7
7
  export function configPath(env?: NodeJS.ProcessEnv): string;
8
+ /**
9
+ * @typedef {{ mode: string, holdTimeoutSec?: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, floor?: { pay?: string[], send?: string[] }, hosts?: { allow?: string[], deny?: string[], unknown?: 'ask'|'deny' }, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} Settings the effective settings of one run (`heldBodyMaxMB` absent means the library default)
10
+ */
8
11
  /**
9
12
  * Read the config file over the defaults. No file means defaults.
10
13
  *
11
14
  * @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
12
- * @returns {{ mode: string, holdTimeoutSec?: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, floor?: { pay?: string[], send?: string[] }, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
15
+ * @returns {Settings & { profiles?: Record<string, Partial<Pick<Settings, 'mode'|'hosts'|'secrets'>>> }} the file's settings over the defaults
13
16
  * @throws {Error} naming the file (and the key) on invalid JSON, an unknown key or a bad value
14
17
  */
15
- export function loadConfig(env?: NodeJS.ProcessEnv): {
16
- mode: string;
17
- holdTimeoutSec?: number | string;
18
- localLlm: string[];
19
- labels: string[];
20
- tenants: Record<string, string[]>;
21
- heldBodyMaxMB?: number;
22
- floor?: {
23
- pay?: string[];
24
- send?: string[];
25
- };
26
- env?: {
27
- pass?: string[];
28
- set?: Record<string, string>;
29
- };
30
- secrets?: Record<string, {
31
- fromEnv?: string;
32
- value?: string;
33
- hosts: string[];
34
- }>;
18
+ export function loadConfig(env?: NodeJS.ProcessEnv): Settings & {
19
+ profiles?: Record<string, Partial<Pick<Settings, "mode" | "hosts" | "secrets">>>;
35
20
  };
36
21
  /**
37
22
  * Settings for one `sbx run`: a CLI flag beats the file, the file beats the default.
23
+ * With `flags.profile`, that profile is laid over the top level first: `mode`,
24
+ * `hosts.allow`, `hosts.unknown` and `secrets` are replaced when the profile
25
+ * sets them, `hosts.deny` is the union. The result has no `profiles` key.
38
26
  *
39
27
  * @param {object} [flags] values given on the command line
40
28
  * @param {string} [flags.mode] `--mode`
29
+ * @param {string} [flags.profile] `--profile`: a name under `profiles`
41
30
  * @param {string} [flags.hold] `--hold` (`"never"` or a positive integer of seconds, as typed)
42
31
  * @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
43
- * @returns {{ mode: string, holdTimeoutSec?: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, floor?: { pay?: string[], send?: string[] }, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
32
+ * @returns {Settings} effective settings, no `profiles` key
44
33
  * @throws {Error} as {@link loadConfig}
45
34
  */
46
35
  export function resolveConfig(flags?: {
47
36
  mode?: string | undefined;
37
+ profile?: string | undefined;
48
38
  hold?: string | undefined;
49
- }, env?: NodeJS.ProcessEnv): {
39
+ }, env?: NodeJS.ProcessEnv): Settings;
40
+ /**
41
+ * the effective settings of one run (`heldBodyMaxMB` absent means the library default)
42
+ */
43
+ export type Settings = {
50
44
  mode: string;
51
45
  holdTimeoutSec?: number | string;
52
46
  localLlm: string[];
@@ -57,6 +51,11 @@ export function resolveConfig(flags?: {
57
51
  pay?: string[];
58
52
  send?: string[];
59
53
  };
54
+ hosts?: {
55
+ allow?: string[];
56
+ deny?: string[];
57
+ unknown?: "ask" | "deny";
58
+ };
60
59
  env?: {
61
60
  pass?: string[];
62
61
  set?: Record<string, string>;
package/types/holds.d.ts CHANGED
@@ -110,8 +110,8 @@ export function normalizeDecision(input: {
110
110
  * @param {number} [opts.pollMs] answer poll interval in ms for the default file checkpoint (default 250, PRD Q9)
111
111
  * @param {OnEvent|null} [opts.onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon
112
112
  * @param {(entry: object) => void} opts.onApprove forward the parked request upstream
113
- * @param {(entry: object, reason: string, answered: boolean) => void} opts.onDeny refuse the parked request; `answered`: a person's answer or the hold timeout ended it (not a cancel, a close or a channel failure)
114
- * @returns {{ add: (entry: object) => string|null, dropBody: (id: string) => void, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string, answered?: boolean) => void }) => { state: 'now'|'queued'|'full', id: string, arrivedAt: number, cancel: () => void }, abandon: (id: string) => void, abandonSocket: (sock: object) => void, wait: (agent: string) => (() => void)|null, pending: () => HeldRequest[], close: () => void }} queue handle
113
+ * @param {(entry: object, reason: string, answered: boolean, timedOut: boolean) => void} opts.onDeny refuse the parked request; `answered`: a person's answer or the hold timeout ended it (not a cancel, a close or a channel failure); `timedOut`: the hold timeout ended it (so `answered && !timedOut` is a person's answer)
114
+ * @returns {{ add: (entry: object) => string|null, dropBody: (id: string) => void, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string, answered?: boolean, timedOut?: boolean) => void }) => { state: 'now'|'queued'|'full', id: string, arrivedAt: number, cancel: () => void }, abandon: (id: string) => void, abandonSocket: (sock: object) => void, wait: (agent: string) => (() => void)|null, pending: () => HeldRequest[], close: () => void }} queue handle
115
115
  */
116
116
  export function createHolds({ log, timeoutMs, maxBody, runtime, onAsk, pollMs, onEvent, onApprove, onDeny }: {
117
117
  log: (o: Record<string, unknown>) => void;
@@ -122,13 +122,13 @@ export function createHolds({ log, timeoutMs, maxBody, runtime, onAsk, pollMs, o
122
122
  pollMs?: number | undefined;
123
123
  onEvent?: OnEvent | null | undefined;
124
124
  onApprove: (entry: object) => void;
125
- onDeny: (entry: object, reason: string, answered: boolean) => void;
125
+ onDeny: (entry: object, reason: string, answered: boolean, timedOut: boolean) => void;
126
126
  }): {
127
127
  add: (entry: object) => string | null;
128
128
  dropBody: (id: string) => void;
129
129
  reserve: (agent: string, cbs: {
130
130
  onReady: () => void;
131
- onExpire: (reason: string, answered?: boolean) => void;
131
+ onExpire: (reason: string, answered?: boolean, timedOut?: boolean) => void;
132
132
  }) => {
133
133
  state: "now" | "queued" | "full";
134
134
  id: string;
package/types/lists.d.ts CHANGED
@@ -35,5 +35,6 @@ export function floorList({ pay, send }?: {
35
35
  entry: string;
36
36
  } | null;
37
37
  };
38
+ export function stripDot(host: string): string;
38
39
  export function isEndpoint(e: unknown): boolean;
39
40
  import { matcherFrom } from 'rwxmap/match';
package/types/policy.d.ts CHANGED
@@ -78,6 +78,8 @@ export function gateFor({ agent, mode, auditPath, humanChannel, tools }: {
78
78
  }): Promise<Gate>;
79
79
  /** The mode names, in the order the CLI and config list them. */
80
80
  export const MODES: string[];
81
+ /** Hosts of the built-in model endpoints: never a first-contact host ask (M14). */
82
+ export const MODEL_HOSTS: Set<string>;
81
83
  /** The matcher used when no label files are loaded: every request is request-only. */
82
84
  export const emptyMatcher: {
83
85
  match: (method: string, url: string) => import("rwxmap/match").MatchResult;