barebox 0.12.0 → 0.14.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
@@ -24,6 +24,8 @@ import { viewBody } from './bodyview.js';
24
24
  import { claimRuntime, ensurePrivateDir, runtimePaths } from './runtime.js';
25
25
  import { paymentPath, toolFor, buildTools, modelTools, modelList, emptyMatcher } from './policy.js';
26
26
  import { checkUpstream } from './wall.js';
27
+ import { floorList } from './lists.js';
28
+ import { findEffect } from './effect.js';
27
29
  import { findPlaceholders, urlPlaceholders, applySecrets } from './secrets.js';
28
30
  import { Gate } from 'bareguard';
29
31
 
@@ -41,6 +43,8 @@ const MAX_AGENTS = 40;
41
43
  // Agents that browse many hosts must not grow the proxy without limit: one TLS context per host, at most this many.
42
44
  const MAX_MITM_CONTEXTS = 256;
43
45
  const EMPTY = Buffer.alloc(0);
46
+ /** The request headers that carry a model API key (M12). */
47
+ const KEY_HEADERS = ['x-api-key', 'authorization'];
44
48
  const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
45
49
  'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade']);
46
50
 
@@ -55,6 +59,7 @@ const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
55
59
  * @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.
56
60
  * @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
57
61
  * @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
+ * @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.
58
63
  * @property {HoldOptions} [hold] hold queue config (deadline, caps, ask seam)
59
64
  * @property {number} [upstreamTimeoutMs] give up on an upstream response after this (default 120000)
60
65
  * @property {object} [unsafeTestOnly] TEST-ONLY escape hatch: everything under
@@ -126,7 +131,7 @@ const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
126
131
  */
127
132
  export function createProxy(opts) {
128
133
  const { logFile, runtime, port = null,
129
- upstreamCa = null, hold = null, gateFor = null, allowLocal = [], labels = null,
134
+ upstreamCa = null, hold = null, gateFor = null, allowLocal = [], floor = null, labels = null,
130
135
  upstreamTimeoutMs = 120000, clientIdleMs = 60000,
131
136
  unsafeTestOnly = null, secrets = [],
132
137
  redact = (e) => e } = opts ?? {};
@@ -141,7 +146,10 @@ export function createProxy(opts) {
141
146
  const matcher = labels?.matcher ?? emptyMatcher;
142
147
  const tools = buildTools(labels?.tools, [...allowLocal]);
143
148
  const models = modelTools(labels?.tools, [...allowLocal]);
149
+ // The built-in endpoints only: a `localLlm` server is free without a key check (M12).
150
+ const builtinModels = modelTools(labels?.tools, []);
144
151
  const modelEndpoints = modelList([...allowLocal]);
152
+ const floors = floorList(floor ?? {});
145
153
  if (!logFile) throw new Error('createProxy: logFile is required');
146
154
  if (typeof runtime !== 'string' || !runtime) throw new Error('createProxy: runtime is required');
147
155
  // One live proxy per runtime, enforced here: claimed before the hold
@@ -278,9 +286,10 @@ export function createProxy(opts) {
278
286
  } catch {}
279
287
  }
280
288
 
281
- // Pre-HTTP raw sockets only (CONNECT line, oversized head, walled CONNECT, cert failure).
282
- function denyRaw(sock, code, note) {
283
- log({ ev: 'deny', agent: agentOf(sock), code, note });
289
+ // 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 } : {}) });
284
293
  if (sock.destroyed) return;
285
294
  try { sock.end(`HTTP/1.1 ${code} ${note}\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n${note}\n`); }
286
295
  catch {}
@@ -435,7 +444,7 @@ export function createProxy(opts) {
435
444
  // A parked request's pending ask ends here: handleRequest, awaiting
436
445
  // its gate, then forwards or refuses.
437
446
  onApprove: (h) => h.finish({ decision: 'allow' }),
438
- onDeny: (h, reason) => h.finish({ decision: 'deny', reason }),
447
+ onDeny: (h, reason, answered) => h.finish({ decision: 'deny', reason, answered }),
439
448
  }) : null;
440
449
  } catch (e) {
441
450
  releaseClaim();
@@ -475,6 +484,53 @@ export function createProxy(opts) {
475
484
  return e.p;
476
485
  }
477
486
 
487
+ /**
488
+ * M12: SHA-256 of the model keys a human allowed in this run. `rememberKey` is the one writer; it
489
+ * lives with the proxy, so it is gone with it. A key's bytes are never kept, logged or asked.
490
+ *
491
+ * @type {Set<string>}
492
+ */
493
+ const allowedKeys = new Set();
494
+ /** @param {string} hash */
495
+ const rememberKey = (hash) => { allowedKeys.add(hash); };
496
+ /**
497
+ * M12: one open ask per unknown key. Parallel calls with that key wait on it instead of asking again.
498
+ *
499
+ * @type {Map<string, Promise<'allow'|'deny'|'none'>>}
500
+ */
501
+ const keyAsks = new Map();
502
+
503
+ /**
504
+ * The model key of a header: `x-api-key`, or `Authorization` without a leading `Bearer `.
505
+ * @param {Record<string, string | string[] | undefined>} headers @param {string} name @returns {string}
506
+ */
507
+ function keyIn(headers, name) {
508
+ const v = headers[name];
509
+ const raw = String((Array.isArray(v) ? v[0] : v) ?? '');
510
+ return (name === 'authorization' ? raw.replace(/^Bearer\s+/i, '') : raw).trim();
511
+ }
512
+
513
+ /**
514
+ * M12: is this built-in model call carrying a key that is not this run's? A key header is the
515
+ * run's when it holds a bound placeholder or its hash was allowed; every other key is "other".
516
+ * With no key header at all the call is "other" too, with nothing to remember.
517
+ *
518
+ * @param {Record<string, string | string[] | undefined>} headers the request headers
519
+ * @param {{ header: string, bound: boolean }[]} found the request's placeholders
520
+ * @returns {null | { hash: string | null, last4: string }} null: the run's key; else the key's hash and last 4 characters (null and '' for no key)
521
+ */
522
+ function otherKey(headers, found) {
523
+ const present = KEY_HEADERS.filter((h) => keyIn(headers, h));
524
+ if (!present.length) return { hash: null, last4: '' };
525
+ for (const h of present) {
526
+ if (found.some((f) => f.bound && f.header === h)) continue;
527
+ const key = keyIn(headers, h);
528
+ const hash = crypto.createHash('sha256').update(key).digest('hex');
529
+ if (!allowedKeys.has(hash)) return { hash, last4: key.length >= 8 ? key.slice(-4) : '' };
530
+ }
531
+ return null;
532
+ }
533
+
478
534
  /**
479
535
  * Requests inside `gate.check()`, by `rid`: how the human channel finds
480
536
  * the request an ask is about. handleRequest sets and deletes each entry
@@ -504,19 +560,25 @@ export function createProxy(opts) {
504
560
  * @property {string|null} heldId id of the held body file, once spooled
505
561
  * @property {((reason: string) => void)|null} endAsk end a not-yet-parked ask as a denial
506
562
  * @property {Buffer|null} decodedHead copy of the first 4 KB of a gzip/deflate body, decoded (the ask preview)
563
+ * @property {'none'|'other'|''} modelKey 'none' (no key header) or 'other' for a model call whose key is not this run's; '' otherwise
564
+ * @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
+ * @property {string|null} askRule the rule the human channel was asked about (null: not asked)
566
+ * @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
567
+ * @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
507
568
  */
508
569
 
509
570
  /**
510
571
  * The human channel (bareguard `humanChannel` shape): every gate's asks
511
572
  * come here. Finds the request by `event.action.rid`, then holds it.
512
573
  *
513
- * @param {{ action?: { rid?: unknown }, rule?: string, rwxLetter?: string }} event
574
+ * @param {{ action?: { rid?: unknown, floor?: unknown, floorEntry?: unknown }, rule?: string, rwxLetter?: string }} event
514
575
  * @returns {Promise<{ decision: 'allow' | 'deny', reason?: string }>}
515
576
  */
516
577
  async function askHuman(event) {
517
578
  const ctx = inflightCtx.get(String(event?.action?.rid));
518
579
  if (!ctx) return { decision: 'deny', reason: 'request gone' };
519
580
  ctx.asked = true;
581
+ ctx.askRule = event.rule ?? null;
520
582
  return holdRequest(ctx, event);
521
583
  }
522
584
 
@@ -528,7 +590,7 @@ export function createProxy(opts) {
528
590
  * when the client or the proxy goes away first.
529
591
  *
530
592
  * @param {RequestCtx} ctx the request
531
- * @param {{ rule?: string, rwxLetter?: string }} event the gate's ask
593
+ * @param {{ rule?: string, rwxLetter?: string, action?: { floor?: unknown, floorEntry?: unknown } }} event the gate's ask
532
594
  * @returns {Promise<{ decision: 'allow' | 'deny', reason?: string }>}
533
595
  */
534
596
  function holdRequest(ctx, event) {
@@ -541,18 +603,20 @@ export function createProxy(opts) {
541
603
  let dead = false;
542
604
  /** @type {import('node:fs').WriteStream|null} */
543
605
  let ws = null;
544
- /** @param {{ decision: 'allow' | 'deny', reason?: string }} d */
606
+ /** @param {{ decision: 'allow' | 'deny', reason?: string, answered?: boolean }} d */
545
607
  const finish = (d) => {
546
608
  if (settled) return;
547
609
  settled = true;
548
610
  ctx.endAsk = null;
549
- resolve(d);
611
+ const { answered, ...rest } = d; // the one place `answered` is set: present only when true
612
+ ctx.answered = answered === true;
613
+ resolve(ctx.answered ? d : rest);
550
614
  };
551
- /** @param {string} reason @param {number} [status] */
552
- const refuse = (reason, status) => {
615
+ /** @param {string} reason @param {number} [status] @param {boolean} [answered] the hold timeout ended it */
616
+ const refuse = (reason, status, answered) => {
553
617
  if (settled) return; // a late failure must not rewrite the settled deny's status
554
618
  if (status) ctx.status = status;
555
- finish({ decision: 'deny', reason });
619
+ finish({ decision: 'deny', reason, answered });
556
620
  };
557
621
  const abort = () => {
558
622
  if (dead) return;
@@ -571,7 +635,7 @@ export function createProxy(opts) {
571
635
  if (!sock || sock.destroyed) { refuse('client gone'); return; }
572
636
  const slot = queue.reserve(agent, {
573
637
  onReady: () => stream(),
574
- onExpire: (why) => { abort(); refuse(why); },
638
+ onExpire: (why, answered) => { abort(); refuse(why, undefined, answered); },
575
639
  });
576
640
  if (slot.state === 'full') { ctx.freeWork(); refuse('hold queue full', 429); return; }
577
641
  ctx.endAsk = (why) => fail(why);
@@ -611,6 +675,10 @@ export function createProxy(opts) {
611
675
  // null: the reservation already expired and onExpire refused.
612
676
  parked = queue.add({ agent, method: ctx.method, url: ctx.url,
613
677
  preview: bodyPreview(ctx.decodedHead ?? ctx.tee.head), bodyBytes: ctx.tee.bytes,
678
+ effect: ctx.effect ?? undefined,
679
+ ...(event.action?.floor ? { floor: { kind: String(event.action.floor), entry: String(event.action.floorEntry) } } : {}),
680
+ ...(ctx.keyLast4 ? { keyLast4: ctx.keyLast4 } : {}),
681
+ ...(ctx.modelKey ? { modelKey: ctx.modelKey } : {}),
614
682
  sock, note: event.rule ?? 'ask', letter: event.rwxLetter, finish,
615
683
  slot, arrivedAt: slot.arrivedAt }) !== null;
616
684
  };
@@ -741,31 +809,94 @@ export function createProxy(opts) {
741
809
  /** @type {() => void} */
742
810
  let free = () => {};
743
811
  const freeWork = () => { if (!freed) { freed = true; free(); } };
812
+ // M12: the open ask this request leads for its unknown model key, if any (see `keyAsks`).
813
+ /** @type {((r: 'allow'|'deny'|'none') => void) | null} */
814
+ let settleKey = null;
744
815
  try {
816
+ // A model call is never card-scanned (user decision, Nov 2); the floor keeps every other request.
817
+ let tool = toolFor(matcher, tools, method, urlStr, modelEndpoints);
818
+ // M12: a call to a built-in model endpoint is a model call only with this run's key; any
819
+ // other key (or none) makes it a plain `x` POST. Parallel calls with one unknown key wait
820
+ // for the one open ask instead of asking again.
821
+ let unknownKey = null;
822
+ if (builtinModels.has(tool)) {
823
+ for (;;) {
824
+ unknownKey = otherKey(creq.headers, found);
825
+ const open = unknownKey?.hash ? keyAsks.get(unknownKey.hash) : undefined;
826
+ if (!open) break;
827
+ // A waiter holds a place among the agent's waiters (the queue owns the count), and loses it
828
+ // when its client goes or the ask ends.
829
+ const release = holds ? holds.wait(agent) : () => {};
830
+ if (!release) {
831
+ discard(creq);
832
+ denyRes(cres, 429, 'denied: hold queue full');
833
+ return;
834
+ }
835
+ /** @type {() => void} */
836
+ let onGone = () => {};
837
+ const gone = new Promise((r) => { onGone = () => r('gone'); cres.once('close', onGone); });
838
+ const r = await Promise.race([open, gone]);
839
+ cres.off('close', onGone);
840
+ release();
841
+ if (r === 'gone') { discard(creq); return; }
842
+ if (r === 'deny') {
843
+ discard(creq);
844
+ denyRes(cres, 403, 'denied: model key');
845
+ return;
846
+ }
847
+ }
848
+ if (unknownKey) {
849
+ tool = `http.${method}`;
850
+ if (unknownKey.hash) {
851
+ const hash = unknownKey.hash;
852
+ /** @type {(r: 'allow'|'deny'|'none') => void} */
853
+ let resolveAsk = () => {};
854
+ keyAsks.set(hash, new Promise((r) => { resolveAsk = r; }));
855
+ settleKey = (r) => { settleKey = null; keyAsks.delete(hash); resolveAsk(r); };
856
+ }
857
+ }
858
+ }
745
859
  if (hasBody) {
746
860
  free = await takeWorkSlot(agent, cres);
747
861
  } else creq.resume();
748
862
  if (sock.destroyed) return;
863
+ // The floor (M11) needs no body to decide. A host the matcher cannot check is refused: it fails closed.
864
+ let floorHit;
865
+ try { floorHit = floors.match(method, url.hostname, urlStr); } catch {
866
+ discard(creq);
867
+ denyRes(cres, 403, 'denied: floor: host not checkable');
868
+ return;
869
+ }
749
870
  /** @type {RequestCtx} */
750
871
  const ctx = { agent, method, url: urlStr, headers: { ...creq.headers }, creq, cres, tee,
751
872
  hasBody, chunks: [], over: false, freeWork, asked: false, status: null, heldId: null,
752
- endAsk: null, decodedHead: null };
753
- // A model call is never card-scanned (user decision, Nov 2); the floor keeps every other request.
754
- const tool = toolFor(matcher, tools, method, urlStr, modelEndpoints);
873
+ endAsk: null, decodedHead: null, effect: null, keyLast4: unknownKey?.last4 ?? '', modelKey: unknownKey ? (unknownKey.hash ? 'other' : 'none') : '', askRule: null, answered: false };
755
874
  let cardLike = false;
756
875
  if (hasBody) {
757
876
  if (await readWorkBody(ctx)) return;
877
+ const scanCards = !models.has(tool);
758
878
  // Past 64 KB the body streams on unscanned (known gap).
759
- if (!ctx.over && !models.has(tool)) {
760
- cardLike = await scanBody(ctx);
879
+ if (ctx.over) {
880
+ if (floorHit) ctx.effect = findEffect('', undefined, 'over');
881
+ } else if (scanCards || floorHit) {
882
+ cardLike = await scanBody(ctx, scanCards, floorHit !== null);
761
883
  }
762
884
  }
763
885
  // The body never goes in the action: bareguard writes the action to its audit file.
764
886
  const action = { type: 'net', tool, url: urlStr, method, agent,
765
- cardLike, paymentPath: paymentPath(urlStr), rid };
887
+ cardLike, paymentPath: paymentPath(urlStr), rid,
888
+ ...(unknownKey ? { modelKey: 'other' } : {}),
889
+ ...(floorHit ? { floor: floorHit.kind, floorEntry: floorHit.entry } : {}) };
766
890
  inflightCtx.set(rid, ctx);
767
891
  const g = await gateOf(agent);
768
892
  const d = await decideAction(g, action);
893
+ // M12: a human's answer about an unknown key (not a card or floor ask) is the key's answer.
894
+ if (settleKey) {
895
+ const keyAsk = ctx.asked && !String(ctx.askRule).startsWith('flags.');
896
+ if (keyAsk && d.outcome === 'allow' && unknownKey?.hash) rememberKey(unknownKey.hash);
897
+ // Only a person's answer or the hold timeout denies the waiters; a cancel, a close or a failure lets the next one ask.
898
+ settleKey(!keyAsk ? 'none' : d.outcome === 'allow' ? 'allow' : ctx.answered ? 'deny' : 'none');
899
+ }
769
900
  if (d.outcome === 'allow') {
770
901
  const common = { agent, method, url: urlStr, headers: withSecrets(ctx.headers), cres,
771
902
  ...(d.aid ? { rec: { gate: g, action, aid: d.aid } } : {}) };
@@ -792,6 +923,7 @@ export function createProxy(opts) {
792
923
  denyRes(cres, ctx.status ?? 403, why);
793
924
  }
794
925
  } finally {
926
+ settleKey?.('none');
795
927
  inflightCtx.delete(rid);
796
928
  freeWork();
797
929
  }
@@ -860,13 +992,17 @@ export function createProxy(opts) {
860
992
  * body or its decoded view outlives the scan (same reason as `readWorkBody`).
861
993
  *
862
994
  * @param {RequestCtx} ctx request context, chunks already read
863
- * @returns {Promise<boolean>} true when the body looks like a card number
995
+ * @param {boolean} cards scan for card numbers (a model call is not scanned)
996
+ * @param {boolean} effect also find the effect fields (a floor request) and keep only that small result on `ctx.effect`
997
+ * @returns {Promise<boolean>} true when `cards` and the body looks like a card number
864
998
  */
865
- async function scanBody(ctx) {
999
+ async function scanBody(ctx, cards, effect) {
866
1000
  const body = Buffer.concat(ctx.chunks);
867
1001
  const view = await viewBody(body, ctx.headers);
868
1002
  // A copy, never a subarray: a subarray would keep the whole decoded buffer alive.
869
1003
  if (view.state === 'decoded' || view.state === 'truncated') ctx.decodedHead = Buffer.from(view.text.subarray(0, ASK_BODY_LIMIT));
1004
+ if (effect) ctx.effect = findEffect(view.text, String(ctx.headers['content-type'] ?? ''), view.state);
1005
+ if (!cards) return false;
870
1006
  // The raw bytes are always scanned; decoded output is scanned as well (one scanner per buffer).
871
1007
  return createCardScanner().push(body) || (view.text !== body && createCardScanner().push(view.text));
872
1008
  }
@@ -911,6 +1047,15 @@ export function createProxy(opts) {
911
1047
  server.on('clientError', (err, sock) => {
912
1048
  try { sock.destroy(); } catch {}
913
1049
  });
1050
+ // A protocol upgrade (WebSocket, h2c) and a CONNECT inside a tunnel are refused at once, in
1051
+ // every mode and for every host: nothing is resolved, gated or dialed. Without these
1052
+ // listeners node would forward the upgrade as a GET, or close the socket with no reason.
1053
+ server.on('upgrade', (creq, sock) => {
1054
+ 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}`);
1057
+ });
1058
+ server.on('connect', (creq, sock) => { denyRaw(sock, 403, 'denied: connect', creq.url || ''); });
914
1059
 
915
1060
  // Dispatch: one CONNECT line, or plain HTTP straight into the same server.
916
1061
  function admit(sock, agent) {
package/src/run.js CHANGED
@@ -65,6 +65,7 @@ import { loadSecrets } from './secrets.js';
65
65
  * @property {number} [heldBodyMaxBytes] cap on a held request's body, in bytes (default 52428800); over it the request is denied
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
+ * @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`)
68
69
  * @property {object} [unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`): everything under it weakens the sandbox wall
69
70
  * @property {NodeJS.WritableStream} [stdout] where the agent's stdout goes (default process.stdout)
70
71
  * @property {NodeJS.WritableStream} [stderr] where the agent's stderr goes (default process.stderr)
@@ -89,6 +90,7 @@ import { loadSecrets } from './secrets.js';
89
90
  * @param {number} [opts.heldBodyMaxBytes] cap on a held request's body, in bytes (default 52428800); over it the request is denied
90
91
  * @param {{ matcher: any, tools: Record<string, any>, dirs?: string[] }|null} [opts.labels] the loaded label files (`loadLabels`); their folders are masked from the sandbox
91
92
  * @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
+ * @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`)
92
94
  * @param {object|null} [opts.unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`)
93
95
  * @param {NodeJS.WritableStream|null} [opts.stdout] where the agent's stdout goes (default process.stdout)
94
96
  * @param {NodeJS.WritableStream|null} [opts.stderr] where the agent's stderr goes (default process.stderr)
@@ -105,7 +107,7 @@ import { loadSecrets } from './secrets.js';
105
107
  */
106
108
  export async function run({ proj, command, mode = 'auto', onAsk = null,
107
109
  onEvent = null, runtime = null, agent = 'agent', timeoutMs, heldBodyMaxBytes,
108
- allowLocal = [], labels = null, unsafeTestOnly = null, stdout = null, stderr = null,
110
+ allowLocal = [], floor = null, labels = null, unsafeTestOnly = null, stdout = null, stderr = null,
109
111
  overlay = false, overlayIgnore, secrets = null, env = null }) {
110
112
  if (typeof proj !== 'string' || !proj) throw new Error('run: proj must be a non-empty string');
111
113
  if (!fs.existsSync(proj)) throw new Error(`run: proj does not exist: ${proj}`);
@@ -143,7 +145,7 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
143
145
  : recordEvent;
144
146
 
145
147
  const proxy = createProxy({
146
- runtime: rt, logFile: audit, allowLocal, unsafeTestOnly, secrets: loaded,
148
+ runtime: rt, logFile: audit, allowLocal, ...(floor ? { floor } : {}), unsafeTestOnly, secrets: loaded,
147
149
  ...(labels ? { labels } : {}),
148
150
  gateFor: (name, { humanChannel, tools }) => gateFor({ agent: name, mode, auditPath: audit, humanChannel, tools }),
149
151
  hold: { onAsk, timeoutMs, maxBody: heldBodyMaxBytes, onEvent: holdOnEvent },
package/types/config.d.ts CHANGED
@@ -9,7 +9,7 @@ export function configPath(env?: NodeJS.ProcessEnv): string;
9
9
  * Read the config file over the defaults. No file means defaults.
10
10
  *
11
11
  * @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, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
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)
13
13
  * @throws {Error} naming the file (and the key) on invalid JSON, an unknown key or a bad value
14
14
  */
15
15
  export function loadConfig(env?: NodeJS.ProcessEnv): {
@@ -19,6 +19,10 @@ export function loadConfig(env?: NodeJS.ProcessEnv): {
19
19
  labels: string[];
20
20
  tenants: Record<string, string[]>;
21
21
  heldBodyMaxMB?: number;
22
+ floor?: {
23
+ pay?: string[];
24
+ send?: string[];
25
+ };
22
26
  env?: {
23
27
  pass?: string[];
24
28
  set?: Record<string, string>;
@@ -36,7 +40,7 @@ export function loadConfig(env?: NodeJS.ProcessEnv): {
36
40
  * @param {string} [flags.mode] `--mode`
37
41
  * @param {string} [flags.hold] `--hold` (`"never"` or a positive integer of seconds, as typed)
38
42
  * @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
39
- * @returns {{ mode: string, holdTimeoutSec?: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
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)
40
44
  * @throws {Error} as {@link loadConfig}
41
45
  */
42
46
  export function resolveConfig(flags?: {
@@ -49,6 +53,10 @@ export function resolveConfig(flags?: {
49
53
  labels: string[];
50
54
  tenants: Record<string, string[]>;
51
55
  heldBodyMaxMB?: number;
56
+ floor?: {
57
+ pay?: string[];
58
+ send?: string[];
59
+ };
52
60
  env?: {
53
61
  pass?: string[];
54
62
  set?: Record<string, string>;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Find every recipient, amount and currency field in a body.
3
+ *
4
+ * @param {string|Buffer} text the body text (decoded when the body view decoded it)
5
+ * @param {string|undefined} contentType the Content-Type header value
6
+ * @param {'plain'|'decoded'|'truncated'|'unread'|'over'} state the body view state, or `over` when the body
7
+ * is over 64 KB and was not viewed
8
+ * @returns {Effect}
9
+ */
10
+ export function findEffect(text: string | Buffer, contentType: string | undefined, state: "plain" | "decoded" | "truncated" | "unread" | "over"): Effect;
11
+ /** The one limit: a kind with more than this many matches is shown as "more than LIST_MAX", never as a list. Each kind keeps at most LIST_MAX + 1. */
12
+ export const LIST_MAX: 5;
13
+ export type EffectField = {
14
+ /**
15
+ * where it sits in the body: `a.b[0].c` for JSON, the key as sent for a form
16
+ */
17
+ path: string;
18
+ /**
19
+ * the scalar value, masked for card numbers and cut at 200 chars
20
+ */
21
+ value: string;
22
+ };
23
+ export type Effect = {
24
+ recipient: EffectField[];
25
+ amount: EffectField[];
26
+ currency: EffectField[];
27
+ /**
28
+ * why the body was not read (the three lists are then empty), else null
29
+ */
30
+ notRead: string | null;
31
+ };
package/types/holds.d.ts CHANGED
@@ -44,6 +44,10 @@ export function bodyPreview(head: Buffer): string;
44
44
  * @property {string} letter the matched rwx letter, `'x'` when the ask names none
45
45
  * @property {string} bodyPreview request body preview, utf8, capped at ASK_BODY_LIMIT bytes, card numbers masked
46
46
  * @property {boolean} truncated true when the body exceeded ASK_BODY_LIMIT
47
+ * @property {{ kind: 'pay'|'send'|string, entry: string }} [floor] present when the request hit a domain the user listed in config `floor` (kind: which list, entry: the matching entry)
48
+ * @property {import('./effect.js').Effect} [effect] present on a floor request with a body: the recipient, amount and currency fields found in it (values masked for card numbers), or why it was not read
49
+ * @property {string} [keyLast4] present on a model call whose key is not this run's: the key's last 4 characters (never more)
50
+ * @property {'none'|'other'} [modelKey] present on a model call whose key is not this run's: 'none' (no key header) or 'other' (a key, possibly too short for a last 4)
47
51
  * @property {number} waitingSec 0 at park; readers use the file mtime for a live value
48
52
  * @property {string|null} expiresAt ISO-8601 UTC deadline, or null when `timeoutMs: 'never'`
49
53
  */
@@ -52,6 +56,15 @@ export function bodyPreview(head: Buffer): string;
52
56
  *
53
57
  * @typedef {(ask: AskPayload) => Promise<{ decision: string, reason?: string }>} OnAsk
54
58
  */
59
+ /**
60
+ * Write `text` to a fresh 0600 temp file next to `file` (parent made on demand).
61
+ * The caller renames or links it into place.
62
+ *
63
+ * @param {string} file destination path the temp file sits beside
64
+ * @param {string} text content
65
+ * @returns {string} path of the temp file
66
+ */
67
+ export function writeTmpFile(file: string, text: string): string;
55
68
  /**
56
69
  * Atomic write: tmp file + rename, so readers never see a partial payload.
57
70
  *
@@ -97,8 +110,8 @@ export function normalizeDecision(input: {
97
110
  * @param {number} [opts.pollMs] answer poll interval in ms for the default file checkpoint (default 250, PRD Q9)
98
111
  * @param {OnEvent|null} [opts.onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon
99
112
  * @param {(entry: object) => void} opts.onApprove forward the parked request upstream
100
- * @param {(entry: object, reason: string) => void} opts.onDeny refuse the parked request
101
- * @returns {{ add: (entry: object) => string|null, dropBody: (id: string) => void, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string) => void }) => { state: 'now'|'queued'|'full', id: string, arrivedAt: number, cancel: () => void }, abandon: (id: string) => void, abandonSocket: (sock: object) => void, pending: () => HeldRequest[], close: () => void }} queue handle
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
102
115
  */
103
116
  export function createHolds({ log, timeoutMs, maxBody, runtime, onAsk, pollMs, onEvent, onApprove, onDeny }: {
104
117
  log: (o: Record<string, unknown>) => void;
@@ -109,13 +122,13 @@ export function createHolds({ log, timeoutMs, maxBody, runtime, onAsk, pollMs, o
109
122
  pollMs?: number | undefined;
110
123
  onEvent?: OnEvent | null | undefined;
111
124
  onApprove: (entry: object) => void;
112
- onDeny: (entry: object, reason: string) => void;
125
+ onDeny: (entry: object, reason: string, answered: boolean) => void;
113
126
  }): {
114
127
  add: (entry: object) => string | null;
115
128
  dropBody: (id: string) => void;
116
129
  reserve: (agent: string, cbs: {
117
130
  onReady: () => void;
118
- onExpire: (reason: string) => void;
131
+ onExpire: (reason: string, answered?: boolean) => void;
119
132
  }) => {
120
133
  state: "now" | "queued" | "full";
121
134
  id: string;
@@ -124,6 +137,7 @@ export function createHolds({ log, timeoutMs, maxBody, runtime, onAsk, pollMs, o
124
137
  };
125
138
  abandon: (id: string) => void;
126
139
  abandonSocket: (sock: object) => void;
140
+ wait: (agent: string) => (() => void) | null;
127
141
  pending: () => HeldRequest[];
128
142
  close: () => void;
129
143
  };
@@ -219,6 +233,25 @@ export type AskPayload = {
219
233
  * true when the body exceeded ASK_BODY_LIMIT
220
234
  */
221
235
  truncated: boolean;
236
+ /**
237
+ * present when the request hit a domain the user listed in config `floor` (kind: which list, entry: the matching entry)
238
+ */
239
+ floor?: {
240
+ kind: "pay" | "send" | string;
241
+ entry: string;
242
+ } | undefined;
243
+ /**
244
+ * present on a floor request with a body: the recipient, amount and currency fields found in it (values masked for card numbers), or why it was not read
245
+ */
246
+ effect?: import("./effect.js").Effect | undefined;
247
+ /**
248
+ * present on a model call whose key is not this run's: the key's last 4 characters (never more)
249
+ */
250
+ keyLast4?: string | undefined;
251
+ /**
252
+ * present on a model call whose key is not this run's: 'none' (no key header) or 'other' (a key, possibly too short for a last 4)
253
+ */
254
+ modelKey?: "none" | "other" | undefined;
222
255
  /**
223
256
  * 0 at park; readers use the file mtime for a live value
224
257
  */
package/types/lists.d.ts CHANGED
@@ -16,4 +16,24 @@ export function normalizeUrl(url: string): string;
16
16
  export function endpointList(entries: string[], makeMatcher?: typeof matcherFrom): {
17
17
  match: (method: string, url: string) => string | null;
18
18
  };
19
+ /**
20
+ * Build the floor lists (M11): the domains the user listed for payments (`pay`)
21
+ * and sends (`send`). A host or `*.domain` entry hits any request whose method is
22
+ * not GET/HEAD; a `"METHOD host/path"` entry hits only that endpoint. Zero built-in
23
+ * entries. `pay` wins when an entry is in both.
24
+ *
25
+ * @param {{ pay?: string[], send?: string[] }} [lists] the config `floor` key
26
+ * @param {typeof matcherFrom} [makeMatcher] builds one host's matcher (a test counts its `match` calls)
27
+ * @returns {{ match: (method: string, hostname: string, url: string) => { kind: 'pay'|'send', entry: string } | null }} `match` takes the request's parsed hostname; it throws (the caller fails closed) on a hostname `hostMatcher` refuses
28
+ */
29
+ export function floorList({ pay, send }?: {
30
+ pay?: string[];
31
+ send?: string[];
32
+ }, makeMatcher?: typeof matcherFrom): {
33
+ match: (method: string, hostname: string, url: string) => {
34
+ kind: "pay" | "send";
35
+ entry: string;
36
+ } | null;
37
+ };
38
+ export function isEndpoint(e: unknown): boolean;
19
39
  import { matcherFrom } from 'rwxmap/match';
package/types/prompt.d.ts CHANGED
@@ -1,4 +1,27 @@
1
- /** @typedef {{ id: string, agent?: string, method: string, url: string, rule: string, letter: string, bodyPreview?: string, expiresAt?: string|null }} AskRecord */
1
+ /** @typedef {{ id: string, agent?: string, method: string, url: string, rule: string, letter: string, bodyPreview?: string, expiresAt?: string|null, floor?: { kind: string, entry: string }, effect?: import('./effect.js').Effect, keyLast4?: string, modelKey?: 'none'|'other' }} AskRecord */
2
+ /**
3
+ * The `To:` / `Amount:` / `Currency:` lines of a floor request, or one `Effect:` line saying why none was read.
4
+ * Up to LIST_MAX fields are all listed; more than that lists none (too many to tell the real one).
5
+ *
6
+ * @param {AskRecord['effect']} effect the ask's effect, absent when the request had no body
7
+ * @param {boolean} color paint with ANSI escapes
8
+ * @returns {string[]} zero or more lines
9
+ */
10
+ export function effectLines(effect: AskRecord["effect"], color: boolean): string[];
11
+ /**
12
+ * The ` floor=<kind> entry=<entry>` tail of a one-line ask (`sbx pending`, the non-terminal `ask` line); empty without a floor hit.
13
+ *
14
+ * @param {AskRecord} ask the parked request
15
+ * @returns {string} the tail, or ''
16
+ */
17
+ export function floorTail(ask: AskRecord): string;
18
+ /**
19
+ * The ` key=…<last 4>` tail of a one-line ask (`sbx pending`, the non-terminal `ask` line); ` key=none` or ` key=other` when there is no last 4 to show; empty unless the ask is a model call with another key.
20
+ *
21
+ * @param {AskRecord} ask the parked request
22
+ * @returns {string} the tail, or ''
23
+ */
24
+ export function keyTail(ask: AskRecord): string;
2
25
  /**
3
26
  * Plain-language lines for one ask record. Every agent-controlled byte goes
4
27
  * through `safe()`.
@@ -56,4 +79,11 @@ export type AskRecord = {
56
79
  letter: string;
57
80
  bodyPreview?: string;
58
81
  expiresAt?: string | null;
82
+ floor?: {
83
+ kind: string;
84
+ entry: string;
85
+ };
86
+ effect?: import("./effect.js").Effect;
87
+ keyLast4?: string;
88
+ modelKey?: "none" | "other";
59
89
  };
package/types/proxy.d.ts CHANGED
@@ -9,6 +9,7 @@
9
9
  * @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.
10
10
  * @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
11
11
  * @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
12
+ * @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.
12
13
  * @property {HoldOptions} [hold] hold queue config (deadline, caps, ask seam)
13
14
  * @property {number} [upstreamTimeoutMs] give up on an upstream response after this (default 120000)
14
15
  * @property {object} [unsafeTestOnly] TEST-ONLY escape hatch: everything under
@@ -129,6 +130,13 @@ export type ProxyOptions = {
129
130
  * exact `host:port` pairs (the `localLlm` setting) that may pass the wall's private/loopback check; any other local destination is still denied
130
131
  */
131
132
  allowLocal?: string[] | undefined;
133
+ /**
134
+ * 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.
135
+ */
136
+ floor?: {
137
+ pay?: string[];
138
+ send?: string[];
139
+ } | undefined;
132
140
  /**
133
141
  * hold queue config (deadline, caps, ask seam)
134
142
  */