barebox 0.5.0 → 0.7.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,48 @@ 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.7.0] - 2026-11-01
8
+
9
+ ### Added
10
+
11
+ - The agent's `node` is the host's: the Node install that runs barebox (`process.execPath`, or `launch({ nodeExec })`) is bound read-only and its `bin` dir put first on the inside `PATH` when it lives outside `/usr`, `$HOME` and the project (nvm, fnm, asdf, a CI toolcache). An exec in a `bin/` dir binds the dir above it, where npm and global CLIs live; any other layout binds only its own dir. It is never bound when that dir is `/`, `$HOME` or above it (then it is not on `PATH` either, and `sbx run` says so on stderr).
12
+
13
+ ### Changed
14
+
15
+ - A secret's placeholder in the URL path or query is refused `403 denied: secret.url` in every mode, before the gate. Keys are swapped in headers only; before, the placeholder was sent as is and the API answered 401 with no hint why.
16
+ - A runtime or project under the bound Node install is safe: the runtime is masked like one under `$HOME` (its `asks/`, `answers/` and `socks/` are not visible), a project there keeps its overlay writable, and `launch()` throws when the runtime IS the Node install dir (or `/etc`, `/usr`).
17
+
18
+ ### Fixed
19
+
20
+ - Node's built-in `fetch` to an `http://` URL failed inside the sandbox (`UND_ERR_SOCKET`), local models such as Ollama included: with `NODE_USE_ENV_PROXY=1` Node tunnels plain http with `CONNECT`, and the proxy treated every tunnel as TLS. The first byte inside a tunnel now decides; plain HTTP is checked like any request (a placeholder there gets `403 denied: secret.scheme`). A certificate is minted only for a TLS tunnel; a plain one mints nothing. The same holds when the first bytes (a TLS ClientHello, or a plain request) arrive in the same write as the `CONNECT` line: the hello was dropped and the handshake never answered.
21
+ - `node` (and npm-installed CLIs) from nvm, fnm or a toolcache were `not found` inside the sandbox (exit 127).
22
+
23
+ ### Security
24
+
25
+ - A locked drawer or `maskDirs` folder under `/etc` or `/usr` (or the bound Node install) is now hidden like one under `$HOME`; before, only paths under `$HOME` and the project were masked, so such a folder stayed readable.
26
+
27
+ ## [0.6.0] - 2026-11-01
28
+
29
+ ### Added
30
+
31
+ - Keys the agent never holds. Config keys `secrets` (`NAME` -> `{ fromEnv` or `value, hosts }`) and `env` (`{ pass, set }`); `run()` takes `secrets` and `env`, `createProxy()` takes `secrets` (the list `loadSecrets` in the new `src/secrets.js` builds), `launch()` takes `env: { pass, set, placeholders }`. The sandbox gets a random placeholder per secret, new each run, under the secret's name. The proxy swaps the real value into request headers (a substring, also inside a decoded `Basic <base64>`) only after the gate allowed the request and only for the secret's hosts, and only into a request that goes upstream over TLS. A placeholder headed for any other host is refused `403 denied: secret.host`, and one headed for a bound host over plain http `403 denied: secret.scheme`, in every mode. Each hit is a `secret` annotate line in `gate.jsonl` (`meta: { agent, rid, name, host, swapped }`); the value is never in the audit, an ask or an error body. `env.pass` refuses names matching `KEY|TOKEN|SECRET|PASSWORD` (any case); a `fromEnv` variable that is unset exits 2 naming the secret. Headers only; the agent's own sign-in in `~/.claude` stays readable.
32
+ - The sandbox sets `NODE_USE_ENV_PROXY=1` next to the proxy variables, so Node's built-in `fetch` uses the proxy.
33
+ - `loadLabels` is exported from `barebox`: an embedder builds the `labels` value `run()` and `createProxy()` take (`{ matcher, tools, dirs }`) without the `sbx` CLI.
34
+
35
+ ### Changed
36
+
37
+ - The host environment no longer reaches the sandbox. The inside gets barebox's own variables (`HOME`, `PATH`, the proxy and CA variables), `TERM`, `COLORTERM`, `LANG`, `LANGUAGE`, `LC_*`, `TZ`, `USER`, `LOGNAME`, `SHELL`, `EDITOR`, `PAGER`, the config `env.pass` names, `env.set`, one placeholder per secret, and `extraEnv`. A caller that relied on an inherited variable lists it in `env.pass` (or passes `launch({ env })` / `extraEnv`). `launch()` still looks `bwrap` up on your `PATH` but starts it with `PATH=/usr/bin:/bin`.
38
+ - Requires Node.js >= 22.21 (was >= 22): the sandbox sets `NODE_USE_ENV_PROXY=1`, honoured from v22.21.0 (the test suite also uses `tls.setDefaultCACertificates`, v22.19.0).
39
+
40
+ ### Fixed
41
+
42
+ - A held request refused for being over the body cap could answer 500 instead of 403 when a body write was still in flight.
43
+
44
+ ### Security
45
+
46
+ - The host environment no longer reaches the sandbox: before, every host variable (an exported API key, `SBX_RUNTIME`) was readable inside, in `env` and in `/proc/*/environ`. `bwrap` is started with a clean environment, so `/proc/1/environ` inside is clean too.
47
+ - The mode no longer changes with `BAREGUARD_RWX_LETTERS` or `BAREGUARD_BUDGET_FILE` in the host environment: the gate gets its letters explicitly and no shared budget file, so a user shell or parent process that exports them cannot widen, break or budget-deny a run.
48
+
7
49
  ## [0.5.0] - 2026-10-30
8
50
 
9
51
  ### Added
package/README.md CHANGED
@@ -39,9 +39,9 @@ Three letters, each handled differently — the same `r`/`w`/`x` as [bareguard](
39
39
  The agent works in your house:
40
40
 
41
41
  - **Tracing paper (w).** The agent sees your real files, but every change lands on an overlay laid over them. At the end you commit it or roll it back (`sbx run --overlay -- <cmd>`, then `sbx diff`, `sbx commit`, `sbx rollback`).
42
- - **Locked drawers (r).** It reads most things. Keys and password stores (`~/.ssh`, `~/secrets`, `~/.gnupg`, `~/.password-store`, keyrings), browser profiles, cloud and cluster credentials (`~/.aws`, `~/.azure`, `~/.config/gcloud`, `~/.kube`, `~/.docker`, `~/.config/gh`, `~/.config/op`) and token files (`~/.netrc`, `~/.npmrc`, `~/.pypirc`, `~/.git-credentials`, `~/.cargo/credentials.toml`) stay shut. The agent's own model credentials (`~/.claude`) do not; moving those out is M5.
42
+ - **Locked drawers (r).** It reads most things. Keys and password stores (`~/.ssh`, `~/secrets`, `~/.gnupg`, `~/.password-store`, keyrings), browser profiles, cloud and cluster credentials (`~/.aws`, `~/.azure`, `~/.config/gcloud`, `~/.kube`, `~/.docker`, `~/.config/gh`, `~/.config/op`) and token files (`~/.netrc`, `~/.npmrc`, `~/.pypirc`, `~/.git-credentials`, `~/.cargo/credentials.toml`) stay shut. The agent's own model credentials (`~/.claude`) do not (a known gap: those tokens refresh themselves).
43
43
  - **One front door with a doorman (x).** No network of its own. Lookups pass; anything that sends, pays, or publishes waits for your yes.
44
- - **Keys it never holds.** The agent types a placeholder; the doorman puts the real API key in the request header only after you approve that request.
44
+ - **Keys it never holds.** The agent types a placeholder; the doorman puts the real API key in the request header only after the request is allowed, and only for the hosts that key is bound to. Your environment does not reach the sandbox.
45
45
 
46
46
  ## What it isn't
47
47
 
@@ -75,6 +75,21 @@ The agent works in your house:
75
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
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.
77
77
 
78
+ ## Keys the agent never holds
79
+
80
+ Put the key in `~/.config/barebox/config.json`, bound to its hosts:
81
+
82
+ ```json
83
+ {
84
+ "secrets": {
85
+ "STRIPE_API_KEY": { "fromEnv": "REAL_STRIPE_KEY", "hosts": ["api.stripe.com"] }
86
+ },
87
+ "env": { "pass": ["MY_TOOL_HOME"] }
88
+ }
89
+ ```
90
+
91
+ Inside the sandbox `$STRIPE_API_KEY` is a random placeholder, new each run. The agent sends it as it would the key (`curl -H "Authorization: Bearer $STRIPE_API_KEY"`, `curl -u "$STRIPE_API_KEY:"`). The proxy swaps the real value into the request headers only after the request is allowed, and only for `api.stripe.com`. A denied request never leaves. The same placeholder sent to any other host is refused: `403 denied: secret.host`. A real value is swapped only into a request that goes upstream over TLS: a placeholder to a bound host over plain `http://` is refused `403 denied: secret.scheme`. The rest of your environment stays out too, except a short default list (`TERM`, `LANG`, `LC_*`, `TZ`, ...) and the names in `env.pass`; `env.pass` refuses names like `*_TOKEN` and `*_KEY` (use `secrets`; a harmless match such as `XKB_KEYMAP` goes in `env.set`). Keys are swapped in headers only: a placeholder in the URL is refused `403 denied: secret.url`. Details: `barebox.context.md`.
92
+
78
93
  ## Numbers
79
94
 
80
95
  Measured, not estimated. Fedora, kernel 7.2, bubblewrap 0.12.0, Node 22.
@@ -111,11 +126,11 @@ M0–M2 are the go/no-go. Later: macOS (`sandbox-exec` + APFS clones), Windows v
111
126
  npm install barebox
112
127
  ```
113
128
 
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.
129
+ Requires Node.js >= 22.21. 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 (`scripts/ci-runner-deps.sh`) and fails if any test is skipped. The host's Node runs inside the sandbox: one under `$HOME` (a default nvm) or `/usr` is already visible, and one outside both (a CI toolcache, a Node with `HOME` set elsewhere) is bound read-only, with its `bin` dir first on the inside `PATH`. A runtime or project under that bound install stays hidden or writable as it would elsewhere. The API is in [`barebox.context.md`](barebox.context.md) and `primitives.json` (both ship in the package); the `sbx` CLI comes with it.
115
130
 
116
131
  ## Try the POCs
117
132
 
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.
133
+ Linux only, with `bwrap` (>= 0.11.0 only for the overlay), `socat`, `openssl`, Node >= 22.21 and Python 3. Needs a normal shell (namespaces + listening sockets), not a tool sandbox. The POCs are throwaway proofs, not the product.
119
134
 
120
135
  ```
121
136
  git clone https://github.com/hamr0/barebox && cd barebox
@@ -5,7 +5,7 @@ nothing leaves the machine without passing the doorman.
5
5
 
6
6
  ## Install
7
7
 
8
- Requires Node >= 22 and Linux with unprivileged user namespaces (bwrap)
8
+ Requires Node >= 22.21 and Linux with unprivileged user namespaces (bwrap)
9
9
  for sandboxes; the proxy and CLI run anywhere Node runs.
10
10
 
11
11
  ```bash
@@ -108,7 +108,7 @@ agent's.
108
108
  (positive integer) and `localLlm` (array of `"host:port"`). A flag beats the file, the file beats the default; an
109
109
  unknown key, bad value or bad JSON exits 2 naming the file and key. The file
110
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".
111
+ 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".
112
112
 
113
113
  ## Modes and the gate
114
114
 
@@ -145,7 +145,8 @@ returning a bareguard `Gate` or any object with `async check(action)` that
145
145
  resolves `{ outcome: "allow" | "deny" | "askHuman", rule?, reason? }`;
146
146
  `askHuman` from a plain object goes to the same queue. Without `gateFor`
147
147
  nothing is checked and everything forwards. `policy.js` exports `MODES` and
148
- `gateFor({ agent, mode, auditPath, humanChannel })`. bareguard writes its
148
+ `gateFor({ agent, mode, auditPath, humanChannel })`; the mode is the whole policy, so
149
+ `BAREGUARD_RWX_LETTERS` and `BAREGUARD_BUDGET_FILE` in the calling shell do not change it. bareguard writes its
149
150
  decisions to `<runtime>/gate.jsonl`, the one audit file (see "The audit file"
150
151
  below). `close()` waits up to 3 s for requests
151
152
  still inside a `check()`.
@@ -154,17 +155,88 @@ still inside a `check()`.
154
155
  array of `"host:port"` strings. Only those exact pairs pass the wall's
155
156
  private/loopback check, never link-local (cloud metadata).
156
157
 
158
+ ## Keys the agent never holds
159
+
160
+ The sandbox does not get your environment. The agent sees only barebox's own
161
+ variables (`HOME`, `PATH`, the proxy and CA variables, `NODE_USE_ENV_PROXY=1`, so Node's `fetch` reaches `http://` and `https://` URLs, local models included, through the proxy), a short default list
162
+ (`TERM`, `COLORTERM`, `LANG`, `LANGUAGE`, `LC_*`, `TZ`, `USER`, `LOGNAME`,
163
+ `SHELL`, `EDITOR`, `PAGER`), the host variables you name in `env.pass`, the
164
+ values in `env.set`, and one placeholder per secret. Nothing else reaches it,
165
+ `/proc/1/environ` included.
166
+
167
+ ```json
168
+ {
169
+ "env": { "pass": ["MY_TOOL_HOME"], "set": { "FOO": "bar" } },
170
+ "secrets": {
171
+ "STRIPE_API_KEY": { "fromEnv": "REAL_STRIPE_KEY", "hosts": ["api.stripe.com"] },
172
+ "JIRA_TOKEN": { "value": "...", "hosts": ["acme.atlassian.net"] }
173
+ }
174
+ }
175
+ ```
176
+
177
+ - `env.pass` refuses a name with `KEY`, `TOKEN`, `SECRET` or `PASSWORD` in it
178
+ (any case): `env.pass: "GITHUB_TOKEN" looks like a secret; use "secrets" for
179
+ it`. There is no override; `env.set` covers a harmless match.
180
+ - A secret has exactly one of `fromEnv` (a host variable; missing at startup
181
+ exits 2 naming the secret) or `value` (inline; the config file is hidden
182
+ inside the sandbox), and a non-empty `hosts` list of hostnames (no scheme,
183
+ no port).
184
+ - The agent sees a random placeholder, `sbx-ph-<16 hex>`, under the secret's
185
+ name, new on every run. It uses it as it would the key: `curl -H
186
+ "Authorization: Bearer $STRIPE_API_KEY"`, `-u "$STRIPE_API_KEY:"`, an
187
+ `x-api-key` header.
188
+ - The proxy looks for each placeholder in every request header value (as a
189
+ substring, also inside a decoded `Basic <base64>`). It swaps in the real
190
+ value only after the gate allowed the request (by mode or by your approval)
191
+ and only for a host the secret is bound to. A denied request never carries
192
+ it: it does not leave at all.
193
+ - A placeholder headed for a host its secret is not bound to is refused in
194
+ every mode: `403 denied: secret.host`. Nothing goes upstream.
195
+ - A real value is swapped only into a request that goes upstream over TLS. A
196
+ placeholder to a bound host over plain http is refused in every mode, before
197
+ the gate: `403 denied: secret.scheme`. Nothing goes upstream.
198
+ - Headers only. A key in a body is not swapped. A placeholder in the URL (path
199
+ or query string) is refused in every mode, before the gate: `403 denied:
200
+ secret.url`. Nothing goes upstream.
201
+ - Audit: one `annotate` line per hit, `verdict: "secret"`,
202
+ `meta: { agent, rid, name, host, swapped }`, joined to the gate line by
203
+ `rid`. The value is never written to the audit, an ask file or an error body.
204
+ - The same path covers plain requests, decrypted HTTPS (CONNECT) and the TCP
205
+ door.
206
+
207
+ Library callers pass the same shapes to `run()` (no `loadSecrets` call; `run()`
208
+ makes the placeholders once per run):
209
+
210
+ ```js no-run
211
+ import { run } from "barebox";
212
+ await run({
213
+ proj: "/path/to/project",
214
+ command: ["bash", "-c", 'curl -H "Authorization: Bearer $STRIPE_API_KEY" https://api.stripe.com/v1/balance'],
215
+ secrets: { STRIPE_API_KEY: { fromEnv: "REAL_STRIPE_KEY", hosts: ["api.stripe.com"] } },
216
+ env: { pass: ["MY_TOOL_HOME"], set: { FOO: "bar" } },
217
+ });
218
+ ```
219
+
220
+ `createProxy({ secrets })` takes the loaded list (`loadSecrets` in
221
+ `src/secrets.js`, internal) and `launch({ env: { pass, set, placeholders } })`
222
+ takes the environment. Known gaps: the agent's own sign-in in `~/.claude`
223
+ stays readable; an upstream that echoes a request header back in its response
224
+ hands the real value to the agent.
225
+
157
226
  ## The audit file
158
227
 
159
228
  `<runtime>/gate.jsonl` (`runtimePaths(runtime).audit`; `run()` returns it as
160
229
  `audit`) is the only log, one JSON object per line, all in bareguard's shape.
230
+ It is never rotated. `sbx run` without `SBX_RUNTIME` gets a fresh runtime, so a
231
+ fresh log, each run; with a reused `SBX_RUNTIME` the file keeps growing: delete
232
+ it between runs (no proxy running) to start a new one.
161
233
  - Decisions: bareguard's gate lines carry the action (`method`, `url`, `tool`,
162
234
  `agent`, `rid`) and an `aid`.
163
235
  - Response status: a `phase:"record"` line with the same `aid` and
164
236
  `result.status`.
165
237
  - barebox's own facts: `phase:"annotate"`, `surface:false`, keyed by `verdict`:
166
238
  `deny`, `hold`, `decide`, `hold-abandoned`, `hold-queue-full`, `stale-answer`,
167
- `malformed-answer`, `body`, and `resp` (forward-all mode, no gate). A hold and
239
+ `malformed-answer`, `body`, `secret`, and `resp` (forward-all mode, no gate). A hold and
168
240
  its outcome share `meta.id`; a request with a body gets one `body` line,
169
241
  `meta: { agent, rid, bodyBytes, bodySha256 }`, joined to its gate line by
170
242
  `action.rid`.
@@ -208,13 +280,14 @@ Model endpoints are `r` (free in every mode): `api.anthropic.com`
208
280
  `POST /v1/messages` and `/v1/messages/count_tokens`; `api.openai.com`
209
281
  `POST /v1/chat/completions`, `/v1/responses` and `/v1/embeddings`; and on each
210
282
  `localLlm` host:port `POST /api/chat`, `/api/generate`, `/api/embed`,
211
- `/v1/chat/completions` and `/v1/completions` (http only). Any other path on
283
+ `/v1/chat/completions` and `/v1/completions` (over http or https). Any other path on
212
284
  those hosts is a normal `POST`.
213
285
 
214
286
  Label folders are hidden inside the sandbox like the config file, so the agent
215
287
  cannot rewrite a letter. `run()` and `createProxy()` take `labels:
216
288
  { matcher, tools }` (what `loadLabels` returns); omitted means no labels and
217
- only the built-in model endpoints.
289
+ only the built-in model endpoints. `loadLabels` is exported from `barebox`:
290
+ `import { loadLabels } from 'barebox'`.
218
291
 
219
292
  ## Undo layer
220
293
 
@@ -246,12 +319,12 @@ The overlay needs bubblewrap >= 0.11.0 for `--overlay` / `sbx diff|commit|rollba
246
319
  `GIT_SSL_CAINFO`. Without it every HTTPS call from inside fails
247
320
  verification. Only `ca.pem` enters the sandbox, never the key.
248
321
  - 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.
322
+ - 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 / 143-172 MB at 10 / 20 / 30 / 40 agents, quiet to busy machine (the budget at 40 agents is the range 145-175 MB; 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
323
  - 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
324
  - 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
325
  - `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.
253
326
  - 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.
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.
327
+ - `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 (a known gap: its sign-in tokens refresh themselves, so `secrets` does not cover them). The host environment does not reach the inside: callers that relied on an inherited variable list it in `env.pass` (or pass `launch({ env })` / `extraEnv`). `launch()` finds `bwrap` on your `PATH` but starts it with a fixed `PATH`. The sandbox sees `/usr`, `/etc`, `$HOME` and the project read-only; the Node you run barebox with is visible too: a Node outside those (nvm, a CI toolcache) has its install bound read-only and its dir first on the inside `PATH`, so `node` and global CLIs run inside. A node in a `bin/` dir binds the dir above it; any other layout binds only the node's own dir. It is never bound when that dir is `/`, `$HOME` or above it; then its dir is not on `PATH` either and `sbx run` prints `barebox: not exposing Node at <dir> ...` on stderr (the sandbox uses `/usr/bin/node` if present). `launch({ nodeExec })` overrides `process.execPath`. Locked drawers and `maskDirs` folders are hidden wherever they sit under any of these (`/etc` and the Node install included). So is the runtime tree: a runtime under any of them gets an empty mask, and a runtime that IS `/etc`, `/usr` or the Node install dir throws. A project under the Node install keeps its overlay (the install is bound before it).
255
328
  - `sbx` exits 0 ok, 1 unknown id / refused / no live proxy / run failure, 2 usage; `sbx run` mirrors the agent's exit code.
256
329
  - Any listening unix socket under `$HOME` (IDE IPC, rootless-container sockets) is reachable from inside the sandbox: a read-only bind does not block `connect(2)`; the locked-paths list is the lever.
257
330
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barebox",
3
- "version": "0.5.0",
3
+ "version": "0.7.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": {
@@ -30,7 +30,7 @@
30
30
  ],
31
31
  "primitives": "./primitives.json",
32
32
  "engines": {
33
- "node": ">=22"
33
+ "node": ">=22.21"
34
34
  },
35
35
  "scripts": {
36
36
  "poc:m0": "bash poc/m0/run-m0.sh",
package/primitives.json CHANGED
@@ -34,9 +34,18 @@
34
34
  "when": "Reach for this to HARNESS-ONLY start one sandboxed agent run: it creates the sandbox the agent lives in. It does not decide anything; combine with the proxy for the front door and the gate (M3) for policy. Pass overlay:true for a writable tracing-paper run (M4). The agent starts in the project dir.",
35
35
  "import": "import { launch } from 'barebox'",
36
36
  "signature": "launch(opts: object) => ChildProcess",
37
- "fails": "Throws synchronously on a missing/empty `runtime`, `agent`, `proj`, or `command`, on a bad agent name, on a non-integer `proxyPort`, on an over-long socket path, when `socket` disagrees with `<runtime>/socks/<agent>.sock`, when `runtime` IS `HOME` or the project dir (its sockets could not be hidden from the agent), or with overlay on when the runtime sits inside the project or uncommitted changes linger. The child fails at runtime (nonzero exit) when `bwrap` or `socat` is missing inside, or when nothing listens on the agent socket.",
37
+ "fails": "Throws synchronously on a missing/empty `runtime`, `agent`, `proj`, or `command`, on a bad agent name, on a non-integer `proxyPort`, on an over-long socket path, when `socket` disagrees with `<runtime>/socks/<agent>.sock`, when `runtime` IS `HOME`, the project dir, `/etc`, `/usr` or the bound Node install dir (its sockets could not be hidden from the agent), or with overlay on when the runtime sits inside the project or uncommitted changes linger. The child fails at runtime (nonzero exit) when `bwrap` or `socat` is missing inside, or when nothing listens on the agent socket.",
38
38
  "example": "import { launch } from \"barebox\";\nconst child = launch({ runtime: \"/tmp/sbx\", agent: \"fx\", proj: \"/tmp/proj\", command: [\"bash\", \"-c\", \"echo hi\"] });\nawait new Promise((r) => child.on(\"close\", r)); // child.exitCode === 0"
39
39
  },
40
+ {
41
+ "name": "loadLabels",
42
+ "category": "labels",
43
+ "when": "Reach for this to build the `labels` value `run()` and `createProxy()` take: it reads rwxmap label folders once at startup and returns the request matcher, the tools table (letters from each gate file) and the absolute folders.",
44
+ "import": "import { loadLabels } from 'barebox'",
45
+ "signature": "loadLabels(cfg: object, env?: NodeJS.ProcessEnv) => { matcher: ReturnType<typeof matcherFrom>, tools: Record<string, any>, dirs: string[] }",
46
+ "fails": "Throws, naming the file or folder, on a folder with no review file, a review file without its gate file, a duplicate key across vendors, a tenants vendor no folder defines, an unreadable folder, or a label file written before rwxmap 0.8.0.",
47
+ "example": "import { loadLabels, run } from \"barebox\";\nconst labels = loadLabels({ labels: [\"/home/me/labels/jira\"], tenants: { jira: [\"https://acme.atlassian.net\"] } });\nawait run({ proj: \"/tmp/proj\", command: [\"bash\", \"-c\", \"true\"], labels });"
48
+ },
40
49
  {
41
50
  "name": "rollbackOverlay",
42
51
  "category": "overlay",
@@ -52,7 +61,7 @@
52
61
  "when": "Reach for this to HARNESS-ONLY run one sandboxed agent start-to-finish in a single call: it starts the proxy, sandboxes the command, answers holds, and returns the exit code with the ask and audit trail (plus the overlay diff once M4 exists).",
53
62
  "import": "import { run } from 'barebox'",
54
63
  "signature": "run(opts: object) => Promise<{ exit: number, asks: AskRecord[], audit: string, diff: OverlayChange[], runtime: string }>",
55
- "fails": "Rejects on a missing/unreadable `proj`, an empty `command`, a bad `mode`, a misshapen `onAsk`, a proxy that never becomes ready, a `launch` that throws (uncommitted overlay changes, a runtime inside the project — the proxy is closed first), or an overlay diff that cannot be read. The agent's own nonzero exit is returned as `exit`, never thrown.",
64
+ "fails": "Rejects on a missing/unreadable `proj`, an empty `command`, a bad `mode`, a misshapen `onAsk`, a `secrets` entry with no value (a `fromEnv` variable missing from this process's environment; the message names the secret, never a value), a proxy that never becomes ready, a `launch` that throws (uncommitted overlay changes, a runtime inside the project — the proxy is closed first), or an overlay diff that cannot be read. The agent's own nonzero exit is returned as `exit`, never thrown.",
56
65
  "example": "import { run } from \"barebox\";\nconst { exit, asks, audit } = await run({ proj: \"/tmp/proj\", command: [\"bash\", \"-c\", \"echo hi\"] });"
57
66
  }
58
67
  ]
package/src/cli.js CHANGED
@@ -36,7 +36,7 @@ import { MODES } from './policy.js';
36
36
  import { writeFileAtomic } from './holds.js';
37
37
  import { run as sandboxRun } from './run.js';
38
38
  import { diffOverlay, commitOverlay, rollbackOverlay } from './overlay.js';
39
- import { assertAgentName, createRuntime, runtimePaths, runtimeLive, safe, shellQuote } from './runtime.js';
39
+ import { assertAgentName, createRuntime, hostNode, runtimePaths, runtimeLive, safe, shellQuote } from './runtime.js';
40
40
 
41
41
  const USAGE = 'usage: sbx [--help] | pending | approve <id> | deny <id> [reason] | diff [--agent <name>] | commit [--agent <name>] [--skip-conflicts] | rollback [--agent <name>] | run [--mode ask|auto|trust] [--json] [--overlay] -- <cmd> [...]';
42
42
 
@@ -164,7 +164,7 @@ async function run(args) {
164
164
  usage();
165
165
  }
166
166
  if (values.mode !== undefined && !MODES.includes(values.mode)) usage();
167
- /** @type {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number }} */
167
+ /** @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[] }> }} */
168
168
  let cfg;
169
169
  try {
170
170
  cfg = resolveConfig({ mode: values.mode });
@@ -186,6 +186,8 @@ async function run(args) {
186
186
  const json = values.json ?? false;
187
187
  const overlay = values.overlay ?? false;
188
188
  const runtime = process.env.SBX_RUNTIME || createRuntime();
189
+ const node = hostNode(process.execPath, process.env.HOME || '/root', process.cwd());
190
+ if (node.refused) err(`barebox: not exposing Node at ${node.dir} (${node.refused}); the sandbox uses /usr/bin/node if present`);
189
191
  // Agent-controlled bytes, sanitized before they reach a terminal or a JSON consumer.
190
192
  const clean = (o, keys) => {
191
193
  const c = { ...o };
@@ -211,7 +213,7 @@ async function run(args) {
211
213
  .map((s) => s.trim()).filter(Boolean);
212
214
  result = await sandboxRun({
213
215
  runtime, proj: process.cwd(), command, mode, timeoutMs,
214
- allowLocal: cfg.localLlm, labels,
216
+ allowLocal: cfg.localLlm, labels, secrets: cfg.secrets, env: cfg.env,
215
217
  ...(cfg.heldBodyMaxMB ? { heldBodyMaxBytes: cfg.heldBodyMaxMB * 1048576 } : {}),
216
218
  unsafeTestOnly: { allowLoopback: process.env.SBX_UNSAFE_TEST_ALLOW_LOOPBACK === '1' },
217
219
  overlay,
package/src/config.js CHANGED
@@ -22,6 +22,49 @@ const isHttpUrl = (v) => {
22
22
  try { return ['http:', 'https:'].includes(new URL(v).protocol); } catch { return false; }
23
23
  };
24
24
 
25
+ const NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
26
+ const SECRET_LIKE = /KEY|TOKEN|SECRET|PASSWORD/i;
27
+ /** A plain object. @param {unknown} v @returns {boolean} */
28
+ const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
29
+
30
+ /** `env`: `{ pass?: names, set?: name -> string }`. @param {unknown} v @returns {string|null} */
31
+ const checkEnv = (v) => {
32
+ if (!isObj(v)) return 'must be an object of { pass?, set? }';
33
+ const o = /** @type {Record<string, any>} */ (v);
34
+ for (const k of Object.keys(o)) if (k !== 'pass' && k !== 'set') return `has unknown field "${k}"`;
35
+ if (o.pass !== undefined) {
36
+ if (!Array.isArray(o.pass) || !o.pass.every((n) => typeof n === 'string' && NAME_RE.test(n))) {
37
+ return 'env.pass must be an array of variable names';
38
+ }
39
+ const bad = o.pass.find((n) => SECRET_LIKE.test(n));
40
+ if (bad !== undefined) return `env.pass: "${bad}" looks like a secret; use "secrets" for it`;
41
+ }
42
+ if (o.set !== undefined) {
43
+ if (!isObj(o.set) || !Object.entries(o.set).every(([n, x]) => NAME_RE.test(n) && typeof x === 'string')) {
44
+ return 'env.set must be an object of variable name -> string';
45
+ }
46
+ }
47
+ return null;
48
+ };
49
+
50
+ /** `secrets`: NAME -> `{ fromEnv | value, hosts }`. @param {unknown} v @returns {string|null} */
51
+ const checkSecrets = (v) => {
52
+ if (!isObj(v)) return 'must be an object of NAME -> { fromEnv or value, hosts }';
53
+ for (const [name, s] of Object.entries(/** @type {Record<string, any>} */ (v))) {
54
+ if (!NAME_RE.test(name)) return `secret name "${name}" is not a variable name`;
55
+ if (!isObj(s)) return `secret ${name} must be an object`;
56
+ for (const k of Object.keys(s)) if (!['fromEnv', 'value', 'hosts'].includes(k)) return `secret ${name} has unknown field "${k}"`;
57
+ if ((s.fromEnv === undefined) === (s.value === undefined)) return `secret ${name} needs exactly one of fromEnv or value`;
58
+ if (s.fromEnv !== undefined && (typeof s.fromEnv !== 'string' || !NAME_RE.test(s.fromEnv))) return `secret ${name}: fromEnv must be a variable name`;
59
+ if (s.value !== undefined && (typeof s.value !== 'string' || s.value === '')) return `secret ${name}: value must be a non-empty string`;
60
+ if (!Array.isArray(s.hosts) || !s.hosts.length
61
+ || !s.hosts.every((h) => typeof h === 'string' && /^[^\s:/@]+$/.test(h))) {
62
+ return `secret ${name}: hosts must be a non-empty array of hostnames (no scheme, no port)`;
63
+ }
64
+ }
65
+ return null;
66
+ };
67
+
25
68
  /** Validators by key; each returns an error string or null. */
26
69
  const KEYS = {
27
70
  mode: (v) => (MODES.includes(v) ? null : `must be one of ${MODES.join(', ')}`),
@@ -35,6 +78,8 @@ const KEYS = {
35
78
  tenants: (v) => (v !== null && typeof v === 'object' && !Array.isArray(v)
36
79
  && Object.values(v).every((a) => Array.isArray(a) && a.length > 0 && a.every(isHttpUrl))
37
80
  ? null : 'must be an object of vendor -> non-empty array of http(s) URLs'),
81
+ env: checkEnv,
82
+ secrets: checkSecrets,
38
83
  };
39
84
 
40
85
  /**
@@ -52,7 +97,7 @@ export function configPath(env = process.env) {
52
97
  * Read the config file over the defaults. No file means defaults.
53
98
  *
54
99
  * @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
55
- * @returns {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number }} effective settings (`heldBodyMaxMB` absent means the library default)
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)
56
101
  * @throws {Error} naming the file (and the key) on invalid JSON, an unknown key or a bad value
57
102
  */
58
103
  export function loadConfig(env = process.env) {
@@ -78,6 +123,12 @@ export function loadConfig(env = process.env) {
78
123
  const bad = KEYS[/** @type {keyof typeof KEYS} */ (k)](v);
79
124
  if (bad) throw new Error(`${file}: key "${k}" ${bad}`);
80
125
  }
126
+ // A secret read from the host environment must be there at startup (the name, never a value).
127
+ for (const [name, s] of Object.entries(data.secrets ?? {})) {
128
+ if (s.fromEnv !== undefined && !env[s.fromEnv]) {
129
+ throw new Error(`${file}: secret ${name}: host variable ${s.fromEnv} is not set`);
130
+ }
131
+ }
81
132
  return { ...DEFAULTS, ...data };
82
133
  }
83
134
 
@@ -87,7 +138,7 @@ export function loadConfig(env = process.env) {
87
138
  * @param {object} [flags] values given on the command line
88
139
  * @param {string} [flags.mode] `--mode`
89
140
  * @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
90
- * @returns {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number }} effective settings (`heldBodyMaxMB` absent means the library default)
141
+ * @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)
91
142
  * @throws {Error} as {@link loadConfig}
92
143
  */
93
144
  export function resolveConfig(flags = {}, env = process.env) {
package/src/index.js CHANGED
@@ -3,3 +3,4 @@ export { launch } from './launcher.js';
3
3
  export { createProxy } from './proxy.js';
4
4
  export { run } from './run.js';
5
5
  export { diffOverlay, commitOverlay, rollbackOverlay } from './overlay.js';
6
+ export { loadLabels } from './labels.js';
package/src/labels.js CHANGED
@@ -30,6 +30,12 @@ function readJson(file) {
30
30
  * @param {NodeJS.ProcessEnv} [env] environment for `$HOME`
31
31
  * @returns {{ matcher: ReturnType<typeof matcherFrom>, tools: Record<string, any>, dirs: string[] }} `dirs` are the absolute folders (the launcher masks them)
32
32
  * @throws {Error} naming the file or folder on a missing gate or review file, a duplicate key, an unknown tenant vendor or a bad sidecar
33
+ * @when Reach for this to build the `labels` value `run()` and `createProxy()` take: it reads rwxmap label folders once at startup and returns the request matcher, the tools table (letters from each gate file) and the absolute folders.
34
+ * @fails Throws, naming the file or folder, on a folder with no review file, a review file without its gate file, a duplicate key across vendors, a tenants vendor no folder defines, an unreadable folder, or a label file written before rwxmap 0.8.0.
35
+ * @example
36
+ * import { loadLabels, run } from "barebox";
37
+ * const labels = loadLabels({ labels: ["/home/me/labels/jira"], tenants: { jira: ["https://acme.atlassian.net"] } });
38
+ * await run({ proj: "/tmp/proj", command: ["bash", "-c", "true"], labels });
33
39
  */
34
40
  export function loadLabels({ labels = [], tenants = {} }, env = process.env) {
35
41
  const home = env.HOME || os.homedir();