barebox 0.5.0 → 0.6.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,28 @@ 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.6.0] - 2026-11-01
8
+
9
+ ### Added
10
+
11
+ - 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.
12
+ - The sandbox sets `NODE_USE_ENV_PROXY=1` next to the proxy variables, so Node's built-in `fetch` uses the proxy.
13
+ - `loadLabels` is exported from `barebox`: an embedder builds the `labels` value `run()` and `createProxy()` take (`{ matcher, tools, dirs }`) without the `sbx` CLI.
14
+
15
+ ### Changed
16
+
17
+ - 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`.
18
+ - 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).
19
+
20
+ ### Fixed
21
+
22
+ - A held request refused for being over the body cap could answer 500 instead of 403 when a body write was still in flight.
23
+
24
+ ### Security
25
+
26
+ - 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.
27
+ - 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.
28
+
7
29
  ## [0.5.0] - 2026-10-30
8
30
 
9
31
  ### 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`). Headers only. 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, copies its Node into `/usr/bin` (the sandbox binds `/usr` only, so a Node installed elsewhere, such as under nvm, is not found inside), 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.
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,6 +155,72 @@ 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`), 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, URL or query string is not swapped.
199
+ - Audit: one `annotate` line per hit, `verdict: "secret"`,
200
+ `meta: { agent, rid, name, host, swapped }`, joined to the gate line by
201
+ `rid`. The value is never written to the audit, an ask file or an error body.
202
+ - The same path covers plain requests, decrypted HTTPS (CONNECT) and the TCP
203
+ door.
204
+
205
+ Library callers pass the same shapes to `run()` (no `loadSecrets` call; `run()`
206
+ makes the placeholders once per run):
207
+
208
+ ```js no-run
209
+ import { run } from "barebox";
210
+ await run({
211
+ proj: "/path/to/project",
212
+ command: ["bash", "-c", 'curl -H "Authorization: Bearer $STRIPE_API_KEY" https://api.stripe.com/v1/balance'],
213
+ secrets: { STRIPE_API_KEY: { fromEnv: "REAL_STRIPE_KEY", hosts: ["api.stripe.com"] } },
214
+ env: { pass: ["MY_TOOL_HOME"], set: { FOO: "bar" } },
215
+ });
216
+ ```
217
+
218
+ `createProxy({ secrets })` takes the loaded list (`loadSecrets` in
219
+ `src/secrets.js`, internal) and `launch({ env: { pass, set, placeholders } })`
220
+ takes the environment. Known gaps: the agent's own sign-in in `~/.claude`
221
+ stays readable; an upstream that echoes a request header back in its response
222
+ hands the real value to the agent.
223
+
157
224
  ## The audit file
158
225
 
159
226
  `<runtime>/gate.jsonl` (`runtimePaths(runtime).audit`; `run()` returns it as
@@ -164,7 +231,7 @@ private/loopback check, never link-local (cloud metadata).
164
231
  `result.status`.
165
232
  - barebox's own facts: `phase:"annotate"`, `surface:false`, keyed by `verdict`:
166
233
  `deny`, `hold`, `decide`, `hold-abandoned`, `hold-queue-full`, `stale-answer`,
167
- `malformed-answer`, `body`, and `resp` (forward-all mode, no gate). A hold and
234
+ `malformed-answer`, `body`, `secret`, and `resp` (forward-all mode, no gate). A hold and
168
235
  its outcome share `meta.id`; a request with a body gets one `body` line,
169
236
  `meta: { agent, rid, bodyBytes, bodySha256 }`, joined to its gate line by
170
237
  `action.rid`.
@@ -214,7 +281,8 @@ those hosts is a normal `POST`.
214
281
  Label folders are hidden inside the sandbox like the config file, so the agent
215
282
  cannot rewrite a letter. `run()` and `createProxy()` take `labels:
216
283
  { matcher, tools }` (what `loadLabels` returns); omitted means no labels and
217
- only the built-in model endpoints.
284
+ only the built-in model endpoints. `loadLabels` is exported from `barebox`:
285
+ `import { loadLabels } from 'barebox'`.
218
286
 
219
287
  ## Undo layer
220
288
 
@@ -246,12 +314,12 @@ The overlay needs bubblewrap >= 0.11.0 for `--overlay` / `sbx diff|commit|rollba
246
314
  `GIT_SSL_CAINFO`. Without it every HTTPS call from inside fails
247
315
  verification. Only `ca.pem` enters the sandbox, never the key.
248
316
  - 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.
317
+ - 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
318
  - 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
319
  - 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
320
  - `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
321
  - 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.
322
+ - `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`.
255
323
  - `sbx` exits 0 ok, 1 unknown id / refused / no live proxy / run failure, 2 usage; `sbx run` mirrors the agent's exit code.
256
324
  - 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
325
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barebox",
3
- "version": "0.5.0",
3
+ "version": "0.6.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
@@ -37,6 +37,15 @@
37
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.",
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
@@ -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 });
@@ -211,7 +211,7 @@ async function run(args) {
211
211
  .map((s) => s.trim()).filter(Boolean);
212
212
  result = await sandboxRun({
213
213
  runtime, proj: process.cwd(), command, mode, timeoutMs,
214
- allowLocal: cfg.localLlm, labels,
214
+ allowLocal: cfg.localLlm, labels, secrets: cfg.secrets, env: cfg.env,
215
215
  ...(cfg.heldBodyMaxMB ? { heldBodyMaxBytes: cfg.heldBodyMaxMB * 1048576 } : {}),
216
216
  unsafeTestOnly: { allowLoopback: process.env.SBX_UNSAFE_TEST_ALLOW_LOOPBACK === '1' },
217
217
  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();
package/src/launcher.js CHANGED
@@ -3,8 +3,8 @@
3
3
  // defaults are baked in, not switchable. The project bind is read-only unless
4
4
  // `overlay:true` mounts the M4 tracing paper over it (see overlay.js).
5
5
  import { spawn } from 'node:child_process';
6
- import { existsSync, lstatSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
7
- import { join, relative, dirname } from 'node:path';
6
+ import { accessSync, constants, existsSync, lstatSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
7
+ import { join, relative, dirname, delimiter } from 'node:path';
8
8
  import { assertAgentName, isInside, realPathOf, runtimePaths } from './runtime.js';
9
9
  import { assertOverlaySupport, setupOverlay } from './overlay.js';
10
10
  import { configPath } from './config.js';
@@ -88,6 +88,26 @@ const SYSTEM_BUNDLES = [
88
88
  const CA_ENV_VARS = ['SSL_CERT_FILE', 'NODE_EXTRA_CA_CERTS', 'REQUESTS_CA_BUNDLE',
89
89
  'CURL_CA_BUNDLE', 'GIT_SSL_CAINFO'];
90
90
 
91
+ // Host variables that reach the inside without being asked for (M5). Nothing
92
+ // else does: the sandbox gets a short list, not the host environment.
93
+ const PASS_DEFAULT = /^(TERM|COLORTERM|LANG|LANGUAGE|LC_[A-Z_]+|TZ|USER|LOGNAME|SHELL|EDITOR|PAGER)$/;
94
+
95
+ /**
96
+ * Where `bwrap` is, looked up on THIS process's PATH. The spawn below runs
97
+ * with a clean environment (its PATH is fixed), so node could not find a
98
+ * `bwrap` that the caller's PATH puts first (the fake one the tests use).
99
+ *
100
+ * @returns {string} the first executable `bwrap` on PATH, else the bare name (spawn then fails ENOENT as before)
101
+ */
102
+ function bwrapBin() {
103
+ for (const d of (process.env.PATH ?? '').split(delimiter)) {
104
+ if (!d) continue;
105
+ const p = join(d, 'bwrap');
106
+ try { accessSync(p, constants.X_OK); return p; } catch {}
107
+ }
108
+ return 'bwrap';
109
+ }
110
+
91
111
  /**
92
112
  * Build the CA bundle the sandbox trusts: system roots plus the barebox CA,
93
113
  * so public hosts verify as usual and the proxy's minted certs verify too.
@@ -131,7 +151,8 @@ export function buildCaBundle(runtime, caFile) {
131
151
  * @param {string} opts.proj project directory, bound read-only
132
152
  * @param {string[]} opts.command argv to run inside, for example `["python3", "agent.py"]`
133
153
  * @param {number} [opts.proxyPort] front-door port inside the sandbox (default 3128)
134
- * @param {object} [opts.extraEnv] extra environment entries for the inside
154
+ * @param {object} [opts.extraEnv] extra environment entries for the inside, set last (they win)
155
+ * @param {{ pass?: string[], set?: Record<string, string>, placeholders?: Record<string, string> }} [opts.env] the inside's environment (M5). The host environment never reaches it except: a short default list (`TERM`, `COLORTERM`, `LANG`, `LANGUAGE`, `LC_*`, `TZ`, `USER`, `LOGNAME`, `SHELL`, `EDITOR`, `PAGER`), the host variables named in `pass`, the values in `set`, and one placeholder per secret under its own name (`placeholders`, name to value). Set in that order, then `extraEnv`.
135
156
  * @param {string|null} [opts.socket] agent socket path, as returned by `proxy.addAgent` (default `<runtime>/socks/<agent>.sock`; the two must agree)
136
157
  * @param {string|null} [opts.caFile] barebox CA cert path (from `proxy.caFile`); when set, the sandbox trusts it for HTTPS alongside the system roots
137
158
  * @param {string[]} [opts.maskDirs] extra folders hidden from the agent exactly like barebox's config dir (the `labels` folders: the agent must not read or rewrite a letter)
@@ -146,7 +167,7 @@ export function buildCaBundle(runtime, caFile) {
146
167
  * await new Promise((r) => child.on("close", r)); // child.exitCode === 0
147
168
  */
148
169
  export function launch({ runtime, agent, proj, command, proxyPort = 3128,
149
- extraEnv = {}, socket = null, caFile = null, overlay = false, overlayIgnore, maskDirs = [] }) {
170
+ extraEnv = {}, env = {}, socket = null, caFile = null, overlay = false, overlayIgnore, maskDirs = [] }) {
150
171
  for (const [k, v] of Object.entries({ runtime, agent, proj })) {
151
172
  if (typeof v !== 'string' || !v) throw new Error(`launch: ${k} must be a non-empty string`);
152
173
  }
@@ -263,18 +284,33 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
263
284
  '--setenv', 'HTTPS_PROXY', `http://127.0.0.1:${proxyPort}`,
264
285
  '--setenv', 'http_proxy', `http://127.0.0.1:${proxyPort}`,
265
286
  '--setenv', 'https_proxy', `http://127.0.0.1:${proxyPort}`,
287
+ // Node's built-in fetch ignores the proxy variables unless this is set.
288
+ '--setenv', 'NODE_USE_ENV_PROXY', '1',
266
289
  );
267
290
  if (caBundle) {
268
291
  for (const v of CA_ENV_VARS) args.push('--setenv', v, '/run/sbx/ca-bundle.pem');
269
292
  }
293
+ // M5: the host environment never enters. The default list and `env.pass` are read from this
294
+ // process; then `env.set`, one placeholder per secret, and `extraEnv` (last wins).
295
+ for (const [k, v] of Object.entries(process.env)) {
296
+ if (v !== undefined && PASS_DEFAULT.test(k)) args.push('--setenv', k, v);
297
+ }
298
+ for (const k of env.pass ?? []) {
299
+ const v = process.env[k];
300
+ if (v !== undefined) args.push('--setenv', k, v);
301
+ }
302
+ for (const [k, v] of Object.entries(env.set ?? {})) args.push('--setenv', k, String(v));
303
+ for (const [k, v] of Object.entries(env.placeholders ?? {})) args.push('--setenv', k, String(v));
270
304
  for (const [k, v] of Object.entries(extraEnv)) args.push('--setenv', k, String(v));
271
305
  const door = String(proxyPort);
272
306
  const inner = 'ip link set lo up 2>/dev/null; ' +
273
307
  `socat TCP-LISTEN:${door},bind=127.0.0.1,reuseaddr,fork UNIX-CONNECT:/run/sbx/agent.sock & ` +
274
308
  `ok=; for i in $(seq 1 50); do (echo > /dev/tcp/127.0.0.1/${door}) 2>/dev/null && { ok=1; break; }; sleep 0.1; done; ` +
275
309
  '[ -n "$ok" ] || exit 99; exec "$@"';
276
- const child = spawn('bwrap', [...args, '/usr/bin/bash', '-c', inner, 'bash', ...command],
277
- { stdio: ['ignore', 'pipe', 'pipe'] });
310
+ const child = spawn(bwrapBin(), [...args, '/usr/bin/bash', '-c', inner, 'bash', ...command],
311
+ // A clean spawn environment: bwrap's own pid-1 process keeps the environment it was started
312
+ // with (it is `/proc/1/environ` inside), so the host's must not be it.
313
+ { stdio: ['ignore', 'pipe', 'pipe'], env: { PATH: '/usr/bin:/bin' } });
278
314
  // No `.overlay` on the child: the tracing paper's address is one call,
279
315
  // `runtimePaths(runtime).overlay(agent)`, so there is nothing to keep in sync.
280
316
  return child;
package/src/policy.js CHANGED
@@ -126,7 +126,10 @@ export async function gateFor({ agent, mode, auditPath, humanChannel, tools = TO
126
126
  const { letters, askUnheld } = MODE_RULES[mode];
127
127
  const gate = new Gate({
128
128
  audit: { path: auditPath },
129
- rwx: { agent, agents: { [agent]: letters }, tools, askUnheld },
129
+ // Explicit letters and an empty sharedFile ('' is falsy: no file, and bareguard's
130
+ // `??` stops there) keep the host's BAREGUARD_RWX_LETTERS / BAREGUARD_BUDGET_FILE out.
131
+ rwx: { agent, letters, tools, askUnheld },
132
+ budget: { sharedFile: '' },
130
133
  // The mode letters plus the card/payment floor are the whole policy; bareguard's
131
134
  // default word patterns scan the URL and method and would fire before rwx.
132
135
  content: { askPatterns: [], denyPatterns: [] },
package/src/proxy.js CHANGED
@@ -23,6 +23,7 @@ import { ASK_BODY_LIMIT, DEFAULT_HOLD_MAX_BODY, bodyPreview, createHolds } from
23
23
  import { claimRuntime, ensurePrivateDir, runtimePaths } from './runtime.js';
24
24
  import { paymentPath, toolFor, buildTools, emptyMatcher } from './policy.js';
25
25
  import { checkUpstream } from './wall.js';
26
+ import { findPlaceholders, applySecrets } from './secrets.js';
26
27
  import { Gate } from 'bareguard';
27
28
 
28
29
  const AGENT = Symbol('agent');
@@ -60,6 +61,7 @@ const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
60
61
  * so tests pass this; production never should.
61
62
  * @property {(host: string) => Promise<string[] | string | null>} [unsafeTestOnly.resolveUpstream]
62
63
  * DNS stub: replaces the wall's resolver so rebinding is testable. Production omits it.
64
+ * @property {import('./secrets.js').Secret[]} [secrets] the loaded secrets (`loadSecrets`): a request carrying a secret's placeholder in a header gets the real value there only after the gate allowed it and only for a bound host; for any other host it is refused `403 denied: secret.host`. The value never reaches the audit file, an ask or an error body.
63
65
  * @property {number} [clientIdleMs] kill a client tunnel idle this long; never fires mid-request (default 60000)
64
66
  * @property {(entry: Record<string, unknown>) => Record<string, unknown>} [redact] log redaction hook, applied after built-in secret scrubbing; its result becomes the `meta` of an `annotate` line (default: identity)
65
67
  */
@@ -123,7 +125,7 @@ export function createProxy(opts) {
123
125
  const { logFile, runtime, port = null,
124
126
  upstreamCa = null, hold = null, gateFor = null, allowLocal = [], labels = null,
125
127
  upstreamTimeoutMs = 120000, clientIdleMs = 60000,
126
- unsafeTestOnly = null,
128
+ unsafeTestOnly = null, secrets = [],
127
129
  redact = (e) => e } = opts ?? {};
128
130
  const { allowLoopback = false, resolveUpstream = null } = unsafeTestOnly ?? {};
129
131
  const gate = {
@@ -538,6 +540,7 @@ export function createProxy(opts) {
538
540
  };
539
541
  /** @param {string} reason @param {number} [status] */
540
542
  const refuse = (reason, status) => {
543
+ if (settled) return; // a late failure must not rewrite the settled deny's status
541
544
  if (status) ctx.status = status;
542
545
  finish({ decision: 'deny', reason });
543
546
  };
@@ -659,6 +662,35 @@ export function createProxy(opts) {
659
662
  denyRes(cres, 403, verdict.reason);
660
663
  return;
661
664
  }
665
+ // The request's one id: the audit lines of its secret swap, its body and
666
+ // its gate decision all carry it.
667
+ const rid = `r${++ridN}`;
668
+ // M5: a placeholder is found before the gate and swapped only after it
669
+ // allows (`withSecrets`), so the real value never sits in `ctx.headers`
670
+ // while the request waits for a decision. A placeholder headed for a host
671
+ // its secret is not bound to is refused in every mode.
672
+ const found = secrets.length ? findPlaceholders(creq.headers, url.hostname, secrets) : [];
673
+ const unbound = found.filter((f) => !f.bound);
674
+ if (unbound.length) {
675
+ for (const f of unbound) log({ ev: 'secret', agent, rid, name: f.name, host: url.hostname, swapped: false });
676
+ try { creq.resume(); } catch {}
677
+ denyRes(cres, 403, 'denied: secret.host');
678
+ return;
679
+ }
680
+ // A real value only ever goes upstream over TLS: forwardInner picks
681
+ // https from this same `url.protocol`, so a cleartext hop is refused here.
682
+ if (found.length && url.protocol !== 'https:') {
683
+ for (const f of found) log({ ev: 'secret', agent, rid, name: f.name, host: url.hostname, swapped: false });
684
+ try { creq.resume(); } catch {}
685
+ denyRes(cres, 403, 'denied: secret.scheme');
686
+ return;
687
+ }
688
+ /** The headers to forward: the real values in, one audit line per swap. @param {Record<string, string | string[] | undefined>} headers */
689
+ const withSecrets = (headers) => {
690
+ if (!found.length) return headers;
691
+ for (const f of found) log({ ev: 'secret', agent, rid, name: f.name, host: url.hostname, swapped: true });
692
+ return applySecrets(headers, url.hostname, secrets);
693
+ };
662
694
  const cl = Number(creq.headers['content-length'] ?? 0);
663
695
  const hasBody = creq.headers['transfer-encoding'] !== undefined || cl > 0;
664
696
 
@@ -672,7 +704,6 @@ export function createProxy(opts) {
672
704
  // `end` fires once the whole body was read, whichever path read it (also
673
705
  // a streamed body past 64 KB), so the values cover all of it. A client
674
706
  // that aborts mid-body never reaches `end`: no line, as before.
675
- const rid = `r${++ridN}`;
676
707
  if (hasBody) {
677
708
  creq.on('end', () => log({ ev: 'body', agent, rid, bodyBytes: tee.bytes, bodySha256: tee.digest() }));
678
709
  }
@@ -680,7 +711,7 @@ export function createProxy(opts) {
680
711
 
681
712
  // No gate: straight through. pipe() resumes the flow.
682
713
  if (!gateFor) {
683
- forward({ agent, method, url: urlStr, headers: { ...creq.headers }, stream: creq, cres });
714
+ forward({ agent, method, url: urlStr, headers: withSecrets({ ...creq.headers }), stream: creq, cres });
684
715
  return;
685
716
  }
686
717
 
@@ -713,7 +744,7 @@ export function createProxy(opts) {
713
744
  const g = await gateOf(agent);
714
745
  const d = await decideAction(g, action);
715
746
  if (d.outcome === 'allow') {
716
- const common = { agent, method, url: urlStr, headers: ctx.headers, cres,
747
+ const common = { agent, method, url: urlStr, headers: withSecrets(ctx.headers), cres,
717
748
  ...(d.aid ? { rec: { gate: g, action, aid: d.aid } } : {}) };
718
749
  if (ctx.heldId) {
719
750
  // The file is the exact body; the client's own framing (length or
package/src/run.js CHANGED
@@ -31,6 +31,7 @@ import { createRuntime, runtimePaths } from './runtime.js';
31
31
  import { launch } from './launcher.js';
32
32
  import { diffOverlay } from './overlay.js';
33
33
  import { MODES, gateFor } from './policy.js';
34
+ import { loadSecrets } from './secrets.js';
34
35
 
35
36
  /**
36
37
  * A collected ask record: the parked ask plus how it was decided.
@@ -67,6 +68,8 @@ import { MODES, gateFor } from './policy.js';
67
68
  * @property {object} [unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`): everything under it weakens the sandbox wall
68
69
  * @property {NodeJS.WritableStream} [stdout] where the agent's stdout goes (default process.stdout)
69
70
  * @property {NodeJS.WritableStream} [stderr] where the agent's stderr goes (default process.stderr)
71
+ * @property {Record<string, { fromEnv?: string, value?: string, hosts: string[] }>} [secrets] keys the agent never holds (M5), the config `secrets` shape: the sandbox gets a random placeholder under each NAME; the proxy swaps in the real value on an allowed request to one of its `hosts` (see `createProxy`). A `fromEnv` variable missing from this process's environment rejects the run, naming the secret
72
+ * @property {{ pass?: string[], set?: Record<string, string> }} [env] the sandbox's environment (M5), the config `env` shape: the host environment never reaches it except a short default list (`TERM`, `LANG`, `LC_*`, `TZ`, ...), the host variables named in `pass` and the values in `set` (see `launch`)
70
73
  * @property {boolean} [overlay] when true, mount a per-run overlay upper over the project (M4 tracing paper) instead of binding it read-only; the result's `diff` lists the run's changes for commit/rollback
71
74
  * @property {string[]} [overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
72
75
  */
@@ -89,11 +92,13 @@ import { MODES, gateFor } from './policy.js';
89
92
  * @param {object|null} [opts.unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`)
90
93
  * @param {NodeJS.WritableStream|null} [opts.stdout] where the agent's stdout goes (default process.stdout)
91
94
  * @param {NodeJS.WritableStream|null} [opts.stderr] where the agent's stderr goes (default process.stderr)
95
+ * @param {Record<string, { fromEnv?: string, value?: string, hosts: string[] }>|null} [opts.secrets] keys the agent never holds (M5), the config `secrets` shape; see {@link RunOptions}
96
+ * @param {{ pass?: string[], set?: Record<string, string> }|null} [opts.env] the sandbox's environment (M5), the config `env` shape; see {@link RunOptions}
92
97
  * @param {boolean} [opts.overlay] when true, mount a per-run overlay upper over the project instead of binding it read-only; the result's `diff` lists the run's changes for commit/rollback
93
98
  * @param {string[]} [opts.overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
94
99
  * @returns {Promise<{ exit: number, asks: AskRecord[], audit: string, diff: import('./overlay.js').OverlayChange[], runtime: string }>} the agent process exit code, the collected ask records, the JSONL audit log path, the run's overlay diff (M4), and the runtime dir addressing it
95
100
  * @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).
96
- * @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.
101
+ * @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.
97
102
  * @example
98
103
  * import { run } from "barebox";
99
104
  * const { exit, asks, audit } = await run({ proj: "/tmp/proj", command: ["bash", "-c", "echo hi"] });
@@ -101,7 +106,7 @@ import { MODES, gateFor } from './policy.js';
101
106
  export async function run({ proj, command, mode = 'auto', onAsk = null,
102
107
  onEvent = null, runtime = null, agent = 'agent', timeoutMs, heldBodyMaxBytes,
103
108
  allowLocal = [], labels = null, unsafeTestOnly = null, stdout = null, stderr = null,
104
- overlay = false, overlayIgnore }) {
109
+ overlay = false, overlayIgnore, secrets = null, env = null }) {
105
110
  if (typeof proj !== 'string' || !proj) throw new Error('run: proj must be a non-empty string');
106
111
  if (!fs.existsSync(proj)) throw new Error(`run: proj does not exist: ${proj}`);
107
112
  if (!Array.isArray(command) || !command.length) {
@@ -114,6 +119,8 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
114
119
  if (!MODES.includes(mode)) {
115
120
  throw new Error(`run: mode must be ${MODES.join('|')}, got ${JSON.stringify(mode)}`);
116
121
  }
122
+ // Once per run: the placeholders are fresh per run. A secret without a value throws here, before any runtime dir.
123
+ const loaded = loadSecrets(secrets ?? {});
117
124
  // Short temp dir: agent socket paths inherit it and cap at ~108 chars.
118
125
  const rt = runtime ?? createRuntime();
119
126
  const audit = runtimePaths(rt).audit;
@@ -136,7 +143,7 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
136
143
  : recordEvent;
137
144
 
138
145
  const proxy = createProxy({
139
- runtime: rt, logFile: audit, allowLocal, unsafeTestOnly,
146
+ runtime: rt, logFile: audit, allowLocal, unsafeTestOnly, secrets: loaded,
140
147
  ...(labels ? { labels } : {}),
141
148
  gateFor: (name, { humanChannel, tools }) => gateFor({ agent: name, mode, auditPath: audit, humanChannel, tools }),
142
149
  hold: { onAsk, timeoutMs, maxBody: heldBodyMaxBytes, onEvent: holdOnEvent },
@@ -161,6 +168,7 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
161
168
  runtime: rt, agent, proj, command,
162
169
  socket: sock, caFile: proxy.caFile,
163
170
  overlay, overlayIgnore, maskDirs: labels?.dirs ?? [],
171
+ env: { ...env, placeholders: Object.fromEntries(loaded.map((s) => [s.name, s.placeholder])) },
164
172
  });
165
173
  const out = stdout ?? process.stdout;
166
174
  const err = stderr ?? process.stderr;
package/src/secrets.js ADDED
@@ -0,0 +1,113 @@
1
+ // Secrets (M5): keys the agent never holds. The sandbox gets one random
2
+ // placeholder per secret; the proxy, outside it, swaps the real value into a
3
+ // request's headers only after the gate allowed it and only for a bound host.
4
+ // Pure: no I/O, no proxy state. Detect and apply are separate on purpose, so
5
+ // the real value is never in a request's headers while it waits for a decision.
6
+ import crypto from 'node:crypto';
7
+
8
+ /**
9
+ * One loaded secret.
10
+ *
11
+ * @typedef {object} Secret
12
+ * @property {string} name the variable name the sandbox sees the placeholder under
13
+ * @property {string} value the real value; never leaves the proxy except in an allowed request's header
14
+ * @property {string[]} hosts hostnames (no port) the real value may be sent to
15
+ * @property {string} placeholder `sbx-ph-<16 hex>`, fresh per call
16
+ */
17
+
18
+ /** Request headers as node reads them: lowercase names, string or string[] values. @typedef {Record<string, string | string[] | undefined>} Headers */
19
+
20
+ const BASIC = /^(Basic\s+)([A-Za-z0-9+/=_-]+)$/i;
21
+
22
+ /** @param {string} h @returns {string} */
23
+ const bare = (h) => h.toLowerCase();
24
+
25
+ /**
26
+ * Read the secrets from the config shape and give each a fresh placeholder.
27
+ *
28
+ * @param {Record<string, { fromEnv?: string, value?: string, hosts: string[] }>} [config] the config `secrets` object
29
+ * @param {NodeJS.ProcessEnv} [env] where `fromEnv` is read (default `process.env`)
30
+ * @returns {Secret[]} one entry per secret, new placeholders on every call (so per run)
31
+ * @throws {Error} naming the secret (never a value) when it has no value or no hosts
32
+ */
33
+ export function loadSecrets(config = {}, env = process.env) {
34
+ return Object.entries(config).map(([name, c]) => {
35
+ const value = c.fromEnv !== undefined ? env[c.fromEnv] : c.value;
36
+ if (typeof value !== 'string' || !value) throw new Error(`secret ${name}: no value`);
37
+ if (!Array.isArray(c.hosts) || !c.hosts.length) throw new Error(`secret ${name}: hosts required`);
38
+ return { name, value, hosts: c.hosts.map(bare), placeholder: `sbx-ph-${crypto.randomBytes(8).toString('hex')}` };
39
+ });
40
+ }
41
+
42
+ /**
43
+ * Does `v` hold the secret's placeholder, plainly or inside `Basic <base64>`?
44
+ * @param {string} v @param {Secret} s @returns {'plain'|'basic'|null}
45
+ */
46
+ function kindIn(v, s) {
47
+ if (v.includes(s.placeholder)) return 'plain';
48
+ const m = BASIC.exec(v);
49
+ if (m && Buffer.from(m[2], 'base64').toString('latin1').includes(s.placeholder)) return 'basic';
50
+ return null;
51
+ }
52
+
53
+ /**
54
+ * @param {string} v one header value @param {Secret} s @returns {string} `v` with the real value in place
55
+ */
56
+ function swapIn(v, s) {
57
+ const kind = kindIn(v, s);
58
+ if (kind === 'plain') return v.split(s.placeholder).join(s.value);
59
+ if (kind === 'basic') {
60
+ const m = /** @type {RegExpExecArray} */ (BASIC.exec(v));
61
+ const dec = Buffer.from(m[2], 'base64').toString('latin1');
62
+ // latin1 keeps every byte; the value goes in as its UTF-8 bytes.
63
+ const real = Buffer.from(s.value, 'utf8').toString('latin1');
64
+ return m[1] + Buffer.from(dec.split(s.placeholder).join(real), 'latin1').toString('base64');
65
+ }
66
+ return v;
67
+ }
68
+
69
+ /**
70
+ * Which placeholders a request carries, and whether each is headed for a host its secret is bound to.
71
+ * Each header value is searched as a substring and, for `Basic <base64>`, decoded.
72
+ *
73
+ * @param {Headers} headers the request headers
74
+ * @param {string} host the request's hostname (no port)
75
+ * @param {Secret[]} secrets from {@link loadSecrets}
76
+ * @returns {{ name: string, header: string, bound: boolean }[]} one entry per (secret, header)
77
+ */
78
+ export function findPlaceholders(headers, host, secrets) {
79
+ const h = bare(host);
80
+ const found = [];
81
+ for (const [header, v] of Object.entries(headers)) {
82
+ const vals = Array.isArray(v) ? v : [v];
83
+ for (const s of secrets) {
84
+ if (vals.some((x) => typeof x === 'string' && kindIn(x, s))) {
85
+ found.push({ name: s.name, header, bound: s.hosts.includes(h) });
86
+ }
87
+ }
88
+ }
89
+ return found;
90
+ }
91
+
92
+ /**
93
+ * The headers with every bound placeholder replaced by its real value. A new
94
+ * object; the input (which the agent's request owns) is never changed.
95
+ * Placeholders of a secret not bound to `host` stay as they are.
96
+ *
97
+ * @param {Headers} headers the request headers
98
+ * @param {string} host the request's hostname (no port)
99
+ * @param {Secret[]} secrets from {@link loadSecrets}
100
+ * @returns {Headers} new headers
101
+ */
102
+ export function applySecrets(headers, host, secrets) {
103
+ const h = bare(host);
104
+ const bound = secrets.filter((s) => s.hosts.includes(h));
105
+ /** @type {Headers} */
106
+ const out = {};
107
+ for (const [k, v] of Object.entries(headers)) {
108
+ /** @param {string} x @returns {string} */
109
+ const one = (x) => bound.reduce((acc, s) => swapIn(acc, s), x);
110
+ out[k] = Array.isArray(v) ? v.map(one) : (typeof v === 'string' ? one(v) : v);
111
+ }
112
+ return out;
113
+ }
package/types/config.d.ts CHANGED
@@ -9,7 +9,7 @@ export function configPath(env?: NodeJS.ProcessEnv): string;
9
9
  * Read the config file over the defaults. No file means defaults.
10
10
  *
11
11
  * @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
12
- * @returns {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number }} effective settings (`heldBodyMaxMB` absent means the library default)
12
+ * @returns {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
13
13
  * @throws {Error} naming the file (and the key) on invalid JSON, an unknown key or a bad value
14
14
  */
15
15
  export function loadConfig(env?: NodeJS.ProcessEnv): {
@@ -19,6 +19,15 @@ export function loadConfig(env?: NodeJS.ProcessEnv): {
19
19
  labels: string[];
20
20
  tenants: Record<string, string[]>;
21
21
  heldBodyMaxMB?: number;
22
+ env?: {
23
+ pass?: string[];
24
+ set?: Record<string, string>;
25
+ };
26
+ secrets?: Record<string, {
27
+ fromEnv?: string;
28
+ value?: string;
29
+ hosts: string[];
30
+ }>;
22
31
  };
23
32
  /**
24
33
  * Settings for one `sbx run`: a CLI flag beats the file, the file beats the default.
@@ -26,7 +35,7 @@ export function loadConfig(env?: NodeJS.ProcessEnv): {
26
35
  * @param {object} [flags] values given on the command line
27
36
  * @param {string} [flags.mode] `--mode`
28
37
  * @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
29
- * @returns {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number }} effective settings (`heldBodyMaxMB` absent means the library default)
38
+ * @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)
30
39
  * @throws {Error} as {@link loadConfig}
31
40
  */
32
41
  export function resolveConfig(flags?: {
@@ -38,4 +47,13 @@ export function resolveConfig(flags?: {
38
47
  labels: string[];
39
48
  tenants: Record<string, string[]>;
40
49
  heldBodyMaxMB?: number;
50
+ env?: {
51
+ pass?: string[];
52
+ set?: Record<string, string>;
53
+ };
54
+ secrets?: Record<string, {
55
+ fromEnv?: string;
56
+ value?: string;
57
+ hosts: string[];
58
+ }>;
41
59
  };
package/types/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { launch } from "./launcher.js";
2
2
  export { createProxy } from "./proxy.js";
3
3
  export { run } from "./run.js";
4
+ export { loadLabels } from "./labels.js";
4
5
  export { diffOverlay, commitOverlay, rollbackOverlay } from "./overlay.js";
package/types/labels.d.ts CHANGED
@@ -9,6 +9,12 @@
9
9
  * @param {NodeJS.ProcessEnv} [env] environment for `$HOME`
10
10
  * @returns {{ matcher: ReturnType<typeof matcherFrom>, tools: Record<string, any>, dirs: string[] }} `dirs` are the absolute folders (the launcher masks them)
11
11
  * @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
12
+ * @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.
13
+ * @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.
14
+ * @example
15
+ * import { loadLabels, run } from "barebox";
16
+ * const labels = loadLabels({ labels: ["/home/me/labels/jira"], tenants: { jira: ["https://acme.atlassian.net"] } });
17
+ * await run({ proj: "/tmp/proj", command: ["bash", "-c", "true"], labels });
12
18
  */
13
19
  export function loadLabels({ labels, tenants }: {
14
20
  labels?: string[] | undefined;
@@ -26,7 +26,8 @@ export function buildCaBundle(runtime: string, caFile: string): string;
26
26
  * @param {string} opts.proj project directory, bound read-only
27
27
  * @param {string[]} opts.command argv to run inside, for example `["python3", "agent.py"]`
28
28
  * @param {number} [opts.proxyPort] front-door port inside the sandbox (default 3128)
29
- * @param {object} [opts.extraEnv] extra environment entries for the inside
29
+ * @param {object} [opts.extraEnv] extra environment entries for the inside, set last (they win)
30
+ * @param {{ pass?: string[], set?: Record<string, string>, placeholders?: Record<string, string> }} [opts.env] the inside's environment (M5). The host environment never reaches it except: a short default list (`TERM`, `COLORTERM`, `LANG`, `LANGUAGE`, `LC_*`, `TZ`, `USER`, `LOGNAME`, `SHELL`, `EDITOR`, `PAGER`), the host variables named in `pass`, the values in `set`, and one placeholder per secret under its own name (`placeholders`, name to value). Set in that order, then `extraEnv`.
30
31
  * @param {string|null} [opts.socket] agent socket path, as returned by `proxy.addAgent` (default `<runtime>/socks/<agent>.sock`; the two must agree)
31
32
  * @param {string|null} [opts.caFile] barebox CA cert path (from `proxy.caFile`); when set, the sandbox trusts it for HTTPS alongside the system roots
32
33
  * @param {string[]} [opts.maskDirs] extra folders hidden from the agent exactly like barebox's config dir (the `labels` folders: the agent must not read or rewrite a letter)
@@ -40,13 +41,18 @@ export function buildCaBundle(runtime: string, caFile: string): string;
40
41
  * const child = launch({ runtime: "/tmp/sbx", agent: "fx", proj: "/tmp/proj", command: ["bash", "-c", "echo hi"] });
41
42
  * await new Promise((r) => child.on("close", r)); // child.exitCode === 0
42
43
  */
43
- export function launch({ runtime, agent, proj, command, proxyPort, extraEnv, socket, caFile, overlay, overlayIgnore, maskDirs }: {
44
+ export function launch({ runtime, agent, proj, command, proxyPort, extraEnv, env, socket, caFile, overlay, overlayIgnore, maskDirs }: {
44
45
  runtime: string;
45
46
  agent: string;
46
47
  proj: string;
47
48
  command: string[];
48
49
  proxyPort?: number | undefined;
49
50
  extraEnv?: object;
51
+ env?: {
52
+ pass?: string[];
53
+ set?: Record<string, string>;
54
+ placeholders?: Record<string, string>;
55
+ } | undefined;
50
56
  socket?: string | null | undefined;
51
57
  caFile?: string | null | undefined;
52
58
  maskDirs?: string[] | undefined;
package/types/proxy.d.ts CHANGED
@@ -18,6 +18,7 @@
18
18
  * so tests pass this; production never should.
19
19
  * @property {(host: string) => Promise<string[] | string | null>} [unsafeTestOnly.resolveUpstream]
20
20
  * DNS stub: replaces the wall's resolver so rebinding is testable. Production omits it.
21
+ * @property {import('./secrets.js').Secret[]} [secrets] the loaded secrets (`loadSecrets`): a request carrying a secret's placeholder in a header gets the real value there only after the gate allowed it and only for a bound host; for any other host it is refused `403 denied: secret.host`. The value never reaches the audit file, an ask or an error body.
21
22
  * @property {number} [clientIdleMs] kill a client tunnel idle this long; never fires mid-request (default 60000)
22
23
  * @property {(entry: Record<string, unknown>) => Record<string, unknown>} [redact] log redaction hook, applied after built-in secret scrubbing; its result becomes the `meta` of an `annotate` line (default: identity)
23
24
  */
@@ -152,6 +153,10 @@ export type ProxyOptions = {
152
153
  */
153
154
  resolveUpstream?: ((host: string) => Promise<string[] | string | null>) | undefined;
154
155
  } | undefined;
156
+ /**
157
+ * the loaded secrets (`loadSecrets`): a request carrying a secret's placeholder in a header gets the real value there only after the gate allowed it and only for a bound host; for any other host it is refused `403 denied: secret.host`. The value never reaches the audit file, an ask or an error body.
158
+ */
159
+ secrets?: import("./secrets.js").Secret[] | undefined;
155
160
  /**
156
161
  * kill a client tunnel idle this long; never fires mid-request (default 60000)
157
162
  */
package/types/run.d.ts CHANGED
@@ -32,6 +32,8 @@
32
32
  * @property {object} [unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`): everything under it weakens the sandbox wall
33
33
  * @property {NodeJS.WritableStream} [stdout] where the agent's stdout goes (default process.stdout)
34
34
  * @property {NodeJS.WritableStream} [stderr] where the agent's stderr goes (default process.stderr)
35
+ * @property {Record<string, { fromEnv?: string, value?: string, hosts: string[] }>} [secrets] keys the agent never holds (M5), the config `secrets` shape: the sandbox gets a random placeholder under each NAME; the proxy swaps in the real value on an allowed request to one of its `hosts` (see `createProxy`). A `fromEnv` variable missing from this process's environment rejects the run, naming the secret
36
+ * @property {{ pass?: string[], set?: Record<string, string> }} [env] the sandbox's environment (M5), the config `env` shape: the host environment never reaches it except a short default list (`TERM`, `LANG`, `LC_*`, `TZ`, ...), the host variables named in `pass` and the values in `set` (see `launch`)
35
37
  * @property {boolean} [overlay] when true, mount a per-run overlay upper over the project (M4 tracing paper) instead of binding it read-only; the result's `diff` lists the run's changes for commit/rollback
36
38
  * @property {string[]} [overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
37
39
  */
@@ -53,16 +55,18 @@
53
55
  * @param {object|null} [opts.unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`)
54
56
  * @param {NodeJS.WritableStream|null} [opts.stdout] where the agent's stdout goes (default process.stdout)
55
57
  * @param {NodeJS.WritableStream|null} [opts.stderr] where the agent's stderr goes (default process.stderr)
58
+ * @param {Record<string, { fromEnv?: string, value?: string, hosts: string[] }>|null} [opts.secrets] keys the agent never holds (M5), the config `secrets` shape; see {@link RunOptions}
59
+ * @param {{ pass?: string[], set?: Record<string, string> }|null} [opts.env] the sandbox's environment (M5), the config `env` shape; see {@link RunOptions}
56
60
  * @param {boolean} [opts.overlay] when true, mount a per-run overlay upper over the project instead of binding it read-only; the result's `diff` lists the run's changes for commit/rollback
57
61
  * @param {string[]} [opts.overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
58
62
  * @returns {Promise<{ exit: number, asks: AskRecord[], audit: string, diff: import('./overlay.js').OverlayChange[], runtime: string }>} the agent process exit code, the collected ask records, the JSONL audit log path, the run's overlay diff (M4), and the runtime dir addressing it
59
63
  * @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).
60
- * @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.
61
65
  * @example
62
66
  * import { run } from "barebox";
63
67
  * const { exit, asks, audit } = await run({ proj: "/tmp/proj", command: ["bash", "-c", "echo hi"] });
64
68
  */
65
- export function run({ proj, command, mode, onAsk, onEvent, runtime, agent, timeoutMs, heldBodyMaxBytes, allowLocal, labels, unsafeTestOnly, stdout, stderr, overlay, overlayIgnore }: {
69
+ export function run({ proj, command, mode, onAsk, onEvent, runtime, agent, timeoutMs, heldBodyMaxBytes, allowLocal, labels, unsafeTestOnly, stdout, stderr, overlay, overlayIgnore, secrets, env }: {
66
70
  proj: string;
67
71
  command: string[];
68
72
  mode?: string | undefined;
@@ -81,6 +85,15 @@ export function run({ proj, command, mode, onAsk, onEvent, runtime, agent, timeo
81
85
  unsafeTestOnly?: object | null;
82
86
  stdout?: NodeJS.WritableStream | null | undefined;
83
87
  stderr?: NodeJS.WritableStream | null | undefined;
88
+ secrets?: Record<string, {
89
+ fromEnv?: string;
90
+ value?: string;
91
+ hosts: string[];
92
+ }> | null | undefined;
93
+ env?: {
94
+ pass?: string[];
95
+ set?: Record<string, string>;
96
+ } | null | undefined;
84
97
  overlay?: boolean | undefined;
85
98
  overlayIgnore?: string[] | undefined;
86
99
  }): Promise<{
@@ -203,6 +216,21 @@ export type RunOptions = {
203
216
  * where the agent's stderr goes (default process.stderr)
204
217
  */
205
218
  stderr?: NodeJS.WritableStream | undefined;
219
+ /**
220
+ * keys the agent never holds (M5), the config `secrets` shape: the sandbox gets a random placeholder under each NAME; the proxy swaps in the real value on an allowed request to one of its `hosts` (see `createProxy`). A `fromEnv` variable missing from this process's environment rejects the run, naming the secret
221
+ */
222
+ secrets?: Record<string, {
223
+ fromEnv?: string;
224
+ value?: string;
225
+ hosts: string[];
226
+ }> | undefined;
227
+ /**
228
+ * the sandbox's environment (M5), the config `env` shape: the host environment never reaches it except a short default list (`TERM`, `LANG`, `LC_*`, `TZ`, ...), the host variables named in `pass` and the values in `set` (see `launch`)
229
+ */
230
+ env?: {
231
+ pass?: string[];
232
+ set?: Record<string, string>;
233
+ } | undefined;
206
234
  /**
207
235
  * when true, mount a per-run overlay upper over the project (M4 tracing paper) instead of binding it read-only; the result's `diff` lists the run's changes for commit/rollback
208
236
  */
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Read the secrets from the config shape and give each a fresh placeholder.
3
+ *
4
+ * @param {Record<string, { fromEnv?: string, value?: string, hosts: string[] }>} [config] the config `secrets` object
5
+ * @param {NodeJS.ProcessEnv} [env] where `fromEnv` is read (default `process.env`)
6
+ * @returns {Secret[]} one entry per secret, new placeholders on every call (so per run)
7
+ * @throws {Error} naming the secret (never a value) when it has no value or no hosts
8
+ */
9
+ export function loadSecrets(config?: Record<string, {
10
+ fromEnv?: string;
11
+ value?: string;
12
+ hosts: string[];
13
+ }>, env?: NodeJS.ProcessEnv): Secret[];
14
+ /**
15
+ * Which placeholders a request carries, and whether each is headed for a host its secret is bound to.
16
+ * Each header value is searched as a substring and, for `Basic <base64>`, decoded.
17
+ *
18
+ * @param {Headers} headers the request headers
19
+ * @param {string} host the request's hostname (no port)
20
+ * @param {Secret[]} secrets from {@link loadSecrets}
21
+ * @returns {{ name: string, header: string, bound: boolean }[]} one entry per (secret, header)
22
+ */
23
+ export function findPlaceholders(headers: Headers, host: string, secrets: Secret[]): {
24
+ name: string;
25
+ header: string;
26
+ bound: boolean;
27
+ }[];
28
+ /**
29
+ * The headers with every bound placeholder replaced by its real value. A new
30
+ * object; the input (which the agent's request owns) is never changed.
31
+ * Placeholders of a secret not bound to `host` stay as they are.
32
+ *
33
+ * @param {Headers} headers the request headers
34
+ * @param {string} host the request's hostname (no port)
35
+ * @param {Secret[]} secrets from {@link loadSecrets}
36
+ * @returns {Headers} new headers
37
+ */
38
+ export function applySecrets(headers: Headers, host: string, secrets: Secret[]): Headers;
39
+ /**
40
+ * One loaded secret.
41
+ */
42
+ export type Secret = {
43
+ /**
44
+ * the variable name the sandbox sees the placeholder under
45
+ */
46
+ name: string;
47
+ /**
48
+ * the real value; never leaves the proxy except in an allowed request's header
49
+ */
50
+ value: string;
51
+ /**
52
+ * hostnames (no port) the real value may be sent to
53
+ */
54
+ hosts: string[];
55
+ /**
56
+ * `sbx-ph-<16 hex>`, fresh per call
57
+ */
58
+ placeholder: string;
59
+ };
60
+ /**
61
+ * Request headers as node reads them: lowercase names, string or string[] values.
62
+ */
63
+ export type Headers = Record<string, string | string[] | undefined>;