barebox 0.3.0 → 0.5.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,86 @@ 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.5.0] - 2026-10-30
8
+
9
+ ### Added
10
+
11
+ - One config file, `${XDG_CONFIG_HOME:-$HOME/.config}/barebox/config.json`, read by the CLI only (`sbx run`). Keys: `mode`, `holdTimeoutSec` (a positive integer or `"never"`), `heldBodyMaxMB` (a positive integer), `localLlm` (an array of `"host:port"`). A flag beats the file, the file beats the default. An unknown key, a bad value or bad JSON makes `sbx run` exit 2, naming the file and the key.
12
+ - The card floor now looks inside bodies: an allowed request whose body is 64 KB or less and holds a card number (13-19 digits, optional single space or dash between digits, first digit 2-6, Luhn-valid) parks as an ask with rule `flags.cardLike` in every mode, `trust` included. Nothing is denied because of a card. Bodies over 64 KB stream through unchecked for cards (known gap). Each agent has one 64 KB working slot, so allowed body-carrying requests read their body one at a time per agent.
13
+ - Held bodies are spooled to `<runtime>/held/<id>` (a 0600 file in an owner-only dir), never kept in memory, and deleted whenever the hold ends. `runtimePaths` gains `heldDir` and `heldFile(id)`; `run()` gains the `heldBodyMaxBytes` option.
14
+ - The `sbx` CLI starts Node with `--max-semi-space-size=1` (caps the V8 young generation to hold proxy memory down; latency unchanged).
15
+ - `holds.js` exports `ASK_BODY_LIMIT`, `DEFAULT_HOLD_MAX_BODY` and `bodyPreview`.
16
+ - bareguard decides every request: one `gate.check()` per request, one gate per agent (and one for the TCP door's `tcp` agent), all sharing one tools table. `src/policy.js` exports `MODES` and `gateFor`. Modes: `ask` holds `r--` and asks for w and x; `auto` holds `rw-` and asks for x; `trust` holds `rwx`. GET/HEAD are r; POST/PUT/PATCH/DELETE are x; any other method is denied (`rwx.unlisted`).
17
+ - The floor is two bareguard flags, `cardLike` and `paymentPath` (`/checkout`, `/payment`, `/orders`, `/purchase`), which ask in every mode, `trust` included.
18
+ - `createProxy` option `gateFor(agent, { humanChannel })`: returns a bareguard `Gate` or any object with `async check(action)` resolving `{ outcome, rule?, reason? }`; `askHuman` from a plain object goes to the same hold queue. Without it nothing is checked.
19
+ - One audit file: `<runtime>/gate.jsonl` (`runtimePaths(runtime).audit`; `createProxy`'s `logFile` names it). Every line is in bareguard's shape. bareguard's gate lines carry the decision; a response status is a `record` line joined to its decision line by `aid`; barebox's own facts are `annotate` lines with `surface:false`, keyed by `verdict`: `deny`, `hold`, `decide`, `hold-abandoned`, `hold-queue-full`, `stale-answer`, `malformed-answer`, `body`, and `resp` in forward-all mode. A request with a body gets one `body` line with `meta: { agent, rid, bodyBytes, bodySha256 }`, joined to its gate line by `rid`.
20
+ - A runtime-level audit-only `sbx` gate takes lines for agents whose gate is not built, and every line when `gateFor` is omitted. `close()` waits up to 3 s for pending audit writes; later lines are dropped.
21
+ - `GateLike` gains optional `record`, `annotate` and `drainAnnotations`; `check` may return `aid`.
22
+ - Config key `localLlm` and the `allowLocal` option of `run()` and `createProxy()`: exact `host:port` pairs (such as a local model server) pass the wall's private/loopback check; link-local (cloud metadata) never does. `checkUpstream` takes a port argument.
23
+ - New dependency: `bareguard` 0.30.0 (exact).
24
+ - rwxmap labels. Two config keys: `labels` (folders the rwxmap CLI wrote) and `tenants` (vendor -> server URLs, replacing placeholder hosts such as `your-domain.atlassian.net`). `src/labels.js` exports `loadLabels({ labels, tenants })`, which reads each `<v>.rwxmap.review.json` for request keys (via `rwxmap/match`). The letters come only from the matching `<v>.rwxmap.json` file's `bareguard.tools`, the file you review and can edit; rwxmap's own guessed letter is never used. A bad or missing label file fails `sbx run` before any agent starts.
25
+ - The tool for a request is the label's key when a label documents it, else a model endpoint key (`r`), else `http.<METHOD>`. A key a label documents but the gate file lacks (a row you deleted) is denied (`rwx.unlisted`).
26
+ - Model endpoints are `r`: Anthropic `/v1/messages` and `/v1/messages/count_tokens`; OpenAI `/v1/chat/completions`, `/v1/responses` and `/v1/embeddings`; and on each `localLlm` host:port `/api/chat`, `/api/generate`, `/api/embed`, `/v1/chat/completions` and `/v1/completions` (http only).
27
+ - `src/policy.js` exports `buildTools`, `toolFor` and `emptyMatcher`; `gateFor` takes `tools`; `createProxy` and `run()` take `labels`; `launch()` takes `maskDirs`.
28
+ - `npm run bench:agents` (`scripts/bench-agents.mjs`): the proxy's memory at 10 / 20 / 30 / 40 agents, each at the full worst case (1 parked + 16 waiting + a filled body slot), proxy in its own process with forced GC. Exits 1 above 175 MB at up to 40 agents, or above 10 MB per sandbox walls.
29
+ - One proxy serves at most 40 agents: `addAgent` throws an error naming the limit and telling you to run another proxy. The TCP door's `tcp` agent does not count; `removeAgent` frees a place.
30
+ - Held bodies are spooled to disk and released from memory as soon as they are written (68 held bodies grow `arrayBuffers` by 0.28 MB).
31
+ - New dependency: `rwxmap` 0.8.0 (exact). Label files written before rwxmap 0.8.0 fail to load with rwxmap's "regenerate" message.
32
+
33
+ ### Changed
34
+
35
+ - The proxy memory budget is a range, about 145-175 MB in the full worst case at 40 agents (was 80 MB, retired: about 53 MB is Node's own code). barebox is for small teams: free, local and lightweight, built to assist and to connect to many tools, not to run swarms or thousands of agents. Measured about 100 / 113-120 / 127-133 / 143-172 MB at 10 / 20 / 30 / 40 agents, quiet to busy machine; normal use about 85-120 MB.
36
+ - `hold.maxBody` now defaults to 52428800 (50 MB), was 1048576. A body over the cap is denied `403 body too large to hold`.
37
+ - The audit file carries a body's length and SHA-256 only (the `body` line), never its content. The ask payload carries the 4 KB `bodyPreview` (card numbers masked except the last 4).
38
+ - Long audit fields are cut before they reach bareguard (`url` to 400 characters, `note` and `reason` to 200), so the ids that join an ask to its outcome survive bareguard's 1000-byte `meta` limit.
39
+ - A denial reads `403 denied: <rule>[: reason]`; an ask carries the gate's rule (`rwx.ask`, `flags.cardLike`, `flags.paymentPath`) and letter.
40
+ - Request bodies of 64 KB or less are read in the agent's working slot before the gate decides; a waiting request's body is spooled to `<runtime>/held/<id>` when it enters the hold line.
41
+ - `holds.add` takes `preview`, `bodyBytes` and `bodyFile` in place of `body` (internal shape).
42
+
43
+ ### Known
44
+
45
+ - Memory varies with machine load: identical 40-agent runs read 143-172 MB. Audit file size does not move it (205 MB of audit read the same as 3 MB), though the first ask of each gate still reads the whole file. Under 54,000 more allowed requests memory stayed flat (98.7–99.0 MB).
46
+ - `BAREGUARD_RWX_LETTERS` set in the shell that starts `sbx` overrides the mode letters (for example `--mode ask` then allows a POST without asking), because barebox passes no explicit letters. The sandboxed agent cannot set it.
47
+ - Held bodies can add up to about 2 GB on disk in the runtime dir (50 MB cap per request, 40 agents).
48
+ - API keys inside a body still show in the ask file's 4 KB preview.
49
+
50
+ ### Removed
51
+
52
+ - **Breaking:** the `createProxy` option `maxLogBody`.
53
+ - **Breaking:** the separate `<runtime>/audit.jsonl` and the `runtimePaths().gateAudit` path; `runtimePaths().audit` is now `gate.jsonl`.
54
+ - The `req` audit line and request-header logging: no request header is written to the audit file. `scrubSecrets` and `SENSITIVE_HEADERS` are gone; the `redact` hook stays and now shapes annotate `meta`.
55
+ - **Breaking:** `hold.shouldHold` and `hold.match` (replace with `gateFor`); `run()`'s internal `shouldHoldForMode` and `holds.js`'s `matchPath` / `ShouldHold` type.
56
+
57
+ ### Security
58
+
59
+ - The audit file holds no request header and no body content. Card numbers are masked in the ask files' 4 KB preview. Known gap: other secrets inside a body still show in the ask file's preview until bareguard redaction lands.
60
+ - The config file is hidden inside the sandbox wherever it resolves (the mask follows `XDG_CONFIG_HOME`).
61
+ - Label folders are hidden inside the sandbox the same way, so the agent cannot rewrite a letter for the next run.
62
+ - The modes decide, with no keyword patterns: the gate runs with empty content patterns, so no word in a URL or method (`remove`, `drop`, `TRUNCATE TABLE`) asks or denies on its own. Only the mode letters, the labels and the floor (card number, payment path) decide.
63
+
64
+ ## [0.4.0] - 2026-10-29
65
+
66
+ ### Changed
67
+
68
+ - Held requests are one per agent (pre-1.0 behaviour change): each agent has at most one held request being read or parked; later ones wait in line, unread, in order. At most 16 wait; the next gets `429 hold queue full`.
69
+ - The hold deadline counts from arrival (default 120 s, `never` supported), time in line and reading the body included; a request past its deadline is denied `hold timeout` whether waiting, sending, or parked.
70
+ - `proxy.removeAgent(name)` ends that agent's open connections, and its held requests end `deny` / `client gone` at once. `run()` calls it when the sandbox exits, so shutting down no longer races a held request into a `proxy closing` log line.
71
+ - An existing runtime dir you don't own (e.g. `SBX_RUNTIME=/tmp`, which 0.3.0 accepted) is now refused with a message naming the dir, its owner and a subdir to use, such as `/tmp/sbx`.
72
+ - The TCP door is one agent: every connection through `createProxy`'s TCP `port` counts as the agent `tcp` and shares one hold line. Use `addAgent` sockets (`sbx run` does) for separate lines.
73
+
74
+ ### Security
75
+
76
+ - The upstream wall checks an IPv4 embedded in IPv6 in every spelling: IPv4-mapped (`::ffff:7f00:1` as well as `::ffff:127.0.0.1`) and compat forms, uncompressed loopback (`0:0:0:0:0:0:0:1`), NAT64 `64:ff9b::/96` (local-use `64:ff9b:1::/48` denied outright) and 6to4 `2002::/16`. NAT64 and 6to4 of public sites stay reachable.
77
+ - Runtime folders are owner-only (0700) whatever the umask: the runtime root, `asks/`, `answers/` and `socks/`. A runtime dir you own is tightened to 0700.
78
+ - Each minted certificate gets a random 128-bit serial instead of a shared serial file (`ca.srl`) that concurrent mints could corrupt (a failed mint reached the agent as a 502); at most 4 mints run at once.
79
+
80
+ ### Fixed
81
+
82
+ - `createProxy` throws synchronously on an unopenable `logFile` and releases the runtime. A later audit-log write error prints one `sbx: audit log … write failed` line to stderr and the proxy keeps running.
83
+ - The `sbx run` "answer with" hint quotes the runtime path, so it is safe to copy-paste.
84
+ - Overlay hashing reads files in 1 MiB chunks, so very large files no longer exhaust memory.
85
+ - `run()` releases the runtime when the agent socket can't be created; the claim no longer stays held refusing a second `run()` on the same runtime as "in use".
86
+
7
87
  ## [0.3.0] - 2026-10-28
8
88
 
9
89
  Breaking changes (pre-1.0): the control socket, `createProxy`'s `certDir` and `allowUpstream`, `run()`'s low-level options, the hold queue's `approve`/`deny`/`size` and the top-level `allowLoopback` option are removed or moved; `runtime` is now required. Each is marked **Breaking** below.
package/README.md CHANGED
@@ -15,11 +15,8 @@
15
15
  <img src="https://img.shields.io/github/package-json/v/hamr0/barebox?label=version&color=2a4f8c" alt="version (auto from package.json)">
16
16
  <img src="https://img.shields.io/badge/license-Apache%202.0-2a4f8c" alt="license: Apache 2.0">
17
17
  <img src="https://img.shields.io/badge/platform-Linux-2a4f8c" alt="platform: Linux">
18
- <img src="https://img.shields.io/badge/status-POC-c0841a" alt="status: POC">
19
18
  </p>
20
19
 
21
- > **Status:** early. The walls (M0), HTTPS inspection (M1), hold-and-ask (M2), the one-call `run()` and file ask channel (M2.5) and the undo layer (M4) are built and measured; the decision rules (M3), key custody (M5) and the rest are not. Today's hold rule is interim: payment destinations, plus every non-GET/HEAD request in `ask` and `auto` modes. Linux only.
22
-
23
20
  ## Why
24
21
 
25
22
  Agents need real access to be useful — shell, files, network. Today you pick one of two bad options:
@@ -75,8 +72,8 @@ The agent works in your house:
75
72
  - **Walls** are [bubblewrap](https://github.com/containers/bubblewrap), unprivileged: separate net/pid/ipc/uts namespaces, read-only binds, tmpfs over locked paths.
76
73
  - **Identity** is the socket, not a header the agent could fake. One socket per agent, all into one proxy.
77
74
  - **HTTPS inspection** uses a local CA that exists only inside the sandbox; the proxy reads method, URL, headers and body, then forwards.
78
- - **The doorman's x-rules**, strongest first: card numbers in the body (Luhn) → payment domains and paths (`/checkout`, `/payment`, …) → rwxmap labels for known APIs → unknown `POST` by mode (strict: ask once per domain; normal: allow and log).
79
- - **Approvals** come from a second terminal (`sbx pending`, `sbx approve <id>`, `sbx deny <id>`). Timeout means deny, with a clear `403` reason.
75
+ - **The doorman's x-rules**, strongest first: card numbers in the body (Luhn) → payment paths (`/checkout`, `/payment`, `/orders`, `/purchase`; a list of payment domains is not built) → rwxmap labels for known APIs → every other request by its letter and the mode (`ask`, `auto`, `trust`; see `barebox.context.md`). The card and payment floor asks in every mode, `trust` included; card numbers are checked in bodies of 64 KB or less.
76
+ - **Approvals** come from a second terminal (`sbx pending`, `sbx approve <id>`, `sbx deny <id>`). Timeout means deny, with a clear `403` reason. One held request per agent at a time: later ones wait in line (16 at most, then `429 hold queue full`), and the deadline counts from arrival.
80
77
 
81
78
  ## Numbers
82
79
 
@@ -84,25 +81,27 @@ Measured, not estimated. Fedora, kernel 7.2, bubblewrap 0.12.0, Node 22.
84
81
 
85
82
  | | barebox (measured) | [srt](https://github.com/anthropic-experimental/sandbox-runtime) 0.0.81 (measured) |
86
83
  |---|---|---|
87
- | Memory per sandbox | **7.8 MB** mean, 7.9 MB max (20 concurrent) | ~100 MB |
88
- | Proxy | one shared, **~60 MB idle, ~72 MB loaded** (20 agents, within the ≤ 80 MB budget) | one per sandbox |
89
- | Start + exit | **10 ms** (M0 POC; unmeasured on the rewrite — TODO re-measure) | 1.87–2.05 s |
90
- | 20 agents | ~228 MB (rough sum: ~72 MB proxy + 20 × 7.8 MB) | ~2 GB |
84
+ | Memory per sandbox | **7.8 MB** mean, 8.0 MB max | ~100 MB (each sandbox runs its own proxy) |
85
+ | Proxy | one shared: **about 85-120 MB** in normal use; **about 100 / 113-120 / 127-133 / 145-175 MB** at 10 / 20 / 30 / 40 agents in the full worst case (each agent with 1 parked + 16 waiting + a filled body slot). The low end is a quiet machine, the high end a busy one | one per sandbox |
86
+ | Start + exit | **10 ms** (M0 POC; unmeasured on the rewrite, TODO re-measure) | 1.87-2.05 s |
87
+ | 10 agents | ~180 MB worst case (proxy + 10 x 8 MB) | ~1 GB |
88
+ | 20 agents | ~275-280 MB worst case | ~2 GB |
89
+ | 40 agents | ~465-495 MB worst case | not measured |
91
90
 
92
- Targets: shared proxy ≤ 80 MB, each extra sandbox ≤ 10 MB, 20 agents on a 2 GB VPS. Bypass attempts (`--noproxy`, unset proxy env, direct IP, host localhost) all fail closed, and a red-team script breaks each wall on purpose to prove the checks can fail. Setup, dead ends and why: [findings](docs/logs/findings.md).
91
+ barebox is for small teams: free, local and lightweight, built to assist and to connect to many tools, not to run swarms or thousands of agents. Budget: shared proxy about 145-175 MB in the full worst case at 40 agents, each extra sandbox 10 MB or less. 40 agents per proxy is the maximum and it is enforced: `addAgent` refuses the 41st with an error telling you to run another proxy. Above 40, run more proxies. Machine load moves the number. A long audit file does not: 205 MB of audit measured the same as 3 MB. Bypass attempts (`--noproxy`, unset proxy env, direct IP, host localhost) all fail closed, and a red-team script breaks each wall on purpose to prove the checks can fail. Setup, dead ends and why: [findings](docs/logs/findings.md).
93
92
 
94
93
  ## Roadmap
95
94
 
96
- | Module | What | Status |
97
- |---|---|---|
98
- | M0 | Walls + front door | **PASS** — 14/14, red-team 8/8 |
99
- | M1 | Proxy sees inside HTTPS (curl, node, python requests, git) | **PASS** — real-internet matrix + negatives, peak 63 MB |
100
- | M2 | Hold one `x` request, ask, keep everything else running | **PASS** — 9-scenario hold matrix, 120 s + never timeouts |
101
- | M3 | Decide r/w/x deterministically (rwxmap + bareguard), audit log | |
102
- | M4 | Undo layer: `diff`, `commit`, `rollback`, conflict flagging | **PASS** — paper + review flow implemented, full bwrap+unix proof in a real shell |
103
- | M5 | Keys the agent never holds | |
104
- | M6 | Scale run: 20 agents + shared proxy | |
105
- | M7 | Demos: payment held for approval; prompt-injected `~/.ssh` exfil blocked | |
95
+ | Module | What |
96
+ |---|---|
97
+ | M0 | Walls + front door |
98
+ | M1 | Proxy sees inside HTTPS (curl, node, python requests, git) |
99
+ | M2 | Hold one `x` request, ask, keep everything else running |
100
+ | M3 | Decide r/w/x deterministically (rwxmap + bareguard), audit log |
101
+ | M4 | Undo layer: `diff`, `commit`, `rollback`, conflict flagging |
102
+ | M5 | Keys the agent never holds |
103
+ | M6 | Scale run: 20 agents + shared proxy |
104
+ | M7 | Demos: payment held for approval; prompt-injected `~/.ssh` exfil blocked |
106
105
 
107
106
  M0–M2 are the go/no-go. Later: macOS (`sandbox-exec` + APFS clones), Windows via WSL2, Landlock/seccomp hardening. Full spec: [the PRD](docs/product/agent-sandbox-prd.md).
108
107
 
@@ -112,11 +111,11 @@ M0–M2 are the go/no-go. Later: macOS (`sandbox-exec` + APFS clones), Windows v
112
111
  npm install barebox
113
112
  ```
114
113
 
115
- Requires Node.js >= 22. Zero production dependencies. Needs bubblewrap >= 0.11.0 for `--overlay` / `sbx diff|commit|rollback` (Ubuntu 24.04 ships 0.9.0: build from source or use a newer distro); plain runs work with older bwrap. CI builds bubblewrap 0.12.0 from a checksum-pinned source tarball and fails if any test is skipped. The API is in [`barebox.context.md`](barebox.context.md) and `primitives.json` (both ship in the package); the `sbx` CLI comes with it.
114
+ Requires Node.js >= 22. Two production dependencies, [bareguard](https://npmjs.com/package/bareguard) (the gate) and [rwxmap](https://npmjs.com/package/rwxmap) (the labels), pinned exactly. Needs bubblewrap >= 0.11.0 for `--overlay` / `sbx diff|commit|rollback` (Ubuntu 24.04 ships 0.9.0: build from source or use a newer distro); plain runs work with older bwrap. CI builds bubblewrap 0.12.0 from a checksum-pinned source tarball and fails if any test is skipped. The API is in [`barebox.context.md`](barebox.context.md) and `primitives.json` (both ship in the package); the `sbx` CLI comes with it.
116
115
 
117
116
  ## Try the POCs
118
117
 
119
- Linux with `bwrap` (>= 0.11.0 only for the overlay), `socat`, `openssl`, Node >= 22 and Python 3. Needs a normal shell (namespaces + listening sockets), not a tool sandbox. The POCs are throwaway proofs, not the product.
118
+ Linux only, with `bwrap` (>= 0.11.0 only for the overlay), `socat`, `openssl`, Node >= 22 and Python 3. Needs a normal shell (namespaces + listening sockets), not a tool sandbox. The POCs are throwaway proofs, not the product.
120
119
 
121
120
  ```
122
121
  git clone https://github.com/hamr0/barebox && cd barebox
@@ -55,8 +55,8 @@ await proxy.close();
55
55
 
56
56
  ## Holds (human approval)
57
57
 
58
- Start the proxy with a hold rule, then decide from a second terminal
59
- through the file checkpoint (`<runtime>/asks` + `<runtime>/answers`):
58
+ When a request needs a decision (see "Modes and the gate" below), it parks.
59
+ Decide from a second terminal through the file checkpoint (`<runtime>/asks` + `<runtime>/answers`):
60
60
 
61
61
  ```bash
62
62
  SBX_RUNTIME=/tmp/sbx npx sbx pending
@@ -64,18 +64,22 @@ SBX_RUNTIME=/tmp/sbx npx sbx approve h1
64
64
  SBX_RUNTIME=/tmp/sbx npx sbx deny h2 "reason here"
65
65
  ```
66
66
 
67
- Held requests wait (default 120 s, `never` supported); approve forwards,
68
- deny and timeout answer 403 with the reason. These commands need the proxy
69
- to be alive: with no live proxy on the runtime `sbx pending`, `approve` and
70
- `deny` exit 1 and say so, because nothing would read the answer.
67
+ Held requests wait (default 120 s, `never` supported), counting from arrival:
68
+ time spent in line and reading the body counts too, and a request past its
69
+ deadline is denied `hold timeout` whether waiting, sending, or parked. Each
70
+ agent holds at most one request being read or parked; later ones wait in
71
+ line, unread, in order — at most 16, the next gets `429 hold queue full`.
72
+ Approve forwards, deny and timeout answer 403 with the reason. A held body is spooled to `<runtime>/held/<id>` (never kept in memory, deleted when the hold ends); one over `hold.maxBody` (default 50 MB) is denied `403 body too large to hold`. These commands
73
+ need the proxy to be alive: with no live proxy on the runtime `sbx pending`,
74
+ `approve` and `deny` exit 1 and say so, because nothing would read the answer.
71
75
 
72
76
  ## One call: `run()` and `sbx run`
73
77
 
74
78
  `run()` starts the proxy, sandboxes one command, answers holds and returns
75
79
  the exit code with the ask and audit trail. Modes: `ask`, `auto` (default),
76
- `trust`. Payment destinations (`/checkout`, `/payment`, `/orders`,
77
- `/purchase`) hold in every mode; `ask` and `auto` also hold every
78
- non-GET/HEAD request (an interim rule until the policy module lands).
80
+ `trust`; see "Modes and the gate" below. `run()` takes `heldBodyMaxBytes` to
81
+ change the held-body cap and `allowLocal` (the `localLlm` setting) to let
82
+ exact `host:port` pairs, such as a local model server, past the wall.
79
83
 
80
84
  ```js no-run
81
85
  import { run } from "barebox";
@@ -98,6 +102,120 @@ line when a request parks and a `decided` line when it ends, then `done`;
98
102
  with `--json` stdout carries only JSON lines. Its exit code mirrors the
99
103
  agent's.
100
104
 
105
+ `sbx run` reads one optional config file,
106
+ `${XDG_CONFIG_HOME:-$HOME/.config}/barebox/config.json`, with keys `mode`,
107
+ `holdTimeoutSec` (positive integer or `"never"`), `heldBodyMaxMB`
108
+ (positive integer) and `localLlm` (array of `"host:port"`). A flag beats the file, the file beats the default; an
109
+ unknown key, bad value or bad JSON exits 2 naming the file and key. The file
110
+ is hidden inside the sandbox wherever it resolves. The library does not read it.
111
+ Two more keys, `labels` and `tenants`, are described under "Labels and model endpoints".
112
+
113
+ ## Modes and the gate
114
+
115
+ Every request becomes one bareguard `gate.check()`; `run()` builds one gate
116
+ per agent (and one for the TCP door's `tcp` agent), all sharing one tools
117
+ table. The mode picks the agent's rwx letters:
118
+
119
+ | Mode | Letters | Asks for |
120
+ |---|---|---|
121
+ | `ask` | `r--` | `w`, `x` |
122
+ | `auto` (default) | `rw-` | `x` |
123
+ | `trust` | `rwx` | nothing |
124
+
125
+ `GET`/`HEAD` are `r`; `POST`/`PUT`/`PATCH`/`DELETE` are `x`; any other method
126
+ is denied in every mode (`rwx.unlisted`). Without a label a request is the tool
127
+ `http.<METHOD>` (see "Labels and model endpoints"). The gate runs with empty
128
+ content patterns, so no word in a URL or method asks or denies on its own: the
129
+ mode letters, the labels and the floor decide. The floor is two bareguard flags,
130
+ `cardLike` (a body of 64 KB or less holding a card number: 13-19 digits,
131
+ optional single space or dash, first digit 2-6, Luhn-valid) and `paymentPath`
132
+ (`/checkout`, `/payment`, `/orders`, `/purchase`); both ask in every mode,
133
+ `trust` included. Nothing is denied because of a card. Bodies over 64 KB
134
+ stream through unscanned. The body never enters the gate's action.
135
+
136
+ barebox's hold queue is each gate's `humanChannel`: the ask files, `onAsk`
137
+ and `sbx approve|deny` work as above, and the ask carries the gate's `rule`
138
+ (`rwx.ask`, `flags.cardLike`, `flags.paymentPath`) and `letter`. A request
139
+ with a body of 64 KB or less is read in the agent's working slot before the
140
+ gate decides. Denials read `403 denied: <rule>[: reason]` (a human or timeout
141
+ denial reads `denied: <reason>`).
142
+
143
+ `createProxy` takes `gateFor(agent, { humanChannel, tools })`, called once per agent,
144
+ returning a bareguard `Gate` or any object with `async check(action)` that
145
+ resolves `{ outcome: "allow" | "deny" | "askHuman", rule?, reason? }`;
146
+ `askHuman` from a plain object goes to the same queue. Without `gateFor`
147
+ nothing is checked and everything forwards. `policy.js` exports `MODES` and
148
+ `gateFor({ agent, mode, auditPath, humanChannel })`. bareguard writes its
149
+ decisions to `<runtime>/gate.jsonl`, the one audit file (see "The audit file"
150
+ below). `close()` waits up to 3 s for requests
151
+ still inside a `check()`.
152
+
153
+ `localLlm` (config key; `allowLocal` on `run()` and `createProxy()`) is an
154
+ array of `"host:port"` strings. Only those exact pairs pass the wall's
155
+ private/loopback check, never link-local (cloud metadata).
156
+
157
+ ## The audit file
158
+
159
+ `<runtime>/gate.jsonl` (`runtimePaths(runtime).audit`; `run()` returns it as
160
+ `audit`) is the only log, one JSON object per line, all in bareguard's shape.
161
+ - Decisions: bareguard's gate lines carry the action (`method`, `url`, `tool`,
162
+ `agent`, `rid`) and an `aid`.
163
+ - Response status: a `phase:"record"` line with the same `aid` and
164
+ `result.status`.
165
+ - barebox's own facts: `phase:"annotate"`, `surface:false`, keyed by `verdict`:
166
+ `deny`, `hold`, `decide`, `hold-abandoned`, `hold-queue-full`, `stale-answer`,
167
+ `malformed-answer`, `body`, and `resp` (forward-all mode, no gate). A hold and
168
+ its outcome share `meta.id`; a request with a body gets one `body` line,
169
+ `meta: { agent, rid, bodyBytes, bodySha256 }`, joined to its gate line by
170
+ `action.rid`.
171
+ - Lines for an agent whose gate is not built, and every line when `gateFor` is
172
+ omitted, are written by a runtime-level `sbx` gate (`meta.agent` names the
173
+ agent).
174
+
175
+ ```bash
176
+ # every request with its response status, joined by aid
177
+ jq -s 'group_by(.aid)[] | select(.[0].aid) | {url: .[0].action.url, status: (map(.result.status) | map(select(.)) | first)}' <runtime>/gate.jsonl
178
+ # a request's body size and hash, joined by rid
179
+ jq -c 'select(.verdict=="body") | .meta' <runtime>/gate.jsonl
180
+ # one ask from hold to decision
181
+ jq -c 'select(.meta.id=="h1")' <runtime>/gate.jsonl
182
+ ```
183
+
184
+ ## Labels and model endpoints
185
+
186
+ Two config keys turn on rwxmap labels. `labels` is an array of folders the
187
+ rwxmap CLI wrote (`rwxmap <spec> -o <dir> --vendor <v>`); a leading `~/` means
188
+ `$HOME`. `tenants` is `{ "<vendor>": ["https://tenant.example.com"] }` (a
189
+ non-empty array of http(s) URLs per vendor); it replaces that vendor's server
190
+ URLs, so a placeholder host such as `your-domain.atlassian.net` matches your
191
+ tenant. A `tenants` vendor that no label folder defines is an error.
192
+
193
+ `loadLabels({ labels, tenants })` (`src/labels.js`) reads each
194
+ `<v>.rwxmap.review.json` for request keys, through `rwxmap/match`. The letters
195
+ come only from the sibling `<v>.rwxmap.json` file's `bareguard.tools`, the file
196
+ you review and can edit; rwxmap's own guessed letter is never used. A folder
197
+ with no review file, a review file without its gate file, or two vendors
198
+ defining the same key fails `sbx run` before any agent starts. A label file
199
+ written before rwxmap 0.8.0 fails with rwxmap's "regenerate it with rwxmap
200
+ 0.8.0" message.
201
+
202
+ The tool for a request is chosen in this order: the label's key when a label
203
+ documents the request; else a model endpoint key when known; else
204
+ `http.<METHOD>`. A label key the gate file lacks (a row you deleted) reaches the
205
+ gate unlisted and is denied (`rwx.unlisted`), in every mode: it fails closed.
206
+
207
+ Model endpoints are `r` (free in every mode): `api.anthropic.com`
208
+ `POST /v1/messages` and `/v1/messages/count_tokens`; `api.openai.com`
209
+ `POST /v1/chat/completions`, `/v1/responses` and `/v1/embeddings`; and on each
210
+ `localLlm` host:port `POST /api/chat`, `/api/generate`, `/api/embed`,
211
+ `/v1/chat/completions` and `/v1/completions` (http only). Any other path on
212
+ those hosts is a normal `POST`.
213
+
214
+ Label folders are hidden inside the sandbox like the config file, so the agent
215
+ cannot rewrite a letter. `run()` and `createProxy()` take `labels:
216
+ { matcher, tools }` (what `loadLabels` returns); omitted means no labels and
217
+ only the built-in model endpoints.
218
+
101
219
  ## Undo layer
102
220
 
103
221
  `overlay: true` (`sbx run --overlay`) mounts a per-run upper over the
@@ -127,9 +245,11 @@ The overlay needs bubblewrap >= 0.11.0 for `--overlay` / `sbx diff|commit|rollba
127
245
  `NODE_EXTRA_CA_CERTS`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`,
128
246
  `GIT_SSL_CAINFO`. Without it every HTTPS call from inside fails
129
247
  verification. Only `ca.pem` enters the sandbox, never the key.
130
- - Certificates live in `<runtime>/certs` (`runtime` is required). There is no `certDir` option and no control socket: decisions flow through `<runtime>/asks` + `<runtime>/answers` or `hold.onAsk`.
131
- - The upstream wall answers `403` for loopback, link-local (incl. `169.254.169.254`), the host's own addresses, private LAN ranges and unresolvable names. Every DNS answer is checked and the dial is pinned to the checked IP; test-only options live under `unsafeTestOnly` (`allowLoopback`, `resolveUpstream`) and production never sets them.
132
- - The audit log (`logFile`) is set to `0600` every time a proxy starts. The values of `Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie`, `X-Api-Key`, `X-Auth-Token` and `Api-Key` are logged as `[redacted]`; other headers and bodies are logged as-is unless your `redact` hook shapes them (it runs after the built-in scrub).
248
+ - Certificates live in `<runtime>/certs` (`runtime` is required). There is no `certDir` option and no control socket: decisions flow through `<runtime>/asks` + `<runtime>/answers` or `hold.onAsk`. Each minted certificate gets a random 128-bit serial (no shared `ca.srl`), and at most 4 mints run at once.
249
+ - Memory and limits: one proxy serves at most 40 agents, enforced. `addAgent` throws `createProxy: agent limit reached (40 agents per proxy); run another proxy for more`; the TCP door's `tcp` agent does not count, and `removeAgent` frees a place. For more than 40 agents run more proxies. Measured worst case (every agent with 1 parked + 16 waiting + a filled 64 KB body slot): proxy about 100 / 113-120 / 127-133 / 145-175 MB at 10 / 20 / 30 / 40 agents, quiet to busy machine (the budget is that range; needs bareguard 0.30.0), plus about 8 MB per sandbox (limit 10). Normal use is about 85-120 MB. Audit file size does not move these numbers. barebox is for small teams: free, local and lightweight, built to assist and to connect to many tools, not to run swarms or thousands of agents.
250
+ - The TCP door is one agent: every connection through `createProxy`'s TCP `port` counts as the agent `tcp` and shares one hold line. Use `addAgent` sockets (`sbx run` does) for separate lines per agent. `removeAgent(name)` ends that agent's open connections; its held requests end as deny / client gone. `run()` calls it when the sandbox exits, so a request still held then ends as client gone, not `proxy closing`.
251
+ - The upstream wall answers `403` for loopback, link-local (incl. `169.254.169.254`), the host's own addresses, private LAN ranges and unresolvable names. An IPv4 embedded in IPv6 is checked in every spelling: mapped, compat, uncompressed, NAT64 `64:ff9b::/96` (local-use `/48` denied outright) and 6to4 `2002::/16`; NAT64 and 6to4 of public sites stay reachable. Every DNS answer is checked and the dial is pinned to the checked IP; test-only options live under `unsafeTestOnly` (`allowLoopback`, `resolveUpstream`) and production never sets them.
252
+ - `createProxy` throws synchronously on an unopenable `logFile` (a directory, a missing parent, no permission) and releases the runtime. The runtime root, `asks/`, `answers/`, `held/` and `socks/` are owner-only (`0700`) whatever the umask. An existing runtime dir you own is tightened to `0700`; one you don't own (such as `/tmp`) is refused with an error naming the dir and its owner and suggesting a subdir like `/tmp/sbx`. The audit file (`logFile`, `gate.jsonl`) is set to `0600` every time a proxy starts. No request header and no body content is written to it: a body is logged as its length and SHA-256 only. The ask payload's `bodyPreview` (the first 4 KB, card numbers masked except the last 4) lives in the ask file only; other secrets inside a body still show there until bareguard redaction lands. Your `redact` hook shapes the `meta` of barebox's own annotate lines.
133
253
  - One proxy per runtime: `createProxy` throws "in use by pid N" (`run()` rejects, `sbx run` exits 1) while a live proxy owns the runtime. The claim is held by the proxy process and the kernel frees it when the process dies, so a crashed proxy never blocks the runtime. Use another `SBX_RUNTIME`, or leave it unset for a fresh one.
134
254
  - `launch()` starts the agent in the project dir, in a new session (no controlling terminal). Locked drawers are 21 credential stores (see `LOCKED_PATHS` in `src/launcher.js`); the agent's own model credentials in `~/.claude` stay readable until keys move out of its reach.
135
255
  - `sbx` exits 0 ok, 1 unknown id / refused / no live proxy / run failure, 2 usage; `sbx run` mirrors the agent's exit code.
@@ -137,8 +257,8 @@ The overlay needs bubblewrap >= 0.11.0 for `--overlay` / `sbx diff|commit|rollba
137
257
 
138
258
  ## What this package does not do
139
259
 
140
- Enforcement policy (which requests hold) arrives in a later module; until
141
- then holds follow the interim rules above (a path rule for `createProxy`;
142
- payment destinations plus non-GET/HEAD for `run()`). The hold decision never
143
- sees the request body, so card numbers in a body are not caught yet. No Docker, no MCP server, no macOS/Windows —
260
+ Per-API labels cover only the vendors whose rwxmap folders you list in
261
+ `labels`; every other request is `http.<METHOD>`. The card-in-body floor checks bodies of 64 KB or less;
262
+ larger bodies stream through unchecked for cards. The removed `hold.shouldHold`
263
+ and `hold.match` are gone: pass `gateFor` instead. No Docker, no MCP server, no macOS/Windows —
144
264
  Linux only. POC harnesses live in `poc/` in the repo and never ship.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barebox",
3
- "version": "0.3.0",
3
+ "version": "0.5.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": {
@@ -36,6 +36,7 @@
36
36
  "poc:m0": "bash poc/m0/run-m0.sh",
37
37
  "redteam:m0": "bash poc/m0/redteam.sh",
38
38
  "bench": "node scripts/bench.mjs",
39
+ "bench:agents": "node scripts/bench-agents.mjs",
39
40
  "test": "env -u NODE_USE_ENV_PROXY -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u FTP_PROXY -u http_proxy -u https_proxy -u all_proxy -u ftp_proxy node --test --import ./test/setup-env.mjs \"test/*.test.mjs\"",
40
41
  "typecheck": "tsc --noEmit && tsc -p tsconfig.scripts.json",
41
42
  "build:types": "tsc",
@@ -47,5 +48,9 @@
47
48
  "devDependencies": {
48
49
  "@types/node": "22",
49
50
  "typescript": "5"
51
+ },
52
+ "dependencies": {
53
+ "bareguard": "0.30.0",
54
+ "rwxmap": "0.8.0"
50
55
  }
51
56
  }
package/primitives.json CHANGED
@@ -16,7 +16,7 @@
16
16
  "when": "Reach for this HARNESS-ONLY to run the front door: it terminates agent TLS, sees every request, and parks the ones a human must decide. It decides nothing itself; pair with the launcher for sandboxes and `sbx` for decisions.",
17
17
  "import": "import { createProxy } from 'barebox'",
18
18
  "signature": "createProxy(opts: ProxyOptions)",
19
- "fails": "Throws synchronously on a missing `logFile` or `runtime`. Throws when another live proxy owns the runtime; the claim dies with its process; nothing is ever taken over. At runtime, dead upstreams, malformed input, over-cap and timed-out holds all become loud logged HTTP errors, never silence and never a crash. A second proxy on the same port rejects `ready`, never crashes the process.",
19
+ "fails": "Throws synchronously on a missing or unopenable `logFile` or `runtime`. Throws when another live proxy owns the runtime; the claim dies with its process; nothing is ever taken over. At runtime, dead upstreams, malformed input, over-cap and timed-out holds all become loud logged HTTP errors, never silence and never a crash. A second proxy on the same port rejects `ready`, never crashes the process.",
20
20
  "example": "import { createProxy } from \"barebox\";\nconst proxy = createProxy({ port: 0, runtime: \"./sbx-runtime\", logFile: \"./mitm.log\" });\nconst { port } = await proxy.ready;\nawait proxy.close();"
21
21
  },
22
22
  {
@@ -0,0 +1,96 @@
1
+ // cardscan.js — card-number detection on a byte stream, pure (no I/O).
2
+ //
3
+ // A candidate is 13-19 digits, optionally grouped by single spaces or dashes
4
+ // between digits, touching no other digit, first digit 2-6 (card networks;
5
+ // this excludes millisecond timestamps, which start with 1), Luhn-valid.
6
+ // The scanner keeps a TAIL-byte tail between chunks so a number split across
7
+ // chunks is found; memory is constant whatever the body size. A candidate
8
+ // that ends exactly at the end of the data seen so far counts at once: the
9
+ // next chunk may continue the digit run, but an over-detect only asks more.
10
+
11
+ const TAIL = 40; // longest candidate: 19 digits + 18 separators = 37 bytes
12
+ const START = /(?<!\d)[2-6]/g; // a candidate starts on a digit 2-6 with no digit before it
13
+
14
+ /** @param {string} digits */
15
+ function luhn(digits) {
16
+ let sum = 0;
17
+ let dbl = false;
18
+ for (let i = digits.length - 1; i >= 0; i--) {
19
+ let n = digits.charCodeAt(i) - 48;
20
+ if (dbl) { n *= 2; if (n > 9) n -= 9; }
21
+ sum += n;
22
+ dbl = !dbl;
23
+ }
24
+ return sum % 10 === 0;
25
+ }
26
+
27
+ /**
28
+ * Every Luhn-valid candidate in `text`, as `{ index, text }`. At each start,
29
+ * the candidates are the 13-19 digit prefixes (single space/dash between
30
+ * digits allowed) whose next char is not a digit; the longest valid one wins.
31
+ */
32
+ function candidates(text) {
33
+ const out = [];
34
+ START.lastIndex = 0;
35
+ for (let m; (m = START.exec(text));) {
36
+ let best = null;
37
+ let digits = '';
38
+ let i = m.index;
39
+ for (;;) {
40
+ digits += text[i++];
41
+ if (digits.length >= 13 && !/\d/.test(text[i] ?? '') && luhn(digits)) best = i;
42
+ if (digits.length === 19) break;
43
+ if (/\d/.test(text[i] ?? '')) continue;
44
+ if ((text[i] === ' ' || text[i] === '-') && /\d/.test(text[i + 1] ?? '')) i++;
45
+ else break;
46
+ }
47
+ if (best) {
48
+ out.push({ index: m.index, text: text.slice(m.index, best) });
49
+ START.lastIndex = best;
50
+ }
51
+ }
52
+ return out;
53
+ }
54
+
55
+ /**
56
+ * Create a streaming card-number scanner.
57
+ * @returns {{ push(chunk: Buffer): boolean, readonly found: boolean, readonly tailLength: number }}
58
+ * `push` returns `found`; `tailLength` is the retained byte count (<= 40).
59
+ */
60
+ export function createCardScanner() {
61
+ let found = false;
62
+ let tail = '';
63
+ let prevDigit = false; // was the byte just before `tail` a digit?
64
+ return {
65
+ push(chunk) {
66
+ if (found) return true;
67
+ const text = (prevDigit ? '0' : ' ') + tail + chunk.toString('latin1');
68
+ if (candidates(text).length) found = true;
69
+ const cut = Math.max(1, text.length - TAIL);
70
+ tail = text.slice(cut);
71
+ prevDigit = /\d/.test(text[cut - 1]);
72
+ return found;
73
+ },
74
+ get found() { return found; },
75
+ get tailLength() { return tail.length; },
76
+ };
77
+ }
78
+
79
+ /**
80
+ * Replace every card candidate's digits with `*` except the last 4,
81
+ * keeping the separators.
82
+ * @param {string} text
83
+ * @returns {string}
84
+ */
85
+ export function maskCards(text) {
86
+ const found = candidates(text);
87
+ let out = '';
88
+ let at = 0;
89
+ for (const c of found) {
90
+ out += text.slice(at, c.index);
91
+ let left = c.text.replace(/[ -]/g, '').length - 4;
92
+ out += c.text.replace(/\d/g, (d) => (left-- > 0 ? '*' : d));
93
+ at = c.index + c.text.length;
94
+ }
95
+ return out + text.slice(at);
96
+ }
package/src/certs.js CHANGED
@@ -6,6 +6,7 @@
6
6
  import { execFile } from 'node:child_process';
7
7
  import { mkdirSync, chmodSync, existsSync, writeFileSync, rmSync } from 'node:fs';
8
8
  import { join } from 'node:path';
9
+ import { randomBytes } from 'node:crypto';
9
10
 
10
11
  /** Hostname/IP spelling both the mint cache and the proxy wall accept. Single definition (see proxy.js). */
11
12
  export const HOST_RE = /^[A-Za-z0-9.-]+$/;
@@ -22,6 +23,25 @@ function sh(file, args) {
22
23
  // In-flight mints, so concurrent CONNECTs to a new host mint once.
23
24
  const inflight = new Map();
24
25
 
26
+ // At most this many mints run at once: each is several `openssl` processes.
27
+ const MAX_MINTS = 4;
28
+ let minting = 0;
29
+ /** @type {Array<() => void>} */
30
+ const mintQueue = [];
31
+
32
+ /** @template T @param {() => Promise<T>} fn @returns {Promise<T>} fn's result, run once a mint slot is free */
33
+ async function withMintSlot(fn) {
34
+ if (minting >= MAX_MINTS) await new Promise((resolve) => mintQueue.push(() => resolve(undefined)));
35
+ else minting++;
36
+ try {
37
+ return await fn();
38
+ } finally {
39
+ // Hand the slot straight to the next waiter, else free it.
40
+ const next = mintQueue.shift();
41
+ if (next) next(); else minting--;
42
+ }
43
+ }
44
+
25
45
  /**
26
46
  * Create the CA in `dir` unless it already exists. Safe to call twice:
27
47
  * an existing `ca.pem` is reused, never regenerated.
@@ -74,7 +94,7 @@ export async function certFor(dir, host) {
74
94
  }
75
95
  let p = inflight.get(host);
76
96
  if (!p) {
77
- p = mint(dir, host, keyPath, certPath).finally(() => { inflight.delete(host); });
97
+ p = withMintSlot(() => mint(dir, host, keyPath, certPath)).finally(() => { inflight.delete(host); });
78
98
  inflight.set(host, p);
79
99
  }
80
100
  return p;
@@ -100,7 +120,7 @@ async function mint(dir, host, keyPath, certPath) {
100
120
  try {
101
121
  await sh('openssl', ['req', '-new', '-key', keyPath, '-out', csr, '-subj', `/CN=${host}`]);
102
122
  await sh('openssl', ['x509', '-req', '-in', csr, '-CA', caCert, '-CAkey', caKey,
103
- '-CAcreateserial', '-days', '825', '-sha256', '-out', certPath, '-extfile', ext]);
123
+ '-set_serial', '0x' + randomBytes(16).toString('hex'), '-days', '825', '-sha256', '-out', certPath, '-extfile', ext]);
104
124
  } finally {
105
125
  rmSync(csr, { force: true });
106
126
  rmSync(ext, { force: true });