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/CHANGELOG.md CHANGED
@@ -4,6 +4,39 @@ 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
+
32
+ ## [0.12.0] - 2026-11-12
33
+
34
+ ### Changed
35
+
36
+ - `sbx run` on a terminal answers at once with `→ sent` and appends the outcome when the proxy decides (`✓ allowed`, `✗ denied`, `✗ timed out (denied)`, ...): a `y` typed just before the `--hold` deadline shows `✗ timed out (denied)`, never `✓ allowed`, and no plain `decided` line repeats it. An answer that cannot be written prints `✗ not sent (<code>)` instead of nothing.
37
+ - After `✗ not sent` the same question stays open for a retry; a second hold never prints into an open `→ sent` line.
38
+ - `sbx run` without a terminal (cron, CI, `--json`, stdin or stderr redirected) now denies a held request after 3 minutes instead of waiting forever; with a terminal it still waits. `--hold` or `holdTimeoutSec` sets either.
39
+
7
40
  ## [0.11.0] - 2026-11-11
8
41
 
9
42
  ### Added
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,12 +77,28 @@ 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 |
81
99
  |---|---|
82
100
  | Keys and credentials: `~/.ssh`, `~/.gnupg`, `~/.password-store`, `~/secrets`, keyrings, browser profiles, `~/.aws`, `~/.azure`, `~/.config/gcloud`, `~/.kube`, `~/.docker`, `~/.config/gh`, `~/.config/op`, `~/.netrc`, `~/.npmrc`, `~/.pypirc`, `~/.git-credentials`, `~/.cargo/credentials.toml` | masked inside the sandbox: they read as empty |
83
- | Your environment | cleared; only a short safe list (`TERM`, `LANG`, `LC_*`, `TZ`, `USER`, `SHELL`, ...) and names you list in `env.pass` get in (names like `*_TOKEN`, `*_KEY` are refused) |
101
+ | Your environment | cleared; only a short safe list (`TERM`, `LANG`, `LC_*`, `TZ`, `USER`, `SHELL`, ...) and names you list in `env.pass` get in (names like `*_TOKEN`, `*_KEY` are refused; set a harmless one such as `XKB_KEYMAP` with `env.set`) |
84
102
  | Any network but the proxy | the sandbox has no network of its own. `--noproxy`, unset proxy env, a direct IP or a raw socket fail closed; UDP and non-HTTP traffic are denied |
85
103
  | Private and local addresses | the proxy checks every resolved IP (IPv6 spellings of IPv4 included) and refuses private ranges and names that don't resolve |
86
104
  | Real API keys | the agent holds a per-run placeholder; the proxy swaps in the real key after the gate allows the request, over HTTPS, and only for the key's bound hosts (see below) |
@@ -97,10 +115,10 @@ A held request asks in the terminal where you ran `sbx run` (`y` allows, anythin
97
115
  Data: {"amount":35000,"currency":"usd"}
98
116
  Allow? [y/N] (hold h1)
99
117
  y
100
- ✓ allowed
118
+ → sent ✓ allowed
101
119
  ```
102
120
 
103
- Name the sandbox (`--name docs-bot`) and a second terminal can answer too: `sbx pending --name docs-bot`, `sbx approve h1 --name docs-bot`. A hold waits until you answer; for unattended runs (cron, CI) pass `--hold <seconds>`, and a timeout is a deny. One held request per agent at a time; up to 16 more wait in line.
121
+ Name the sandbox (`--name docs-bot`) and a second terminal can answer too: `sbx pending --name docs-bot`, `sbx approve h1 --name docs-bot`. A hold waits until you answer at a terminal; without one (cron, CI, `--json`, stdin or stderr redirected) it is denied after 3 minutes. `--hold <seconds|never>` or `holdTimeoutSec` changes either, and a timeout is a deny. One held request per agent at a time; up to 16 more wait in line.
104
122
 
105
123
  Demo A's end-of-run summary (from the recorded take):
106
124
 
@@ -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
 
@@ -60,7 +60,10 @@ When a request needs a decision (see "Modes and the gate" below), it parks.
60
60
  the sandbox name, what it wants to do and why, the URL, a masked body
61
61
  preview, then `Allow? [y/N] (hold h3)`. `y` or `yes` allows; anything else, Enter
62
62
  included, denies with `denied at the terminal`. A line typed before a question
63
- appears answers nothing. Name the sandbox with `sbx run --name docs-bot`: the
63
+ appears answers nothing. `→ sent` prints at once when your answer is written, and the
64
+ outcome is appended on the same line when the proxy decides (`✓ allowed`, `✗ denied`,
65
+ `✗ timed out (denied)`, `✗ agent gone (denied)`, `✗ sandbox closed (denied)`, `✓`/`✗ answered
66
+ elsewhere`), so a `y` that arrives after the deadline shows `→ sent ✗ timed out (denied)`. Name the sandbox with `sbx run --name docs-bot`: the
64
67
  name is the agent name and picks the runtime dir
65
68
  (`$XDG_RUNTIME_DIR/barebox/<name>`, else `<tmpdir>/sbx-<uid>/<name>`, kept
66
69
  after the run), and every other command takes `--name docs-bot` instead of
@@ -68,7 +71,7 @@ after the run), and every other command takes `--name docs-bot` instead of
68
71
 
69
72
  A second terminal can answer at the same time through the file checkpoint
70
73
  (`<runtime>/asks` + `<runtime>/answers`); the first answer wins and the
71
- prompt says `answered elsewhere`:
74
+ prompt prints `✓ answered elsewhere (allowed)` or `✗ answered elsewhere (<reason>)` when the proxy decides. A write that fails prints `✗ not sent (<code>), try again:` with the same question, and the next line typed retries; the hold also stays open for another terminal or its deadline:
72
75
 
73
76
  ```bash
74
77
  npx sbx pending --name docs-bot
@@ -80,7 +83,7 @@ SBX_RUNTIME=/tmp/sbx npx sbx approve h1
80
83
  SBX_RUNTIME=/tmp/sbx npx sbx deny h2 "reason here"
81
84
  ```
82
85
 
83
- Held requests wait, counting from arrival, until a deadline: the library's default is 120 s (`createHolds`/`createProxy`; `'never'` supported), while `sbx run` waits until answered by default (`holdTimeoutSec` `"never"`; `--hold <seconds|never>` or the config key sets a deadline):
86
+ Held requests wait, counting from arrival, until a deadline: the library's default is 120 s (`createHolds`/`createProxy`; `'never'` supported), while `sbx run` waits until answered when a terminal is attached and denies after 180 s without one (`--hold <seconds|never>` or `holdTimeoutSec` overrides either):
84
87
  time spent in line and reading the body counts too, and a request past its
85
88
  deadline is denied `hold timeout` whether waiting, sending, or parked. Each
86
89
  agent holds at most one request being read or parked; later ones wait in
@@ -90,7 +93,7 @@ need the proxy to be alive: with no live proxy on the runtime `sbx pending`,
90
93
  `approve` and `deny` exit 1 and say so, because nothing would read the answer.
91
94
  `approve` and `deny` wait briefly to learn what the proxy did: an answer for a hold that already ended exits 1 with `<id> already decided`; if the proxy has not read it yet they print `answer written, the proxy has not read it yet` and still report `approved` / `denied`. `--name` for a sandbox that never ran exits 1 with `no sandbox named <n>` and creates nothing. The terminal question is colored only when stderr is a TTY and `NO_COLOR` is unset.
92
95
 
93
- Unattended runs (cron, CI, no TTY, `--json`): nobody answers on the terminal, and `sbx run` waits forever by default, so a held request would hang the run. Pass `--hold <seconds>` (or set `holdTimeoutSec`) so a hold times out as a deny.
96
+ Unattended runs (cron, CI, `--json`, stdin or stderr not a TTY; redirecting only stdout still counts as a terminal): nobody answers on the terminal, so by default a held request is denied after 180 s instead of hanging the run. Pass `--hold <seconds|never>` (or set `holdTimeoutSec`) to change that, with or without a terminal.
94
97
 
95
98
  ## One call: `run()` and `sbx run`
96
99
 
@@ -124,11 +127,11 @@ Its exit code mirrors the agent's.
124
127
 
125
128
  `sbx run` reads one optional config file,
126
129
  `${XDG_CONFIG_HOME:-$HOME/.config}/barebox/config.json`, with keys `mode`,
127
- `holdTimeoutSec` (positive integer or `"never"`; default `"never"`, overridden per run by `--hold`), `heldBodyMaxMB`
130
+ `holdTimeoutSec` (positive integer or `"never"`; unset: `"never"` with a terminal, 180 without; overridden per run by `--hold`), `heldBodyMaxMB`
128
131
  (positive integer) and `localLlm` (array of `"host:port"`). A flag beats the file, the file beats the default; an
129
132
  unknown key, bad value or bad JSON exits 2 naming the file and key. The file
130
133
  is hidden inside the sandbox wherever it resolves. The library does not read it.
131
- 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".
132
135
 
133
136
  ## Modes and the gate
134
137
 
@@ -146,10 +149,11 @@ table. The mode picks the agent's rwx letters:
146
149
  is denied in every mode (`rwx.unlisted`). Without a label a request is the tool
147
150
  `http.<METHOD>` (see "Labels and model endpoints"). The gate runs with empty
148
151
  content patterns, so no word in a URL or method asks or denies on its own: the
149
- 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,
150
153
  `cardLike` (a body of 64 KB or less holding a card number: 13-19 digits,
151
154
  optional single space or dash, first digit 2-6, Luhn-valid) and `paymentPath`
152
- (`/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,
153
157
  `trust` included. Nothing is denied because of a card. One exception: a call
154
158
  to a model endpoint (see "Labels and model endpoints") is never card-scanned,
155
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.11.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
@@ -7,7 +7,7 @@
7
7
  // cwd-relative default.
8
8
  //
9
9
  // Settings (mode, holdTimeoutSec, heldBodyMaxMB, localLlm) come from the one config file, see config.js;
10
- // a flag beats the file. A bad file is a usage-class error (exit 2).
10
+ // a flag beats the file, the file beats the default (holdTimeoutSec unset: wait with a terminal, 180 s then deny without). A bad file is a usage-class error (exit 2).
11
11
  //
12
12
  // With a terminal (stdin and stderr TTYs, no --json) `sbx run` asks each hold in place (prompt.js);
13
13
  // `--name <n>` names the sandbox (agent name + runtime dir, runtime.js namedRuntime) and every
@@ -38,11 +38,13 @@ 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';
45
45
 
46
+ // Seconds a held request waits when no one is at a terminal and neither --hold nor holdTimeoutSec is set.
47
+ const HOLD_NO_TERMINAL_SEC = 180;
46
48
  const USAGE = 'usage: sbx [--help] | run [--mode ask|auto|trust] [--hold <seconds|never>] [--name <n>] [--json] [--overlay] -- <cmd> [...] | pending|diff|rollback [--name <n>] | approve <id> [--name <n>] | deny <id> [reason] [--name <n>] | commit [--name <n>] [--skip-conflicts] (--name replaces SBX_RUNTIME; --agent stays for diff/commit/rollback)';
47
49
 
48
50
  /** Hold ids the CLI accepts: `h<n>` only. Anything else is a usage error, never a path. */
@@ -216,7 +218,7 @@ async function run(args) {
216
218
  usage();
217
219
  }
218
220
  if (values.mode !== undefined && !MODES.includes(values.mode)) usage();
219
- /** @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[] }> }} */
220
222
  let cfg;
221
223
  try {
222
224
  cfg = resolveConfig({ mode: values.mode, hold: values.hold });
@@ -233,9 +235,14 @@ async function run(args) {
233
235
  err(e instanceof Error ? e.message : String(e));
234
236
  process.exit(2);
235
237
  }
236
- const timeoutMs = cfg.holdTimeoutSec === 'never' ? 'never' : Number(cfg.holdTimeoutSec) * 1000;
237
238
  if (!command.length) usage();
238
239
  const json = values.json ?? false;
240
+ // A person at this terminal (stdin and stderr are TTYs, not --json) answers
241
+ // holds here; the file channel stays on, so `sbx approve` still works too.
242
+ const interactive = !json && !!process.stdin.isTTY && !!process.stderr.isTTY;
243
+ // No --hold and no holdTimeoutSec: wait for the person at a terminal, else deny after 180 s.
244
+ const hold = cfg.holdTimeoutSec ?? (interactive ? 'never' : HOLD_NO_TERMINAL_SEC);
245
+ const timeoutMs = hold === 'never' ? 'never' : Number(hold) * 1000;
239
246
  const overlay = values.overlay ?? false;
240
247
  const name = values.name;
241
248
  if (name !== undefined) {
@@ -250,10 +257,8 @@ async function run(args) {
250
257
  for (const k of keys) if (c[k] != null) c[k] = safe(c[k]);
251
258
  return c;
252
259
  };
253
- // A person at this terminal (stdin and stderr are TTYs, not --json) answers
254
- // holds here; the file channel stays on, so `sbx approve` still works too.
255
260
  const errColor = !!process.stderr.isTTY && !process.env.NO_COLOR;
256
- const prompt = !json && process.stdin.isTTY && process.stderr.isTTY
261
+ const prompt = interactive
257
262
  ? createTerminalPrompt({
258
263
  input: process.stdin,
259
264
  output: process.stderr,
@@ -261,13 +266,15 @@ async function run(args) {
261
266
  answer: (id, decision, reason) => writeAnswer(runtimePaths(runtime), id, decision, reason),
262
267
  })
263
268
  : null;
269
+ const prompted = new Set(); // holds the prompt showed: their answer is shown there too
264
270
  const emitAsk = (h) => {
265
- if (prompt?.ask(h)) return;
271
+ if (prompt?.ask(h)) { prompted.add(h.id); return; }
266
272
  const c = clean(h, ['id', 'agent', 'method', 'url', 'rule', 'bodyPreview']);
267
273
  if (json) out(JSON.stringify({ ev: 'ask', ...c }));
268
- 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)}`);
269
275
  };
270
276
  const emitDecided = (e) => {
277
+ if (!json && prompted.delete(e.id)) return;
271
278
  const c = clean(e, ['id', 'decision', 'reason']);
272
279
  if (json) out(JSON.stringify({ ev: 'decided', id: c.id, decision: c.decision, reason: c.reason }));
273
280
  else out(`decided ${c.id} ${c.decision}${c.reason ? ` (${c.reason})` : ''}`);
@@ -288,7 +295,7 @@ async function run(args) {
288
295
  result = await sandboxRun({
289
296
  runtime, proj: process.cwd(), command, mode, timeoutMs,
290
297
  ...(name !== undefined ? { agent: name } : {}),
291
- allowLocal: cfg.localLlm, labels, secrets: cfg.secrets, env: cfg.env,
298
+ allowLocal: cfg.localLlm, floor: cfg.floor, labels, secrets: cfg.secrets, env: cfg.env,
292
299
  ...(cfg.heldBodyMaxMB ? { heldBodyMaxBytes: cfg.heldBodyMaxMB * 1048576 } : {}),
293
300
  unsafeTestOnly: { allowLoopback: process.env.SBX_UNSAFE_TEST_ALLOW_LOOPBACK === '1' },
294
301
  overlay,
@@ -419,7 +426,8 @@ async function pending(rest) {
419
426
  // Agent-controlled bytes (URL, rule, body preview): sanitized before
420
427
  // they reach the approver's terminal (see `safe`).
421
428
  const body = safe(h.bodyPreview).replace(/\s+/g, ' ').slice(0, 200);
422
- 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);
423
431
  }
424
432
  process.exit(0);
425
433
  }
package/src/config.js CHANGED
@@ -6,8 +6,9 @@ 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
- const DEFAULTS = { mode: 'auto', holdTimeoutSec: 'never', localLlm: [], labels: [], tenants: {} };
11
+ const DEFAULTS = { mode: 'auto', localLlm: [], labels: [], tenants: {} };
11
12
 
12
13
  /** One `host:port` (host without a colon, port 1-65535). @param {unknown} v @returns {boolean} */
13
14
  const isHostPort = (v) => {
@@ -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))),