barebox 0.11.0 → 0.13.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/lists.js CHANGED
@@ -6,9 +6,18 @@
6
6
  // every server in it). The host is checked in a Map first: rwxmap's `match()` runs
7
7
  // a classifier on every miss, and most requests are for hosts on no list.
8
8
  import { matcherFrom } from 'rwxmap/match';
9
+ import { hostMatcher } from 'bareguard';
9
10
 
10
11
  const METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'];
11
12
 
13
+ /**
14
+ * The one trailing-dot rule: `api.anthropic.com.` is `api.anthropic.com`.
15
+ *
16
+ * @param {string} host a hostname
17
+ * @returns {string} the host without one trailing dot
18
+ */
19
+ const stripDot = (host) => (host.endsWith('.') ? host.slice(0, -1) : host);
20
+
12
21
  /**
13
22
  * The one place a request URL is normalised: one trailing dot is stripped from the
14
23
  * host (`api.anthropic.com.` is `api.anthropic.com`). Throws like `URL` on a non-URL.
@@ -18,7 +27,7 @@ const METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'];
18
27
  */
19
28
  export function normalizeUrl(url) {
20
29
  const u = new URL(url);
21
- if (u.hostname.endsWith('.')) u.hostname = u.hostname.slice(0, -1);
30
+ u.hostname = stripDot(u.hostname);
22
31
  return u.href;
23
32
  }
24
33
 
@@ -75,3 +84,71 @@ export function endpointList(entries, makeMatcher = matcherFrom) {
75
84
  },
76
85
  };
77
86
  }
87
+
88
+ /** `"METHOD host/path"` has a space; a host or `*.domain` entry never does. @param {unknown} e @returns {boolean} */
89
+ export const isEndpoint = (e) => typeof e === 'string' && e.includes(' ');
90
+
91
+ /**
92
+ * The floor's endpoint spelling rule, for the request path only: per segment drop
93
+ * `;params`, decode `%XX` of unreserved characters (`A-Z a-z 0-9 - . _ ~`), lowercase.
94
+ * Reserved escapes (`%2F`) stay, so `/v1/charges%2Fx` is still a different path.
95
+ *
96
+ * @param {string} url full request URL
97
+ * @returns {string} the same URL with the path spelled one way
98
+ */
99
+ function floorSpelling(url) {
100
+ const u = new URL(url);
101
+ u.pathname = u.pathname.split('/').map((seg) => seg.split(';')[0]
102
+ .replace(/%([0-9A-Fa-f]{2})/g, (m, h) => { const c = String.fromCharCode(parseInt(h, 16)); return /[A-Za-z0-9\-._~]/.test(c) ? c : m; })
103
+ .toLowerCase()).join('/');
104
+ return u.href;
105
+ }
106
+
107
+ /**
108
+ * Build the floor lists (M11): the domains the user listed for payments (`pay`)
109
+ * and sends (`send`). A host or `*.domain` entry hits any request whose method is
110
+ * not GET/HEAD; a `"METHOD host/path"` entry hits only that endpoint. Zero built-in
111
+ * entries. `pay` wins when an entry is in both.
112
+ *
113
+ * @param {{ pay?: string[], send?: string[] }} [lists] the config `floor` key
114
+ * @param {typeof matcherFrom} [makeMatcher] builds one host's matcher (a test counts its `match` calls)
115
+ * @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
116
+ */
117
+ export function floorList({ pay = [], send = [] } = {}, makeMatcher = matcherFrom) {
118
+ const kinds = /** @type {const} */ (['pay', 'send']).map((kind) => {
119
+ const entries = kind === 'pay' ? pay : send;
120
+ const hostEntries = entries.filter((e) => !isEndpoint(e));
121
+ const endpointEntries = entries.filter(isEndpoint);
122
+ // Entry paths are lowercased to match the lowercased request path; `written` maps back to the string the user wrote.
123
+ /** @type {Map<string, string>} */
124
+ const written = new Map();
125
+ const lowered = endpointEntries.map((e) => {
126
+ const { method, host, path } = parseEntry(e);
127
+ const l = `${method} ${host}${path.toLowerCase()}`;
128
+ if (!written.has(l)) written.set(l, e);
129
+ return l;
130
+ });
131
+ return {
132
+ kind,
133
+ written,
134
+ hosts: hostEntries.length ? hostMatcher(hostEntries) : null,
135
+ endpoints: endpointEntries.length ? endpointList(lowered, makeMatcher) : null,
136
+ // The port is dropped: the request's hostname never carries one; endpointList then checks it exactly.
137
+ endpointHosts: new Set(endpointEntries.map((e) => parseEntry(e).host.replace(/:\d+$/, ''))),
138
+ };
139
+ });
140
+ return {
141
+ match(method, hostname, url) {
142
+ const host = stripDot(hostname);
143
+ const m = method.toUpperCase();
144
+ const write = m !== 'GET' && m !== 'HEAD';
145
+ for (const { kind, written, hosts, endpoints, endpointHosts } of kinds) {
146
+ const byHost = write && hosts ? hosts.match(host) : null;
147
+ if (byHost !== null) return { kind, entry: byHost };
148
+ const byEndpoint = endpoints && endpointHosts.has(host) ? endpoints.match(method, floorSpelling(url)) : null;
149
+ if (byEndpoint !== null) return { kind, entry: /** @type {string} */ (written.get(byEndpoint)) };
150
+ }
151
+ return null;
152
+ },
153
+ };
154
+ }
package/src/policy.js CHANGED
@@ -140,7 +140,7 @@ export function toolFor(matcher, tools, method, url, models) {
140
140
  }
141
141
 
142
142
  /** @type {Record<string, Record<string, 'ask' | 'deny'>>} */
143
- const FLAGS = { cardLike: { true: 'ask' }, paymentPath: { true: 'ask' } };
143
+ const FLAGS = { cardLike: { true: 'ask' }, paymentPath: { true: 'ask' }, floor: { pay: 'ask', send: 'ask' } };
144
144
 
145
145
  /** Payment-destination path fragments: the URL-visible half of the floor (PRD section 2). */
146
146
  const PAYMENT_PATHS = ['/checkout', '/payment', '/orders', '/purchase'];
package/src/prompt.js CHANGED
@@ -8,6 +8,8 @@
8
8
  // question open is dropped (so a `y` typed during h1 never approves h2), and
9
9
  // once a hold is decided elsewhere nothing is written for it.
10
10
  import { safe } from './runtime.js';
11
+ import { isEndpoint } from './lists.js';
12
+ import { LIST_MAX } from './effect.js';
11
13
 
12
14
  const BODY_CHARS = 200;
13
15
  const EOL = /\r\n|\r|\n/;
@@ -27,7 +29,39 @@ export const ANSI = { bold: '\x1b[1m', dim: '\x1b[2m', red: '\x1b[31m', green: '
27
29
  */
28
30
  export const paint = (on, codes, text) => (on ? `${codes}${text}${ANSI.reset}` : text);
29
31
 
30
- /** @typedef {{ id: string, agent?: string, method: string, url: string, rule: string, letter: string, bodyPreview?: string, expiresAt?: string|null }} AskRecord */
32
+ /** @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 }} AskRecord */
33
+
34
+ /**
35
+ * The `To:` / `Amount:` / `Currency:` lines of a floor request, or one `Effect:` line saying why none was read.
36
+ * Up to LIST_MAX fields are all listed; more than that lists none (too many to tell the real one).
37
+ *
38
+ * @param {AskRecord['effect']} effect the ask's effect, absent when the request had no body
39
+ * @param {boolean} color paint with ANSI escapes
40
+ * @returns {string[]} zero or more lines
41
+ */
42
+ export function effectLines(effect, color) {
43
+ if (!effect) return [];
44
+ const { bold } = ANSI;
45
+ if (effect.notRead !== null) return [` ${paint(color, bold, 'Effect:')} not read (${safe(effect.notRead)})`];
46
+ /** @type {[string, { path: string, value: string }[]][]} */
47
+ const rows = [['To:', effect.recipient], ['Amount:', effect.amount], ['Currency:', effect.currency]];
48
+ return rows.filter(([, f]) => f.length).map(([label, f]) => {
49
+ const shown = f.length > LIST_MAX
50
+ ? `more than ${LIST_MAX} fields (not listed: too many to tell the real one)`
51
+ : f.map((x) => `${safe(x.path)}=${safe(x.value)}`).join('; ');
52
+ return ` ${paint(color, bold, label)} ${shown}`;
53
+ });
54
+ }
55
+
56
+ /**
57
+ * The ` floor=<kind> entry=<entry>` tail of a one-line ask (`sbx pending`, the non-terminal `ask` line); empty without a floor hit.
58
+ *
59
+ * @param {AskRecord} ask the parked request
60
+ * @returns {string} the tail, or ''
61
+ */
62
+ export function floorTail(ask) {
63
+ return ask.floor ? ` floor=${safe(ask.floor.kind)} entry=${safe(ask.floor.entry)}` : '';
64
+ }
31
65
 
32
66
  /**
33
67
  * Plain-language lines for one ask record. Every agent-controlled byte goes
@@ -48,7 +82,9 @@ export function questionLines(ask, now = Date.now(), color = false) {
48
82
  : method === 'DELETE' ? 'DELETE data on'
49
83
  : `make a ${method} request to`;
50
84
  const rule = safe(ask.rule);
51
- const why = rule === 'flags.cardLike' ? 'it contains what looks like a card number'
85
+ const why = rule === 'flags.floor' && ask.floor
86
+ ? `${ask.floor.kind === 'send' ? 'a send' : 'a payment'} to ${isEndpoint(ask.floor.entry) ? 'an endpoint' : 'a domain'} you listed (${safe(ask.floor.entry)})`
87
+ : rule === 'flags.cardLike' ? 'it contains what looks like a card number'
52
88
  : rule === 'flags.paymentPath' ? 'the address looks like a payment'
53
89
  : ask.letter === 'w' ? 'a change (reversible: the vendor says it can be undone)'
54
90
  : ask.letter === 'x' ? "a change barebox can't undo"
@@ -63,6 +99,7 @@ export function questionLines(ask, now = Date.now(), color = false) {
63
99
  ` ${paint(color, bold, 'Why:')} ${why}`,
64
100
  ` ${paint(color, bold, 'URL:')} ${paint(color, cyan, `${method} ${safe(ask.url)}`)}`,
65
101
  ];
102
+ lines.push(...effectLines(ask.effect, color));
66
103
  const body = safe(ask.bodyPreview).slice(0, BODY_CHARS);
67
104
  if (body) lines.push(` ${paint(color, bold, 'Data:')} ${paint(color, dim, body)}`);
68
105
  const tail = `(hold ${safe(ask.id)})${left === null || Number.isNaN(left) ? '' : ` — no answer in ${left} s means No`}`;
@@ -71,40 +108,67 @@ export function questionLines(ask, now = Date.now(), color = false) {
71
108
  }
72
109
 
73
110
  /**
74
- * The terminal prompt. One question open at a time. `ask()` opens a question
75
- * and returns true, or returns false when one is already open (or the prompt
76
- * is closed) so the caller prints the plain `ask` line instead; `decided()`
77
- * closes the question when the hold ended some other way, `close()` releases
111
+ * The terminal prompt. It owns one hold from its question to the proxy's
112
+ * verdict. `ask()` opens a question and returns true, or returns false when a
113
+ * hold is still current (asking or awaiting its verdict) or the prompt is
114
+ * closed, so the caller prints the plain `ask` line instead; `decided()`
115
+ * ends the current hold with its outcome line, `close()` releases
78
116
  * `input`.
79
117
  *
80
118
  * @param {{ input: import('node:stream').Readable, output: { write: (s: string) => unknown }, color?: boolean, answer: (id: string, decision: 'allow'|'deny', reason?: string) => boolean|void }} opts streams and the answer writer
81
119
  * @returns {{ ask: (ask: AskRecord) => boolean, decided: (e: { id: string, decision: string, reason?: string }) => void, close: () => void }} the prompt
82
120
  */
83
121
  export function createTerminalPrompt({ input, output, answer, color = false }) {
84
- /** @type {AskRecord|null} */
85
- let open = null;
122
+ /** The one hold this prompt owns, from its question to the proxy's verdict. `typedYes`: true/false once our answer was written, null when another answer won, undefined while still asking.
123
+ * @type {{ ask: AskRecord, state: 'asking'|'sent', typedYes?: boolean|null }|null} */
124
+ let current = null;
86
125
  let buf = '';
87
126
  let closed = false;
88
127
  const say = (/** @type {string} */ s) => { output.write(`${s}\n`); };
89
128
 
129
+ // The one place that words an outcome. `typedYes` is true/false when our
130
+ // typed answer was written (✓/✗ allowed/denied only when the proxy's verdict
131
+ // matches it), undefined/null when nothing of ours was sent.
132
+ const outcome = (/** @type {{ decision: string, reason?: string }} */ e, /** @type {boolean|null|undefined} */ typedYes) => {
133
+ const why = safe(e.reason);
134
+ return typedYes === true && e.decision === 'allow' ? paint(color, ANSI.green + ANSI.bold, '✓ allowed')
135
+ : typedYes === false && e.decision === 'deny' && why === 'denied at the terminal' ? paint(color, ANSI.red + ANSI.bold, '✗ denied')
136
+ : why === 'hold timeout' ? paint(color, ANSI.red, '✗ timed out (denied)')
137
+ : why === 'client gone' ? paint(color, ANSI.red, '✗ agent gone (denied)')
138
+ : why === 'proxy closing' ? paint(color, ANSI.red, '✗ sandbox closed (denied)')
139
+ : e.decision === 'allow' ? '✓ answered elsewhere (allowed)'
140
+ : `✗ answered elsewhere (${why || 'denied'})`;
141
+ };
142
+
90
143
  const onLine = (/** @type {string} */ line) => {
91
- if (!open) return; // unreachable at runtime (onData checks); narrows the type for tsc
92
- const { id } = open;
93
- open = null; // closed before the write: one answer per question
144
+ const hold = current;
145
+ if (!hold || hold.state !== 'asking') return; // unreachable at runtime (onData checks); narrows the type for tsc
94
146
  const yes = YES.has(line.trim().toLowerCase());
147
+ let written = false;
95
148
  try {
96
- const written = answer(id, yes ? 'allow' : 'deny', yes ? undefined : 'denied at the terminal') !== false;
97
- say(!written ? 'answered elsewhere'
98
- : yes ? paint(color, ANSI.green + ANSI.bold, '✓ allowed') : paint(color, ANSI.red + ANSI.bold, '✗ denied'));
99
- } catch {
100
- // The hold ended (or the runtime went) before this write; the run goes on.
149
+ written = answer(hold.ask.id, yes ? 'allow' : 'deny', yes ? undefined : 'denied at the terminal') !== false;
150
+ } catch (e) {
151
+ // The write failed (disk full, runtime gone, ...); the run goes on and the
152
+ // hold stays open and asking: the next line retries. Say so at once:
153
+ // nothing else would, and a hold with no timeout would wait on a blank
154
+ // line. Never the message: it may hold a path.
155
+ const code = e && typeof e === 'object' && 'code' in e && typeof e.code === 'string' ? e.code : 'error';
156
+ const question = questionLines(hold.ask, Date.now(), color).at(-1)?.trimStart();
157
+ say(`${paint(color, ANSI.red, `✗ not sent (${safe(code)}), try again:`)} ${question}`);
158
+ return;
101
159
  }
160
+ // The receipt is instant; the verdict is appended by `decided` once the proxy
161
+ // has read the file (it may still time the hold out first). A lost write
162
+ // (another answer won) prints nothing now, but its `decided` still words the outcome.
163
+ hold.state = 'sent';
164
+ hold.typedYes = written ? yes : null;
165
+ if (written) output.write(`${paint(color, ANSI.dim, '→ sent')} `);
102
166
  };
103
167
 
104
168
  const onData = (/** @type {string|Buffer} */ chunk) => {
105
- if (!open) return;
169
+ if (current?.state !== 'asking') return;
106
170
  buf += String(chunk);
107
- for (let m = EOL.exec(buf); m && open; m = EOL.exec(buf)) {
171
+ for (let m = EOL.exec(buf); m && current?.state === 'asking'; m = EOL.exec(buf)) {
108
172
  const line = buf.slice(0, m.index);
109
173
  buf = buf.slice(m.index + m[0].length);
110
174
  onLine(line);
@@ -116,23 +180,21 @@ export function createTerminalPrompt({ input, output, answer, color = false }) {
116
180
 
117
181
  return {
118
182
  ask(ask) {
119
- if (closed || open) return false;
120
- open = ask;
183
+ if (closed || current) return false;
184
+ current = { ask, state: 'asking' };
121
185
  buf = ''; // a half-typed line from before the question is stale
122
- for (const l of questionLines(open, Date.now(), color)) say(l);
186
+ for (const l of questionLines(ask, Date.now(), color)) say(l);
123
187
  return true;
124
188
  },
125
189
  decided(e) {
126
- if (open?.id !== e.id) return;
127
- open = null; // closed before anything else: no answer can follow
128
- const why = safe(e.reason);
129
- say(why === 'hold timeout' ? paint(color, ANSI.red, `timed out: ${safe(e.decision)}`)
130
- : why === 'client gone' || why === 'proxy closing' ? paint(color, ANSI.red, `agent gone: ${safe(e.decision)}`)
131
- : `answered elsewhere: ${safe(e.decision)}${why ? ` (${why})` : ''}`);
190
+ if (current?.ask.id !== e.id) return;
191
+ const typedYes = current.typedYes;
192
+ current = null; // closed before anything else: no answer can follow
193
+ say(outcome(e, typedYes));
132
194
  },
133
195
  close() {
134
196
  closed = true;
135
- open = null;
197
+ current = null;
136
198
  input.removeListener('data', onData);
137
199
  input.pause();
138
200
  },
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
 
@@ -55,6 +57,7 @@ const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
55
57
  * @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
58
  * @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
59
  * @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
60
+ * @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
61
  * @property {HoldOptions} [hold] hold queue config (deadline, caps, ask seam)
59
62
  * @property {number} [upstreamTimeoutMs] give up on an upstream response after this (default 120000)
60
63
  * @property {object} [unsafeTestOnly] TEST-ONLY escape hatch: everything under
@@ -126,7 +129,7 @@ const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
126
129
  */
127
130
  export function createProxy(opts) {
128
131
  const { logFile, runtime, port = null,
129
- upstreamCa = null, hold = null, gateFor = null, allowLocal = [], labels = null,
132
+ upstreamCa = null, hold = null, gateFor = null, allowLocal = [], floor = null, labels = null,
130
133
  upstreamTimeoutMs = 120000, clientIdleMs = 60000,
131
134
  unsafeTestOnly = null, secrets = [],
132
135
  redact = (e) => e } = opts ?? {};
@@ -142,6 +145,7 @@ export function createProxy(opts) {
142
145
  const tools = buildTools(labels?.tools, [...allowLocal]);
143
146
  const models = modelTools(labels?.tools, [...allowLocal]);
144
147
  const modelEndpoints = modelList([...allowLocal]);
148
+ const floors = floorList(floor ?? {});
145
149
  if (!logFile) throw new Error('createProxy: logFile is required');
146
150
  if (typeof runtime !== 'string' || !runtime) throw new Error('createProxy: runtime is required');
147
151
  // One live proxy per runtime, enforced here: claimed before the hold
@@ -504,13 +508,14 @@ export function createProxy(opts) {
504
508
  * @property {string|null} heldId id of the held body file, once spooled
505
509
  * @property {((reason: string) => void)|null} endAsk end a not-yet-parked ask as a denial
506
510
  * @property {Buffer|null} decodedHead copy of the first 4 KB of a gzip/deflate body, decoded (the ask preview)
511
+ * @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
512
  */
508
513
 
509
514
  /**
510
515
  * The human channel (bareguard `humanChannel` shape): every gate's asks
511
516
  * come here. Finds the request by `event.action.rid`, then holds it.
512
517
  *
513
- * @param {{ action?: { rid?: unknown }, rule?: string, rwxLetter?: string }} event
518
+ * @param {{ action?: { rid?: unknown, floor?: unknown, floorEntry?: unknown }, rule?: string, rwxLetter?: string }} event
514
519
  * @returns {Promise<{ decision: 'allow' | 'deny', reason?: string }>}
515
520
  */
516
521
  async function askHuman(event) {
@@ -528,7 +533,7 @@ export function createProxy(opts) {
528
533
  * when the client or the proxy goes away first.
529
534
  *
530
535
  * @param {RequestCtx} ctx the request
531
- * @param {{ rule?: string, rwxLetter?: string }} event the gate's ask
536
+ * @param {{ rule?: string, rwxLetter?: string, action?: { floor?: unknown, floorEntry?: unknown } }} event the gate's ask
532
537
  * @returns {Promise<{ decision: 'allow' | 'deny', reason?: string }>}
533
538
  */
534
539
  function holdRequest(ctx, event) {
@@ -611,6 +616,8 @@ export function createProxy(opts) {
611
616
  // null: the reservation already expired and onExpire refused.
612
617
  parked = queue.add({ agent, method: ctx.method, url: ctx.url,
613
618
  preview: bodyPreview(ctx.decodedHead ?? ctx.tee.head), bodyBytes: ctx.tee.bytes,
619
+ effect: ctx.effect ?? undefined,
620
+ ...(event.action?.floor ? { floor: { kind: String(event.action.floor), entry: String(event.action.floorEntry) } } : {}),
614
621
  sock, note: event.rule ?? 'ask', letter: event.rwxLetter, finish,
615
622
  slot, arrivedAt: slot.arrivedAt }) !== null;
616
623
  };
@@ -746,23 +753,34 @@ export function createProxy(opts) {
746
753
  free = await takeWorkSlot(agent, cres);
747
754
  } else creq.resume();
748
755
  if (sock.destroyed) return;
756
+ // The floor (M11) needs no body to decide. A host the matcher cannot check is refused: it fails closed.
757
+ let floorHit;
758
+ try { floorHit = floors.match(method, url.hostname, urlStr); } catch {
759
+ discard(creq);
760
+ denyRes(cres, 403, 'denied: floor: host not checkable');
761
+ return;
762
+ }
749
763
  /** @type {RequestCtx} */
750
764
  const ctx = { agent, method, url: urlStr, headers: { ...creq.headers }, creq, cres, tee,
751
765
  hasBody, chunks: [], over: false, freeWork, asked: false, status: null, heldId: null,
752
- endAsk: null, decodedHead: null };
766
+ endAsk: null, decodedHead: null, effect: null };
753
767
  // A model call is never card-scanned (user decision, Nov 2); the floor keeps every other request.
754
768
  const tool = toolFor(matcher, tools, method, urlStr, modelEndpoints);
755
769
  let cardLike = false;
756
770
  if (hasBody) {
757
771
  if (await readWorkBody(ctx)) return;
772
+ const scanCards = !models.has(tool);
758
773
  // Past 64 KB the body streams on unscanned (known gap).
759
- if (!ctx.over && !models.has(tool)) {
760
- cardLike = await scanBody(ctx);
774
+ if (ctx.over) {
775
+ if (floorHit) ctx.effect = findEffect('', undefined, 'over');
776
+ } else if (scanCards || floorHit) {
777
+ cardLike = await scanBody(ctx, scanCards, floorHit !== null);
761
778
  }
762
779
  }
763
780
  // The body never goes in the action: bareguard writes the action to its audit file.
764
781
  const action = { type: 'net', tool, url: urlStr, method, agent,
765
- cardLike, paymentPath: paymentPath(urlStr), rid };
782
+ cardLike, paymentPath: paymentPath(urlStr), rid,
783
+ ...(floorHit ? { floor: floorHit.kind, floorEntry: floorHit.entry } : {}) };
766
784
  inflightCtx.set(rid, ctx);
767
785
  const g = await gateOf(agent);
768
786
  const d = await decideAction(g, action);
@@ -860,13 +878,17 @@ export function createProxy(opts) {
860
878
  * body or its decoded view outlives the scan (same reason as `readWorkBody`).
861
879
  *
862
880
  * @param {RequestCtx} ctx request context, chunks already read
863
- * @returns {Promise<boolean>} true when the body looks like a card number
881
+ * @param {boolean} cards scan for card numbers (a model call is not scanned)
882
+ * @param {boolean} effect also find the effect fields (a floor request) and keep only that small result on `ctx.effect`
883
+ * @returns {Promise<boolean>} true when `cards` and the body looks like a card number
864
884
  */
865
- async function scanBody(ctx) {
885
+ async function scanBody(ctx, cards, effect) {
866
886
  const body = Buffer.concat(ctx.chunks);
867
887
  const view = await viewBody(body, ctx.headers);
868
888
  // A copy, never a subarray: a subarray would keep the whole decoded buffer alive.
869
889
  if (view.state === 'decoded' || view.state === 'truncated') ctx.decodedHead = Buffer.from(view.text.subarray(0, ASK_BODY_LIMIT));
890
+ if (effect) ctx.effect = findEffect(view.text, String(ctx.headers['content-type'] ?? ''), view.state);
891
+ if (!cards) return false;
870
892
  // The raw bytes are always scanned; decoded output is scanned as well (one scanner per buffer).
871
893
  return createCardScanner().push(body) || (view.text !== body && createCardScanner().push(view.text));
872
894
  }
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,16 +9,20 @@ 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): {
16
16
  mode: string;
17
- holdTimeoutSec: number | string;
17
+ holdTimeoutSec?: number | string;
18
18
  localLlm: string[];
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?: {
@@ -44,11 +48,15 @@ export function resolveConfig(flags?: {
44
48
  hold?: string | undefined;
45
49
  }, env?: NodeJS.ProcessEnv): {
46
50
  mode: string;
47
- holdTimeoutSec: number | string;
51
+ holdTimeoutSec?: number | string;
48
52
  localLlm: string[];
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,8 @@ 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
47
49
  * @property {number} waitingSec 0 at park; readers use the file mtime for a live value
48
50
  * @property {string|null} expiresAt ISO-8601 UTC deadline, or null when `timeoutMs: 'never'`
49
51
  */
@@ -219,6 +221,17 @@ export type AskPayload = {
219
221
  * true when the body exceeded ASK_BODY_LIMIT
220
222
  */
221
223
  truncated: boolean;
224
+ /**
225
+ * present when the request hit a domain the user listed in config `floor` (kind: which list, entry: the matching entry)
226
+ */
227
+ floor?: {
228
+ kind: "pay" | "send" | string;
229
+ entry: string;
230
+ } | undefined;
231
+ /**
232
+ * 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
233
+ */
234
+ effect?: import("./effect.js").Effect | undefined;
222
235
  /**
223
236
  * 0 at park; readers use the file mtime for a live value
224
237
  */
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,20 @@
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 }} 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;
2
18
  /**
3
19
  * Plain-language lines for one ask record. Every agent-controlled byte goes
4
20
  * through `safe()`.
@@ -10,10 +26,11 @@
10
26
  */
11
27
  export function questionLines(ask: AskRecord, now?: number, color?: boolean): string[];
12
28
  /**
13
- * The terminal prompt. One question open at a time. `ask()` opens a question
14
- * and returns true, or returns false when one is already open (or the prompt
15
- * is closed) so the caller prints the plain `ask` line instead; `decided()`
16
- * closes the question when the hold ended some other way, `close()` releases
29
+ * The terminal prompt. It owns one hold from its question to the proxy's
30
+ * verdict. `ask()` opens a question and returns true, or returns false when a
31
+ * hold is still current (asking or awaiting its verdict) or the prompt is
32
+ * closed, so the caller prints the plain `ask` line instead; `decided()`
33
+ * ends the current hold with its outcome line, `close()` releases
17
34
  * `input`.
18
35
  *
19
36
  * @param {{ input: import('node:stream').Readable, output: { write: (s: string) => unknown }, color?: boolean, answer: (id: string, decision: 'allow'|'deny', reason?: string) => boolean|void }} opts streams and the answer writer
@@ -55,4 +72,9 @@ export type AskRecord = {
55
72
  letter: string;
56
73
  bodyPreview?: string;
57
74
  expiresAt?: string | null;
75
+ floor?: {
76
+ kind: string;
77
+ entry: string;
78
+ };
79
+ effect?: import("./effect.js").Effect;
58
80
  };