barebox 0.12.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/CHANGELOG.md CHANGED
@@ -4,6 +4,31 @@ All notable changes to this project will be documented in this file.
4
4
 
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
6
6
 
7
+ ## [0.13.0] - 2026-11-30
8
+
9
+ ### Docs
10
+
11
+ - README: the suite section is now a short map of the bare suite (Hands / Rails / Apps) plus what this pairs well with, linking the full list on github.com/hamr0.
12
+
13
+ ### Added
14
+
15
+ - `floor` config key (`floor.pay`, `floor.send`): your own payment and email or chat domains ask in every mode, `trust` included, for any write (a method other than GET or HEAD) to a listed host or `*.domain`, or to a listed `"METHOD host/path"` endpoint. The question shows every recipient, amount and currency field found in a JSON or form body, labelled by its path (shallowest first), or says why none was read (body over 64 KB, multipart, undecoded encoding, bad JSON). No built-in entries: only what you list. A host the floor cannot check is refused with 403. The audit records the floor kind and entry, never body values.
16
+ - New README demo GIF (`assets/demo.gif`): one unedited take of a scripted agent in a real `sbx run --mode auto --hold 8`, showing a free search, a payment allowed (real key swapped in only after the yes), an email allowed, a second payment denied, an unanswered upload denied after 8 s, and the end-of-run report. `examples/demo-gif/record.sh` records a take and fails unless the audit shows exactly those outcomes; `render.mjs` turns it into the GIF with ffmpeg (no new dependency).
17
+
18
+ ### Changed
19
+
20
+ - bareguard pin 0.34.0 to 0.38.0 (the precompiled host-pattern matcher the floor uses).
21
+
22
+ ### Security
23
+
24
+ - The floor's effect list cannot hide the real recipient: up to 5 recipient, amount or currency fields are all listed, and more than 5 lists none ("more than 5 fields") instead of a first few. Each list is capped while the body is read, and paths are cut at 200 characters, so a 64 KB body cannot make the question slow or large.
25
+ - A floor endpoint entry matches the path however it is spelled: case, `%XX` of unreserved characters and `;params` no longer slip past it (`/v1/%63harges`, `/V1/charges`, `/v1/charges;x=1`). The model-endpoint list stays exact.
26
+ - `sbx pending` and the non-terminal `ask` line name the floor entry (`floor=pay entry=...`), and `sbx pending` prints the recipient, amount and currency lines, so an approver in a second terminal sees what the same-terminal question shows.
27
+
28
+ ### Removed
29
+
30
+ - `assets/demo-a.gif` (the Nov 3 live take stays as `assets/demo-a.webm`, linked from the README).
31
+
7
32
  ## [0.12.0] - 2026-11-12
8
33
 
9
34
  ### Changed
package/README.md CHANGED
@@ -17,9 +17,11 @@
17
17
  <img src="https://img.shields.io/badge/platform-Linux-2a4f8c" alt="platform: Linux">
18
18
  </p>
19
19
 
20
- ![Demo A: a real agent books a trip inside barebox. Reads and model calls go out free, a payment waits for a yes and only then gets the real key, a no never leaves the machine](assets/demo-a.gif)
20
+ <img src="assets/demo.gif" width="800" alt="A scripted agent books a trip inside barebox: the search goes out free, a payment asks and gets the real key only after a yes, an email is allowed, a second payment is denied and never leaves, an unanswered upload is denied after 8 s, then the report of what barebox decided">
21
21
 
22
- Demo A, a live unedited run: Meta's muse model books a trip. 31 requests, 23 went out with no question, 8 stopped for a person (3 allowed, 5 denied); the real payment key reached the server once, after a yes. Full captioned take: [assets/demo-a.webm](assets/demo-a.webm).
22
+ A scripted agent, real barebox (v0.12.0), one unedited take: a free search, a payment allowed (the real key goes in only after the yes), an email allowed, an unexpected second payment denied (403, nothing left), an upload nobody answered denied after 8 s, then the report from barebox's audit log. Record and render it yourself (needs ffmpeg): `bash examples/demo-gif/record.sh && node examples/demo-gif/render.mjs examples/demo-gif/take examples/demo-gif/captions.json assets/demo.gif`.
23
+
24
+ With a real model: Meta's muse books a trip, a live unedited run (Nov 3). 31 requests, 23 went out with no question, 8 stopped for a person (3 allowed, 5 denied); the real payment key reached the server once, after a yes. Captioned take: [assets/demo-a.webm](assets/demo-a.webm).
23
25
 
24
26
  **Replay it** (Linux, from a clone; needs network, httpbin.org stands in for the real services):
25
27
 
@@ -75,6 +77,22 @@ The mode (`sbx run --mode ...`) picks which letters pass without asking:
75
77
 
76
78
  **The floor asks in every mode, `trust` included:** a card number (Luhn) in a body of 64 KB or less, or a payment path (`/checkout`, `/payment`, `/orders`, `/purchase`).
77
79
 
80
+ **Your own pay and send domains ask too.** List the payment and email or chat domains you use under `floor` in `~/.config/barebox/config.json`. Any write (a method other than `GET` or `HEAD`) to a listed domain asks in every mode, `trust` included; reads keep their letter and mode. barebox ships **no built-in entries**: it promises only what you list.
81
+
82
+ ```json
83
+ {
84
+ "floor": {
85
+ "pay": ["api.stripe.com", "*.paypal.com", "*.adyen.com", "*.adyenpayments.com", "connect.squareup.com"],
86
+ "send": ["api.sendgrid.com", "api.mailgun.net", "api.postmarkapp.com", "api.resend.com", "hooks.slack.com",
87
+ "POST slack.com/api/chat.postMessage",
88
+ "POST gmail.googleapis.com/gmail/v1/users/{userId}/messages/send",
89
+ "POST api.twilio.com/2010-04-01/Accounts/{sid}/Messages.json"]
90
+ }
91
+ }
92
+ ```
93
+
94
+ An entry is a host, `*.domain` (subdomains only, never the bare domain), or `"METHOD host/path"` for one endpoint on a shared host, so other writes there keep their letter. The question names the recipient, amount and currency found in the body by common field names (`to`, `email`, `amount`, `currency` and a few more), each labelled with where it sits in the body, so a decoy field cannot hide the real one: up to 5 fields of a kind are all listed; more than 5 lists none ("more than 5 fields"), because then barebox cannot tell you which is the real one. An endpoint entry matches the path however it is spelled: upper or lower case, `%XX` for a plain letter, digit or `-._~`, and `;params` on a segment all hit (`%2F` does not). Known limit: a suffix such as `.json` is a different path, so list the suffix you use. `sbx pending` shows the same floor entry and the recipient, amount and currency lines under each held request. When the body cannot be read (over 64 KB, multipart, an encoding barebox does not decode, bad JSON) the question says so and still asks; nothing is denied for that. A listed domain can't be loosened by a mode.
95
+
78
96
  ## What it blocks by default
79
97
 
80
98
  | Blocked | How |
@@ -169,27 +187,13 @@ npm install barebox
169
187
 
170
188
  Linux. Node.js >= 22.21, `bwrap`, `socat`, `openssl`; bubblewrap >= 0.11.0 for `--overlay` (Ubuntu 24.04 ships 0.9.0). Two dependencies, [bareguard](https://npmjs.com/package/bareguard) and [rwxmap](https://npmjs.com/package/rwxmap), pinned exactly. The `sbx` CLI comes with it; the API is in [`barebox.context.md`](barebox.context.md).
171
189
 
172
- ## The bare ecosystem
173
-
174
- Local-first, composable agent infrastructure. Same API patterns throughout —
175
- mix and match, each module works standalone.
176
-
177
- **Core** — the brain, the gate, the walls, the memory.
178
-
179
- - **[bareagent](https://npmjs.com/package/bare-agent)** — the think→act→observe loop. *Goal in → coordinated actions out.* Replaces LangChain, CrewAI, AutoGen.
180
- - **[bareguard](https://npmjs.com/package/bareguard)** — the single gate every action passes through. *Action in → allow / deny / ask-a-human out. Work in → green / red.* Replaces hand-rolled allowlists and scattered policy code.
181
- - **[barebox](https://github.com/hamr0/barebox)** — the walls and the front door, this repo. *Agent in → contained run out: writes undoable, irreversible actions held for a human.* Replaces Docker/VM isolation and approve-everything prompts.
182
- - **[litectx](https://npmjs.com/package/litectx)** — tree-sitter code + memory graph with activation decay, plus lightweight context engineering (write · select · compress · isolate). *Query in → ranked context out.*
183
-
184
- **Add-on for bareguard** — labels API operations for the gate.
185
-
186
- - **[rwxmap](https://github.com/hamr0/rwxmap)** [WIP] — labels every OpenAPI operation r/w/x as a starting point, marked for review. *API spec in → per-operation letter out.* barebox's doorman uses its labels for known APIs.
190
+ ## bare suite
187
191
 
188
- **Optional reach** — give the agent hands.
192
+ - **Hands** · [barebrowse](https://github.com/hamr0/barebrowse) · [baremobile](https://github.com/hamr0/baremobile) · [beeperbox](https://github.com/hamr0/beeperbox)
193
+ - **Rails** · [bareagent](https://github.com/hamr0/bareagent) · [bareguard](https://github.com/hamr0/bareguard) · **barebox** · [litectx](https://github.com/hamr0/litectx)
194
+ - **Apps** · [fwdloop](https://github.com/hamr0/fwdloop) · [bareloop](https://github.com/hamr0/bareloop)
189
195
 
190
- - **[barebrowse](https://npmjs.com/package/barebrowse)** — a real browser for agents. *URL in → pruned snapshot out.* Replaces Playwright, Selenium, Puppeteer.
191
- - **[baremobile](https://npmjs.com/package/baremobile)** — Android + iOS device control. *Screen in → pruned snapshot out.* Replaces Appium, Espresso, XCUITest.
192
- - **[beeperbox](https://github.com/hamr0/beeperbox)** — 50+ messaging networks via one MCP server (headless Beeper Desktop in Docker). *Chat in → unified message stream out.* Replaces Twilio, per-platform bot APIs.
196
+ Built on [bareguard](https://github.com/hamr0/bareguard) and [rwxmap](https://github.com/hamr0/rwxmap). → [The whole suite](https://github.com/hamr0)
193
197
 
194
198
  ## License
195
199
 
@@ -131,7 +131,7 @@ Its exit code mirrors the agent's.
131
131
  (positive integer) and `localLlm` (array of `"host:port"`). A flag beats the file, the file beats the default; an
132
132
  unknown key, bad value or bad JSON exits 2 naming the file and key. The file
133
133
  is hidden inside the sandbox wherever it resolves. The library does not read it.
134
- Two more keys, `labels` and `tenants`, are described under "Labels and model endpoints". Two more, `env` and `secrets`, are described under "Keys the agent never holds".
134
+ Two more keys, `labels` and `tenants`, are described under "Labels and model endpoints". `floor` (`{ pay?: string[], send?: string[] }`) lists your own payment and send domains: an entry is a host, `*.domain` (subdomains only) or `"METHOD host/path"`; any write to a listed host, or the one listed endpoint, asks in every mode, `trust` included, and the question shows the recipient, amount and currency fields found in the body (labelled by path), or says why none was read. Each of the three lists in the effect holds at most 6 fields, and 6 means "more than 5": a list of more than 5 is shown as "more than 5 fields", none listed. Endpoint entries match the request path case-insensitively, with `%XX` of unreserved characters decoded and `;params` dropped; `sbx pending` shows the floor entry and the effect lines. There are no built-in entries; an absent `floor` lists nothing. Two more, `env` and `secrets`, are described under "Keys the agent never holds".
135
135
 
136
136
  ## Modes and the gate
137
137
 
@@ -149,10 +149,11 @@ table. The mode picks the agent's rwx letters:
149
149
  is denied in every mode (`rwx.unlisted`). Without a label a request is the tool
150
150
  `http.<METHOD>` (see "Labels and model endpoints"). The gate runs with empty
151
151
  content patterns, so no word in a URL or method asks or denies on its own: the
152
- mode letters, the labels and the floor decide. The floor is two bareguard flags,
152
+ mode letters, the labels and the floor decide. The floor is three bareguard flags,
153
153
  `cardLike` (a body of 64 KB or less holding a card number: 13-19 digits,
154
154
  optional single space or dash, first digit 2-6, Luhn-valid) and `paymentPath`
155
- (`/checkout`, `/payment`, `/orders`, `/purchase`); both ask in every mode,
155
+ (`/checkout`, `/payment`, `/orders`, `/purchase`), and `floor` (`pay` or
156
+ `send`: the request hit a `floor` config entry); all three ask in every mode,
156
157
  `trust` included. Nothing is denied because of a card. One exception: a call
157
158
  to a model endpoint (see "Labels and model endpoints") is never card-scanned,
158
159
  in any mode. `gzip` and `deflate` bodies are decoded for the scan and the ask preview (decoded output capped at 64 KB; the upstream still gets the original bytes); `br` and other encodings are scanned as sent. Bodies over 64 KB stream through unscanned. The body never enters the gate's action.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barebox",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "Lightweight local sandbox for AI agents: every write undoable, nothing leaves the machine without passing the doorman.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -50,7 +50,7 @@
50
50
  "typescript": "5"
51
51
  },
52
52
  "dependencies": {
53
- "bareguard": "0.34.0",
53
+ "bareguard": "0.38.0",
54
54
  "rwxmap": "0.11.1"
55
55
  }
56
56
  }
package/src/cli.js CHANGED
@@ -38,7 +38,7 @@ import { resolveConfig } from './config.js';
38
38
  import { loadLabels } from './labels.js';
39
39
  import { MODES } from './policy.js';
40
40
  import { run as sandboxRun } from './run.js';
41
- import { createTerminalPrompt, paint, ANSI } from './prompt.js';
41
+ import { createTerminalPrompt, paint, ANSI, effectLines, floorTail } from './prompt.js';
42
42
  import { DEFAULT_POLL_MS } from './holds.js';
43
43
  import { diffOverlay, commitOverlay, rollbackOverlay } from './overlay.js';
44
44
  import { assertAgentName, createRuntime, namedRuntime, hostNode, runtimePaths, runtimeLive, safe, shellQuote } from './runtime.js';
@@ -218,7 +218,7 @@ async function run(args) {
218
218
  usage();
219
219
  }
220
220
  if (values.mode !== undefined && !MODES.includes(values.mode)) usage();
221
- /** @type {{ 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[] }> }} */
221
+ /** @type {{ 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[] }> }} */
222
222
  let cfg;
223
223
  try {
224
224
  cfg = resolveConfig({ mode: values.mode, hold: values.hold });
@@ -271,7 +271,7 @@ async function run(args) {
271
271
  if (prompt?.ask(h)) { prompted.add(h.id); return; }
272
272
  const c = clean(h, ['id', 'agent', 'method', 'url', 'rule', 'bodyPreview']);
273
273
  if (json) out(JSON.stringify({ ev: 'ask', ...c }));
274
- else out(`ask ${c.id} ${c.agent} ${c.method} ${c.url} rule=${c.rule}`);
274
+ else out(`ask ${c.id} ${c.agent} ${c.method} ${c.url} rule=${c.rule}${floorTail(h)}`);
275
275
  };
276
276
  const emitDecided = (e) => {
277
277
  if (!json && prompted.delete(e.id)) return;
@@ -295,7 +295,7 @@ async function run(args) {
295
295
  result = await sandboxRun({
296
296
  runtime, proj: process.cwd(), command, mode, timeoutMs,
297
297
  ...(name !== undefined ? { agent: name } : {}),
298
- allowLocal: cfg.localLlm, labels, secrets: cfg.secrets, env: cfg.env,
298
+ allowLocal: cfg.localLlm, floor: cfg.floor, labels, secrets: cfg.secrets, env: cfg.env,
299
299
  ...(cfg.heldBodyMaxMB ? { heldBodyMaxBytes: cfg.heldBodyMaxMB * 1048576 } : {}),
300
300
  unsafeTestOnly: { allowLoopback: process.env.SBX_UNSAFE_TEST_ALLOW_LOOPBACK === '1' },
301
301
  overlay,
@@ -426,7 +426,8 @@ async function pending(rest) {
426
426
  // Agent-controlled bytes (URL, rule, body preview): sanitized before
427
427
  // they reach the approver's terminal (see `safe`).
428
428
  const body = safe(h.bodyPreview).replace(/\s+/g, ' ').slice(0, 200);
429
- out(`${safe(h.id)} ${safe(h.agent)} ${safe(h.method)} ${safe(h.url)} (${waiting}s) rule=${safe(h.rule)} body=${body}`);
429
+ out(`${safe(h.id)} ${safe(h.agent)} ${safe(h.method)} ${safe(h.url)} (${waiting}s) rule=${safe(h.rule)}${floorTail(h)} body=${body}`);
430
+ for (const line of effectLines(h.effect, false)) out(line);
430
431
  }
431
432
  process.exit(0);
432
433
  }
package/src/config.js CHANGED
@@ -6,6 +6,7 @@ import fs from 'node:fs';
6
6
  import os from 'node:os';
7
7
  import path from 'node:path';
8
8
  import { MODES } from './policy.js';
9
+ import { floorList } from './lists.js';
9
10
 
10
11
  const DEFAULTS = { mode: 'auto', localLlm: [], labels: [], tenants: {} };
11
12
 
@@ -65,6 +66,20 @@ const checkSecrets = (v) => {
65
66
  return null;
66
67
  };
67
68
 
69
+ /** @param {unknown} v @returns {string|null} the error for a `floor` value, or null */
70
+ const checkFloor = (/** @type {any} */ v) => {
71
+ if (!isObj(v)) return 'must be an object of { pay?, send? }, each an array of hosts, "*.domain" or "METHOD host/path"';
72
+ for (const [k, list] of Object.entries(v)) {
73
+ if (k !== 'pay' && k !== 'send') return `has unknown field "${k}"`;
74
+ if (!Array.isArray(list)) return `floor.${k} must be an array`;
75
+ for (const [i, e] of list.entries()) {
76
+ if (typeof e !== 'string') return `floor.${k}[${i}] must be a string`;
77
+ try { floorList({ [k]: [e] }); } catch (err) { return `floor.${k}[${i}]: ${err instanceof Error ? err.message : String(err)}`; }
78
+ }
79
+ }
80
+ return null;
81
+ };
82
+
68
83
  /** Validators by key; each returns an error string or null. */
69
84
  const KEYS = {
70
85
  mode: (v) => (MODES.includes(v) ? null : `must be one of ${MODES.join(', ')}`),
@@ -78,6 +93,7 @@ const KEYS = {
78
93
  tenants: (v) => (v !== null && typeof v === 'object' && !Array.isArray(v)
79
94
  && Object.values(v).every((a) => Array.isArray(a) && a.length > 0 && a.every(isHttpUrl))
80
95
  ? null : 'must be an object of vendor -> non-empty array of http(s) URLs'),
96
+ floor: checkFloor,
81
97
  env: checkEnv,
82
98
  secrets: checkSecrets,
83
99
  };
@@ -97,7 +113,7 @@ export function configPath(env = process.env) {
97
113
  * Read the config file over the defaults. No file means defaults.
98
114
  *
99
115
  * @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
100
- * @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)
116
+ * @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)
101
117
  * @throws {Error} naming the file (and the key) on invalid JSON, an unknown key or a bad value
102
118
  */
103
119
  export function loadConfig(env = process.env) {
@@ -139,7 +155,7 @@ export function loadConfig(env = process.env) {
139
155
  * @param {string} [flags.mode] `--mode`
140
156
  * @param {string} [flags.hold] `--hold` (`"never"` or a positive integer of seconds, as typed)
141
157
  * @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
142
- * @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)
158
+ * @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)
143
159
  * @throws {Error} as {@link loadConfig}
144
160
  */
145
161
  export function resolveConfig(flags = {}, env = process.env) {
package/src/effect.js ADDED
@@ -0,0 +1,139 @@
1
+ // effect.js — what a request body does: the recipient, amount and currency
2
+ // fields in it, found by common field names (generic, no per-vendor rules).
3
+ // Pure (no I/O). The caller passes the body text the body view produced.
4
+ //
5
+ // The rule: return every match up to LIST_MAX + 1, shallowest path first, never
6
+ // only the first, so a decoy top-level `to` can never hide a nested real
7
+ // recipient. A list that reaches LIST_MAX + 1 means "more than LIST_MAX": the
8
+ // caller lists none of them (too many to tell the real one). A body
9
+ // that cannot be read says why in `notRead` instead of showing nothing.
10
+ import { maskCards } from './cardscan.js';
11
+
12
+ const NAMES = {
13
+ recipient: new Set(['to', 'recipient', 'recipients', 'email', 'channel', 'chat_id', 'phone']),
14
+ amount: new Set(['amount', 'value', 'amount_money', 'total']),
15
+ currency: new Set(['currency', 'currency_code']),
16
+ };
17
+ const VALUE_CAP = 200;
18
+ const PATH_CAP = 200;
19
+ /** 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. */
20
+ export const LIST_MAX = 5;
21
+
22
+ /**
23
+ * @typedef {object} EffectField
24
+ * @property {string} path where it sits in the body: `a.b[0].c` for JSON, the key as sent for a form
25
+ * @property {string} value the scalar value, masked for card numbers and cut at 200 chars
26
+ */
27
+
28
+ /**
29
+ * @typedef {object} Effect
30
+ * @property {EffectField[]} recipient
31
+ * @property {EffectField[]} amount
32
+ * @property {EffectField[]} currency
33
+ * @property {string|null} notRead why the body was not read (the three lists are then empty), else null
34
+ */
35
+
36
+ /** @param {string} reason @returns {Effect} */
37
+ function unread(reason) {
38
+ return { recipient: [], amount: [], currency: [], notRead: reason };
39
+ }
40
+
41
+ /**
42
+ * @param {string} name a key name
43
+ * @returns {'recipient'|'amount'|'currency'|null}
44
+ */
45
+ function kindOf(name) {
46
+ const n = name.toLowerCase();
47
+ for (const kind of /** @type {const} */ (['recipient', 'amount', 'currency'])) {
48
+ if (NAMES[kind].has(n)) return kind;
49
+ }
50
+ return null;
51
+ }
52
+
53
+ /**
54
+ * @param {Effect} out
55
+ * @param {'recipient'|'amount'|'currency'} kind
56
+ * @param {string} path
57
+ * @param {unknown} value
58
+ */
59
+ function add(out, kind, path, value) {
60
+ if (out[kind].length > LIST_MAX) return;
61
+ out[kind].push({ path: path.slice(0, PATH_CAP), value: maskCards(String(value)).slice(0, VALUE_CAP) });
62
+ }
63
+
64
+ /**
65
+ * Breadth-first, so matches come out shallowest first and in document order
66
+ * within a depth, and a deeply nested body cannot overflow the stack. A
67
+ * scalar inside an array is judged by the key the array sits under.
68
+ *
69
+ * @param {Effect} out
70
+ * @param {unknown} root
71
+ */
72
+ function walkJson(out, root) {
73
+ /** @type {{ v: unknown, path: string, key: string|null }[]} */
74
+ const queue = [{ v: root, path: '', key: null }];
75
+ for (let i = 0; i < queue.length; i++) {
76
+ const { v, path, key } = queue[i];
77
+ if (Array.isArray(v)) {
78
+ v.forEach((item, n) => queue.push({ v: item, path: path.length >= PATH_CAP ? path : `${path}[${n}]`.slice(0, PATH_CAP), key }));
79
+ } else if (v !== null && typeof v === 'object') {
80
+ for (const k of Object.keys(v)) {
81
+ queue.push({ v: /** @type {Record<string, unknown>} */ (v)[k], path: path.length >= PATH_CAP ? path : (path ? `${path}.${k}` : k).slice(0, PATH_CAP), key: k });
82
+ }
83
+ } else if (v !== null && key !== null) {
84
+ const kind = kindOf(key);
85
+ if (kind) add(out, kind, path, v);
86
+ }
87
+ }
88
+ }
89
+
90
+ /**
91
+ * A form key `metadata[x]` is named by its last bracket segment; the path is
92
+ * the key as sent. Shallowest first: fewer bracket segments first, stable.
93
+ *
94
+ * @param {Effect} out
95
+ * @param {string} text
96
+ */
97
+ function walkForm(out, text) {
98
+ const rows = [];
99
+ for (const [k, v] of new URLSearchParams(text)) {
100
+ const segs = k.split(/\[|\]/).filter(Boolean);
101
+ rows.push({ k, v, depth: segs.length, name: segs[segs.length - 1] ?? k });
102
+ }
103
+ rows.sort((a, b) => a.depth - b.depth);
104
+ for (const { k, v, name } of rows) {
105
+ const kind = kindOf(name);
106
+ if (kind) add(out, kind, k, v);
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Find every recipient, amount and currency field in a body.
112
+ *
113
+ * @param {string|Buffer} text the body text (decoded when the body view decoded it)
114
+ * @param {string|undefined} contentType the Content-Type header value
115
+ * @param {'plain'|'decoded'|'truncated'|'unread'|'over'} state the body view state, or `over` when the body
116
+ * is over 64 KB and was not viewed
117
+ * @returns {Effect}
118
+ */
119
+ export function findEffect(text, contentType, state) {
120
+ if (state === 'unread') return unread('encoding not decoded');
121
+ if (state === 'over') return unread('body over 64 KB');
122
+ const type = String(contentType ?? '').split(';')[0].trim().toLowerCase();
123
+ const isJson = type === 'application/json' || type.endsWith('+json');
124
+ const isForm = type === 'application/x-www-form-urlencoded';
125
+ if (!isJson && !isForm) return unread(`${type || 'no content type'} not read`);
126
+ const out = { recipient: [], amount: [], currency: [], notRead: null };
127
+ if (isForm) {
128
+ walkForm(out, String(text));
129
+ return out;
130
+ }
131
+ let parsed;
132
+ try {
133
+ parsed = JSON.parse(String(text));
134
+ } catch {
135
+ return unread('body is not valid JSON');
136
+ }
137
+ walkJson(out, parsed);
138
+ return out;
139
+ }
package/src/holds.js CHANGED
@@ -117,6 +117,8 @@ const MAX_WAITING_PER_AGENT = 16;
117
117
  * @property {string} letter the matched rwx letter, `'x'` when the ask names none
118
118
  * @property {string} bodyPreview request body preview, utf8, capped at ASK_BODY_LIMIT bytes, card numbers masked
119
119
  * @property {boolean} truncated true when the body exceeded ASK_BODY_LIMIT
120
+ * @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)
121
+ * @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
120
122
  * @property {number} waitingSec 0 at park; readers use the file mtime for a live value
121
123
  * @property {string|null} expiresAt ISO-8601 UTC deadline, or null when `timeoutMs: 'never'`
122
124
  */
@@ -383,6 +385,8 @@ export function createHolds({ log, timeoutMs = 120000,
383
385
  letter: entry.letter ?? 'x',
384
386
  bodyPreview: entry.preview,
385
387
  truncated: entry.bodyBytes > ASK_BODY_LIMIT,
388
+ ...(entry.floor ? { floor: entry.floor } : {}),
389
+ ...(entry.effect ? { effect: entry.effect } : {}),
386
390
  waitingSec: 0,
387
391
  // ISO-8601 UTC (not epoch ms): readable in `sbx pending` and logs.
388
392
  expiresAt: ms === null ? null : new Date(entry.t0 + ms).toISOString(),
@@ -521,7 +525,8 @@ export function createHolds({ log, timeoutMs = 120000,
521
525
  * parks nothing and returns `null`. Without `slot`, parks exactly as
522
526
  * before, without limit.
523
527
  *
524
- * The entry carries the masked `preview` and the full `bodyBytes`, never
528
+ * The entry also carries `floor` and `effect` for a floor request (ask file only).
529
+ * It carries the masked `preview` and the full `bodyBytes`, never
525
530
  * the body itself (the proxy spooled it to `heldFile(id)`). `finish` is
526
531
  * the proxy's resolver for the request's pending ask: the queue never
527
532
  * calls it directly, `onApprove` / `onDeny` do.
@@ -529,7 +534,7 @@ export function createHolds({ log, timeoutMs = 120000,
529
534
  * @param {object} entry queue entry
530
535
  * @returns {string|null} hold id, or null for a finished slot
531
536
  */
532
- add({ agent, method, url, preview = '', bodyBytes = 0, sock, note, letter, finish, slot, arrivedAt }) {
537
+ add({ agent, method, url, preview = '', bodyBytes = 0, effect, floor, sock, note, letter, finish, slot, arrivedAt }) {
533
538
  const hst = typeof slot === 'object' && slot !== null ? handleState.get(slot) : undefined;
534
539
  const s = slots.get(agent);
535
540
  if (slot && (!hst || hst.done || !s || s.holder !== slot)) return null;
@@ -537,7 +542,7 @@ export function createHolds({ log, timeoutMs = 120000,
537
542
  const ms = deadlineMs();
538
543
  const t0 = typeof arrivedAt === 'number' ? arrivedAt : Date.now();
539
544
  const entry = {
540
- id, agent, method, url, preview, bodyBytes, sock, note, letter, finish, t0,
545
+ id, agent, method, url, preview, bodyBytes, effect, floor, sock, note, letter, finish, t0,
541
546
  slot: null,
542
547
  timer: ms === null ? null
543
548
  : setTimeout(() => settle(id, false, 'hold timeout'), Math.max(0, ms - (Date.now() - t0))),
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`}`;
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,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,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()`.
@@ -56,4 +72,9 @@ export type AskRecord = {
56
72
  letter: string;
57
73
  bodyPreview?: string;
58
74
  expiresAt?: string | null;
75
+ floor?: {
76
+ kind: string;
77
+ entry: string;
78
+ };
79
+ effect?: import("./effect.js").Effect;
59
80
  };
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
  */
package/types/run.d.ts CHANGED
@@ -29,6 +29,7 @@
29
29
  * @property {number} [heldBodyMaxBytes] cap on a held request's body, in bytes (default 52428800); over it the request is denied
30
30
  * @property {{ matcher: any, tools: Record<string, any>, dirs?: string[] }} [labels] the loaded label files (`loadLabels`); their folders are masked from the sandbox
31
31
  * @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)
32
+ * @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`)
32
33
  * @property {object} [unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`): everything under it weakens the sandbox wall
33
34
  * @property {NodeJS.WritableStream} [stdout] where the agent's stdout goes (default process.stdout)
34
35
  * @property {NodeJS.WritableStream} [stderr] where the agent's stderr goes (default process.stderr)
@@ -52,6 +53,7 @@
52
53
  * @param {number} [opts.heldBodyMaxBytes] cap on a held request's body, in bytes (default 52428800); over it the request is denied
53
54
  * @param {{ matcher: any, tools: Record<string, any>, dirs?: string[] }|null} [opts.labels] the loaded label files (`loadLabels`); their folders are masked from the sandbox
54
55
  * @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)
56
+ * @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`)
55
57
  * @param {object|null} [opts.unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`)
56
58
  * @param {NodeJS.WritableStream|null} [opts.stdout] where the agent's stdout goes (default process.stdout)
57
59
  * @param {NodeJS.WritableStream|null} [opts.stderr] where the agent's stderr goes (default process.stderr)
@@ -66,7 +68,7 @@
66
68
  * import { run } from "barebox";
67
69
  * const { exit, asks, audit } = await run({ proj: "/tmp/proj", command: ["bash", "-c", "echo hi"] });
68
70
  */
69
- export function run({ proj, command, mode, onAsk, onEvent, runtime, agent, timeoutMs, heldBodyMaxBytes, allowLocal, labels, unsafeTestOnly, stdout, stderr, overlay, overlayIgnore, secrets, env }: {
71
+ export function run({ proj, command, mode, onAsk, onEvent, runtime, agent, timeoutMs, heldBodyMaxBytes, allowLocal, floor, labels, unsafeTestOnly, stdout, stderr, overlay, overlayIgnore, secrets, env }: {
70
72
  proj: string;
71
73
  command: string[];
72
74
  mode?: string | undefined;
@@ -82,6 +84,10 @@ export function run({ proj, command, mode, onAsk, onEvent, runtime, agent, timeo
82
84
  dirs?: string[];
83
85
  } | null | undefined;
84
86
  allowLocal?: string[] | undefined;
87
+ floor?: {
88
+ pay?: string[];
89
+ send?: string[];
90
+ } | null | undefined;
85
91
  unsafeTestOnly?: object | null;
86
92
  stdout?: NodeJS.WritableStream | null | undefined;
87
93
  stderr?: NodeJS.WritableStream | null | undefined;
@@ -204,6 +210,13 @@ export type RunOptions = {
204
210
  * exact `host:port` pairs (for example a local model server) that may pass the wall's private/loopback check (the `localLlm` setting)
205
211
  */
206
212
  allowLocal?: string[] | undefined;
213
+ /**
214
+ * the config `floor` key (M11): hosts, `*.domain` or `"METHOD host/path"` entries that ask in every mode, `trust` included (see `createProxy`)
215
+ */
216
+ floor?: {
217
+ pay?: string[];
218
+ send?: string[];
219
+ } | undefined;
207
220
  /**
208
221
  * TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`): everything under it weakens the sandbox wall
209
222
  */