barebox 0.1.0 → 0.3.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 +97 -0
- package/README.md +152 -7
- package/barebox.context.md +144 -0
- package/package.json +40 -3
- package/primitives.json +59 -0
- package/src/certs.js +109 -0
- package/src/cli.js +361 -0
- package/src/holds.js +476 -0
- package/src/index.js +5 -0
- package/src/launcher.js +272 -0
- package/src/overlay-walk.js +49 -0
- package/src/overlay.js +1012 -0
- package/src/proxy.js +572 -0
- package/src/run.js +226 -0
- package/src/runtime.js +263 -0
- package/src/wall.js +156 -0
- package/types/certs.d.ts +26 -0
- package/types/cli.d.ts +2 -0
- package/types/holds.d.ts +248 -0
- package/types/index.d.ts +4 -0
- package/types/launcher.d.ts +53 -0
- package/types/overlay-walk.d.ts +1 -0
- package/types/overlay.d.ts +220 -0
- package/types/proxy.d.ts +204 -0
- package/types/run.d.ts +192 -0
- package/types/runtime.d.ts +112 -0
- package/types/wall.d.ts +30 -0
- package/.claude/remember/AGENT_RULES.md +0 -291
- package/docs/product/agent-sandbox-prd.md +0 -418
- package/docs/product/agent-sandbox.md +0 -218
- package/poc/m0/README.md +0 -20
- package/poc/m0/func-fx.txt +0 -15
- package/poc/m0/func-fy.txt +0 -15
- package/poc/m0/launch.sh +0 -43
- package/poc/m0/measure.js +0 -53
- package/poc/m0/measure.txt +0 -23
- package/poc/m0/proxy.js +0 -74
- package/poc/m0/proxy.log +0 -28
- package/poc/m0/red-mem.txt +0 -4
- package/poc/m0/red-proxy.log +0 -13
- package/poc/m0/redteam.sh +0 -118
- package/poc/m0/run-m0.sh +0 -136
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
|
|
6
|
+
|
|
7
|
+
## [0.3.0] - 2026-10-28
|
|
8
|
+
|
|
9
|
+
Breaking changes (pre-1.0): the control socket, `createProxy`'s `certDir` and `allowUpstream`, `run()`'s low-level options, the hold queue's `approve`/`deny`/`size` and the top-level `allowLoopback` option are removed or moved; `runtime` is now required. Each is marked **Breaking** below.
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- M2.5 integration seam: `ask`, `auto` (the default) and `trust` modes with the card/payment floor in every mode; the `onAsk` seam plus the file-checkpoint ask channel (`asks/<id>.json` → `answers/<id>.json`, control socket deleted); `run()` wrapping proxy + launch; `sbx run [--mode ask|auto|trust] [--json] [--overlay]`; a 0600 JSONL audit log (bareguard's line shape deferred to M3); `sbx pending` / `approve` / `deny` refuse when no live proxy owns the runtime.
|
|
14
|
+
- M4 undo layer: per-run overlay tracing paper with `sbx diff` / `commit` / `rollback`, conflict flagging (refuse by default, `--skip-conflicts`), and `node_modules` invisibility. Diff walks the merged view with node inside the mount (no shell); `commit` stages into the project and swaps by journaled rename, undoing every step on failure (a full undo reports nothing was applied; a partial one names the steps not undone and keeps the commit folder with the originals); it strips setuid/setgid bits, and committed files get fresh mtimes. `rollback` reports diff's answer, or raw upper paths when the project is gone. Needs bubblewrap ≥ 0.11.0; older bwrap gets a clear refusal.
|
|
15
|
+
- The agent always starts in the project dir.
|
|
16
|
+
- The commit applies under read-only project folders.
|
|
17
|
+
- Rollback always removes the overlay upper, whatever the agent left there.
|
|
18
|
+
- The walker has no output cap, and node is resolved wherever it is installed.
|
|
19
|
+
- One proxy per runtime, enforced by a kernel-held lock: `createProxy` binds an abstract unix socket named from the runtime's real path, device and inode and holds it while the proxy lives. A second live proxy throws "in use" naming the owner's pid, before touching sockets or `asks/`. The kernel frees the lock when the process dies (SIGKILL included), so there is no stale claim and no takeover. `<runtime>/owner` (0600) only names the pid.
|
|
20
|
+
- `sbx pending`, `approve` and `deny` need a live proxy on the runtime and refuse otherwise.
|
|
21
|
+
- `SBX_OVERLAY_IGNORE=a,b` extends the list of folders the overlay layer ignores (`node_modules` is always ignored).
|
|
22
|
+
- Locked credential paths: `launch` hides 21 credential stores from the agent (keys, password stores, keyrings, browser profiles, cloud/cluster/container credentials, `gh`/`op` CLIs, token files). Folders are masked with an empty tmpfs and files read empty; a symlinked drawer is masked at its real target inside `$HOME` or the project. `~/.claude` is deliberately left visible.
|
|
23
|
+
- The upstream wall lives in `src/wall.js`: every resolved IP is checked after DNS, unresolvable names fail closed, and the dial is pinned to the checked IPs. One writer (`denyRes`) produces every HTTP error response.
|
|
24
|
+
- The agent sandbox always runs with bwrap `--new-session`, so its stdin is never the terminal.
|
|
25
|
+
|
|
26
|
+
### Security
|
|
27
|
+
|
|
28
|
+
- The audit log is owner-only (0600) and scrubs sensitive header values to `[redacted]` before any user `redact` hook runs.
|
|
29
|
+
- Ask and answer files are owner-only (0600); `sbx approve`/`deny` accept only `h<n>` ids; `sbx pending` and `sbx run` strip terminal control sequences from agent-controlled fields before printing.
|
|
30
|
+
|
|
31
|
+
### Removed
|
|
32
|
+
|
|
33
|
+
- **Breaking:** Control socket (`createProxy`'s `controlSocket` option, `SBX_SOCK`): decisions flow through the file checkpoint (`<runtime>/asks` + `<runtime>/answers`) or `hold.onAsk`; the migration guards are deleted.
|
|
34
|
+
- **Breaking:** `createProxy`'s `certDir`. Certificates always live in `<runtime>/certs`, and `runtime` is now required.
|
|
35
|
+
- **Breaking:** `createProxy`'s `allowUpstream`. There is no escape hatch around the upstream wall.
|
|
36
|
+
- **Breaking:** `run()`'s `gate`, `match`, `shouldHold`, `pollMs`, `proxyPort` and `extraEnv`. Use `createProxy` + `launch` for low-level control.
|
|
37
|
+
- **Breaking:** The hold queue's `approve(id)`, `deny(id)` and `size()`, and `body` on `pending()` entries (the ask payload carries `bodyPreview`).
|
|
38
|
+
- **Breaking:** The library's `ASK OPEN <id>` write to stderr. The library never prints.
|
|
39
|
+
|
|
40
|
+
### Changed
|
|
41
|
+
|
|
42
|
+
- **Breaking:** Test-only options moved under one key: `createProxy({ unsafeTestOnly: { allowLoopback, resolveUpstream } })`, `run({ unsafeTestOnly: { allowLoopback } })`. The CLI variable is renamed from `SBX_ALLOW_LOOPBACK` to `SBX_UNSAFE_TEST_ALLOW_LOOPBACK`.
|
|
43
|
+
- `onEvent(e)` on `createHolds` / `createProxy`'s `hold` / `run()`: `{ type: 'ask', ask }` when a hold parks, `{ type: 'decided', id, decision, reason }` when it settles. `run()`'s `asks` result is built from these events.
|
|
44
|
+
- `sbx run` prints how each ask ended: `decided <id> <allow|deny> [(reason)]`, or `{"ev":"decided","id","decision","reason"}` with `--json`, between the `ask` and `done` lines. A hold whose client went away reports `deny` / `client gone` (also in `run()`'s `asks`).
|
|
45
|
+
- Decisions are written as `allow` / `deny` everywhere, the audit log included. `approve` is still accepted, as an alias in answer files only.
|
|
46
|
+
- `sbx` results go to stdout; every error, refusal and usage-on-error goes to stderr through `err`. `--help` stays on stdout, exit 0. Exit codes don't change.
|
|
47
|
+
|
|
48
|
+
## [0.2.0] - 2026-10-27
|
|
49
|
+
|
|
50
|
+
Graduation rewrite: the M0–M2 POCs become a library. The POCs (Oct 26, `poc/`, not shipped) passed all three go/no-go gates:
|
|
51
|
+
|
|
52
|
+
- walls + front door: 14/14 checks, red-team 8/8
|
|
53
|
+
- inspection inside HTTPS: curl, node, python requests and git over the real internet
|
|
54
|
+
- hold-and-ask: a 9-scenario matrix
|
|
55
|
+
|
|
56
|
+
### Added
|
|
57
|
+
|
|
58
|
+
- `createProxy`: TLS-inspecting front door with on-demand per-host certs (via `openssl`), per-agent unix sockets as identity (`addAgent`), an opt-in test TCP listener bound to 127.0.0.1 only, and `ready`/`close` lifecycle.
|
|
59
|
+
- Upstream wall: DNS is fail-closed (every answer checked, unresolvable names denied) and the checked IP is pinned into the dial, so there is no rebinding. Loopback, link-local, private LAN (RFC 1918, CGNAT, ULA) and host addresses are denied; `allowUpstream` and test-only `allowLoopback` are the opt-ins.
|
|
60
|
+
- Hold queue: requests park for approve/deny or time out; holds abandoned by a disconnecting client are dropped; `maxBody` caps queued bodies.
|
|
61
|
+
- `launch`: bwrap sandbox with locked paths, a CA trust bundle exported through the usual env vars, and the runtime sockets masked from the sandbox (including a runtime reached through a symlink).
|
|
62
|
+
- `sbx` CLI: `pending`, `approve`, `deny`, `--help`, defined exit codes; socket from `SBX_SOCK` or `SBX_RUNTIME`, with no cwd default.
|
|
63
|
+
- `npm run bench`: per-sandbox and proxy RSS benchmark. Measured with 20 agents: 7.8 MB mean per sandbox (budget 10), and proxy 60.1 MB idle, 71.9 MB with 20 parked holds (budget 80).
|
|
64
|
+
- TypeScript types, `primitives.json` and `barebox.context.md`.
|
|
65
|
+
- `package.json` `repository` field, which npm provenance needs. Published with SLSA provenance.
|
|
66
|
+
|
|
67
|
+
### Changed
|
|
68
|
+
|
|
69
|
+
- `createProxy` throws unless `certDir` and the control socket live inside `runtime` (real paths compared).
|
|
70
|
+
- HTTP handling uses the stdlib `http` server instead of hand-rolled framing.
|
|
71
|
+
- The `bin` path is written as `src/cli.js`, without `./`.
|
|
72
|
+
|
|
73
|
+
### Fixed
|
|
74
|
+
|
|
75
|
+
- POST/PUT bodies to real hostnames no longer hang; the client stream is paused until the upstream pipe is attached.
|
|
76
|
+
- HEAD requests no longer return 502 after 6 s, and slow upstreams are no longer killed at 10 s.
|
|
77
|
+
- Plain-HTTP requests now go through holds the same way HTTPS ones do.
|
|
78
|
+
- The publish workflow installs the same sandbox runner deps as CI (bubblewrap, socat, curl, openssl, userns sysctl).
|
|
79
|
+
- The adopter-gate quickstart uses the 0.2.0 API (`pending()`, a JSON import with `with { type: "json" }`).
|
|
80
|
+
|
|
81
|
+
### Security
|
|
82
|
+
|
|
83
|
+
- The proxy listens on 127.0.0.1 only, not on all interfaces.
|
|
84
|
+
- An agent can no longer approve its own holds. A read-only bind does not block `connect` on a unix socket, so the runtime is masked inside the sandbox and the control socket must live in the runtime.
|
|
85
|
+
- Loopback is no longer reachable through the proxy. A failed DNS lookup is denied, and the private LAN is blocked.
|
|
86
|
+
- `ca.key` can no longer leak through a `certDir` outside the runtime.
|
|
87
|
+
- Audit log is created 0600 and `Authorization` headers are scrubbed from logged lines.
|
|
88
|
+
|
|
89
|
+
## [0.1.0] - 2026-10-26
|
|
90
|
+
|
|
91
|
+
### Added
|
|
92
|
+
|
|
93
|
+
- Reserved `barebox` on npm; repo scaffold (docs, M0 throwaway POC, publish workflow).
|
|
94
|
+
|
|
95
|
+
[0.3.0]: https://github.com/hamr0/barebox/compare/v0.2.0...v0.3.0
|
|
96
|
+
[0.2.0]: https://github.com/hamr0/barebox/compare/1f144f4...v0.2.0
|
|
97
|
+
[0.1.0]: https://github.com/hamr0/barebox/commit/1f144f4
|
package/README.md
CHANGED
|
@@ -1,10 +1,155 @@
|
|
|
1
|
-
|
|
1
|
+
```
|
|
2
|
+
┌──────────────┐
|
|
3
|
+
│ agent inside │
|
|
4
|
+
│ r w x │── doorman ──▶ world
|
|
5
|
+
└──────────────┘
|
|
6
|
+
read undo ask
|
|
2
7
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
passing a doorman. You're asked only when something irreversible is about to happen.
|
|
8
|
+
barebox
|
|
9
|
+
```
|
|
6
10
|
|
|
7
|
-
|
|
8
|
-
|
|
11
|
+
> An agent runs on your machine with your real tools, every write is undoable, and nothing leaves the machine without passing a doorman. You're asked only when something irreversible is about to happen.
|
|
12
|
+
> No root, no daemon, no image. One shared proxy, many thin sandboxes: ~8 MB each, 10 ms to start (M0 POC figure — unmeasured on the rewritten code, TODO re-measure).
|
|
9
13
|
|
|
10
|
-
|
|
14
|
+
<p align="center">
|
|
15
|
+
<img src="https://img.shields.io/github/package-json/v/hamr0/barebox?label=version&color=2a4f8c" alt="version (auto from package.json)">
|
|
16
|
+
<img src="https://img.shields.io/badge/license-Apache%202.0-2a4f8c" alt="license: Apache 2.0">
|
|
17
|
+
<img src="https://img.shields.io/badge/platform-Linux-2a4f8c" alt="platform: Linux">
|
|
18
|
+
<img src="https://img.shields.io/badge/status-POC-c0841a" alt="status: POC">
|
|
19
|
+
</p>
|
|
20
|
+
|
|
21
|
+
> **Status:** early. The walls (M0), HTTPS inspection (M1), hold-and-ask (M2), the one-call `run()` and file ask channel (M2.5) and the undo layer (M4) are built and measured; the decision rules (M3), key custody (M5) and the rest are not. Today's hold rule is interim: payment destinations, plus every non-GET/HEAD request in `ask` and `auto` modes. Linux only.
|
|
22
|
+
|
|
23
|
+
## Why
|
|
24
|
+
|
|
25
|
+
Agents need real access to be useful — shell, files, network. Today you pick one of two bad options:
|
|
26
|
+
|
|
27
|
+
- **Approve everything.** About forty prompts per task. People stop reading them, or switch prompts off.
|
|
28
|
+
- **Heavy isolation.** Docker or a VM: images, a daemon, root, and the agent can't use your installed toolchain. Most people skip it.
|
|
29
|
+
|
|
30
|
+
Neither matches where the risk is. Reads are mostly harmless. File writes can be fixed. Only a few actions can't be undone: paying, sending, publishing, pushing. barebox asks about those and nothing else.
|
|
31
|
+
|
|
32
|
+
## What it is
|
|
33
|
+
|
|
34
|
+
Three letters, each handled differently — the same `r`/`w`/`x` as [bareguard](https://github.com/hamr0/bareguard) and [rwxmap](https://github.com/hamr0/rwxmap).
|
|
35
|
+
|
|
36
|
+
| Letter | Meaning | What barebox does | You're asked? |
|
|
37
|
+
|---|---|---|---|
|
|
38
|
+
| `r` | reads, changes nothing | lets it through (except locked paths) | never |
|
|
39
|
+
| `w` | changes things, can be set back | records it on an undo layer | once, at the end (review the diff) |
|
|
40
|
+
| `x` | can't be undone: send, pay, publish, push | holds it at the door until you decide | at the moment it happens |
|
|
41
|
+
|
|
42
|
+
The agent works in your house:
|
|
43
|
+
|
|
44
|
+
- **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`).
|
|
45
|
+
- **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.
|
|
46
|
+
- **One front door with a doorman (x).** No network of its own. Lookups pass; anything that sends, pays, or publishes waits for your yes.
|
|
47
|
+
- **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.
|
|
48
|
+
|
|
49
|
+
## What it isn't
|
|
50
|
+
|
|
51
|
+
- **Not a security boundary against a determined attacker.** The kernel is shared; a kernel exploit escapes. Use a VM for that. barebox is a strong guardrail against mistakes and prompt-injected agents.
|
|
52
|
+
- No Docker, no VM, no cluster, no cloud control plane. Your box or a cheap VPS.
|
|
53
|
+
- Not a content filter and not intent detection — the doorman sees requests, not intent. Cert-pinned apps, non-HTTP egress and UDP are denied, not inspected.
|
|
54
|
+
|
|
55
|
+
## How it works
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
agent process (real node, python, git)
|
|
59
|
+
|
|
|
60
|
+
+-----+--------------- bwrap sandbox (unprivileged) ---------------+
|
|
61
|
+
| files: overlay lower = real project (read only) |
|
|
62
|
+
| upper = per-run tracing paper |
|
|
63
|
+
| locked paths (~/.ssh etc.) -> empty tmpfs or /dev/null |
|
|
64
|
+
| network: none of its own |
|
|
65
|
+
| socat inside: 127.0.0.1:3128 -> per-agent unix socket |
|
|
66
|
+
+-----+------------------------------------------------------------+
|
|
67
|
+
| per-agent unix socket (the connection = the agent's identity)
|
|
68
|
+
v
|
|
69
|
+
ONE shared proxy (Node, in-process: rwxmap + bareguard)
|
|
70
|
+
|-- r -> forward
|
|
71
|
+
|-- x -> hold, ask the human, forward or 403
|
|
72
|
+
'-- unknown -> per-mode default
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
- **Walls** are [bubblewrap](https://github.com/containers/bubblewrap), unprivileged: separate net/pid/ipc/uts namespaces, read-only binds, tmpfs over locked paths.
|
|
76
|
+
- **Identity** is the socket, not a header the agent could fake. One socket per agent, all into one proxy.
|
|
77
|
+
- **HTTPS inspection** uses a local CA that exists only inside the sandbox; the proxy reads method, URL, headers and body, then forwards.
|
|
78
|
+
- **The doorman's x-rules**, strongest first: card numbers in the body (Luhn) → payment domains and paths (`/checkout`, `/payment`, …) → rwxmap labels for known APIs → unknown `POST` by mode (strict: ask once per domain; normal: allow and log).
|
|
79
|
+
- **Approvals** come from a second terminal (`sbx pending`, `sbx approve <id>`, `sbx deny <id>`). Timeout means deny, with a clear `403` reason.
|
|
80
|
+
|
|
81
|
+
## Numbers
|
|
82
|
+
|
|
83
|
+
Measured, not estimated. Fedora, kernel 7.2, bubblewrap 0.12.0, Node 22.
|
|
84
|
+
|
|
85
|
+
| | barebox (measured) | [srt](https://github.com/anthropic-experimental/sandbox-runtime) 0.0.81 (measured) |
|
|
86
|
+
|---|---|---|
|
|
87
|
+
| Memory per sandbox | **7.8 MB** mean, 7.9 MB max (20 concurrent) | ~100 MB |
|
|
88
|
+
| Proxy | one shared, **~60 MB idle, ~72 MB loaded** (20 agents, within the ≤ 80 MB budget) | one per sandbox |
|
|
89
|
+
| Start + exit | **10 ms** (M0 POC; unmeasured on the rewrite — TODO re-measure) | 1.87–2.05 s |
|
|
90
|
+
| 20 agents | ~228 MB (rough sum: ~72 MB proxy + 20 × 7.8 MB) | ~2 GB |
|
|
91
|
+
|
|
92
|
+
Targets: shared proxy ≤ 80 MB, each extra sandbox ≤ 10 MB, 20 agents on a 2 GB VPS. Bypass attempts (`--noproxy`, unset proxy env, direct IP, host localhost) all fail closed, and a red-team script breaks each wall on purpose to prove the checks can fail. Setup, dead ends and why: [findings](docs/logs/findings.md).
|
|
93
|
+
|
|
94
|
+
## Roadmap
|
|
95
|
+
|
|
96
|
+
| Module | What | Status |
|
|
97
|
+
|---|---|---|
|
|
98
|
+
| M0 | Walls + front door | **PASS** — 14/14, red-team 8/8 |
|
|
99
|
+
| M1 | Proxy sees inside HTTPS (curl, node, python requests, git) | **PASS** — real-internet matrix + negatives, peak 63 MB |
|
|
100
|
+
| M2 | Hold one `x` request, ask, keep everything else running | **PASS** — 9-scenario hold matrix, 120 s + never timeouts |
|
|
101
|
+
| M3 | Decide r/w/x deterministically (rwxmap + bareguard), audit log | |
|
|
102
|
+
| M4 | Undo layer: `diff`, `commit`, `rollback`, conflict flagging | **PASS** — paper + review flow implemented, full bwrap+unix proof in a real shell |
|
|
103
|
+
| M5 | Keys the agent never holds | |
|
|
104
|
+
| M6 | Scale run: 20 agents + shared proxy | |
|
|
105
|
+
| M7 | Demos: payment held for approval; prompt-injected `~/.ssh` exfil blocked | |
|
|
106
|
+
|
|
107
|
+
M0–M2 are the go/no-go. Later: macOS (`sandbox-exec` + APFS clones), Windows via WSL2, Landlock/seccomp hardening. Full spec: [the PRD](docs/product/agent-sandbox-prd.md).
|
|
108
|
+
|
|
109
|
+
## Install
|
|
110
|
+
|
|
111
|
+
```
|
|
112
|
+
npm install barebox
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Requires Node.js >= 22. Zero production dependencies. Needs bubblewrap >= 0.11.0 for `--overlay` / `sbx diff|commit|rollback` (Ubuntu 24.04 ships 0.9.0: build from source or use a newer distro); plain runs work with older bwrap. CI builds bubblewrap 0.12.0 from a checksum-pinned source tarball and fails if any test is skipped. The API is in [`barebox.context.md`](barebox.context.md) and `primitives.json` (both ship in the package); the `sbx` CLI comes with it.
|
|
116
|
+
|
|
117
|
+
## Try the POCs
|
|
118
|
+
|
|
119
|
+
Linux with `bwrap` (>= 0.11.0 only for the overlay), `socat`, `openssl`, Node >= 22 and Python 3. Needs a normal shell (namespaces + listening sockets), not a tool sandbox. The POCs are throwaway proofs, not the product.
|
|
120
|
+
|
|
121
|
+
```
|
|
122
|
+
git clone https://github.com/hamr0/barebox && cd barebox
|
|
123
|
+
npm run poc:m0 # 20 sandboxes, bypass suite
|
|
124
|
+
npm run redteam:m0 # breaks each wall on purpose; passes iff all detected
|
|
125
|
+
bash poc/m1/run-m1.sh local # HTTPS inspection against a local TLS echo server
|
|
126
|
+
bash poc/m1/run-m1.sh real # same, real internet, incl. git over https
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## The bare ecosystem
|
|
130
|
+
|
|
131
|
+
Local-first, composable agent infrastructure. Same API patterns throughout —
|
|
132
|
+
mix and match, each module works standalone.
|
|
133
|
+
|
|
134
|
+
**Core** — the brain, the gate, the walls, the memory.
|
|
135
|
+
|
|
136
|
+
- **[bareagent](https://npmjs.com/package/bare-agent)** — the think→act→observe loop. *Goal in → coordinated actions out.* Replaces LangChain, CrewAI, AutoGen.
|
|
137
|
+
- **[bareguard](https://npmjs.com/package/bareguard)** — the single gate every action passes through. *Action in → allow / deny / ask-a-human out. Work in → green / red.* Replaces hand-rolled allowlists and scattered policy code.
|
|
138
|
+
- **[barebox](https://github.com/hamr0/barebox)** [WIP] — the walls and the front door, this repo. *Agent in → contained run out: writes undoable, irreversible actions held for a human.* Replaces Docker/VM isolation and approve-everything prompts.
|
|
139
|
+
- **[litectx](https://npmjs.com/package/litectx)** — tree-sitter code + memory graph with activation decay, plus lightweight context engineering (write · select · compress · isolate). *Query in → ranked context out.*
|
|
140
|
+
|
|
141
|
+
**Add-on for bareguard** — labels API operations for the gate.
|
|
142
|
+
|
|
143
|
+
- **[rwxmap](https://github.com/hamr0/rwxmap)** [WIP] — labels every OpenAPI operation r/w/x as a starting point, marked for review. *API spec in → per-operation letter out.* barebox's doorman uses its labels for known APIs.
|
|
144
|
+
|
|
145
|
+
**Optional reach** — give the agent hands.
|
|
146
|
+
|
|
147
|
+
- **[barebrowse](https://npmjs.com/package/barebrowse)** — a real browser for agents. *URL in → pruned snapshot out.* Replaces Playwright, Selenium, Puppeteer.
|
|
148
|
+
- **[baremobile](https://npmjs.com/package/baremobile)** — Android + iOS device control. *Screen in → pruned snapshot out.* Replaces Appium, Espresso, XCUITest.
|
|
149
|
+
- **[beeperbox](https://github.com/hamr0/beeperbox)** — 50+ messaging networks via one MCP server (headless Beeper Desktop in Docker). *Chat in → unified message stream out.* Replaces Twilio, per-platform bot APIs.
|
|
150
|
+
|
|
151
|
+
bareguard decides the action; barebox contains where it runs.
|
|
152
|
+
|
|
153
|
+
## License
|
|
154
|
+
|
|
155
|
+
Apache 2.0. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# barebox.context.md — complete adopter contract (independent quickstart)
|
|
2
|
+
|
|
3
|
+
barebox is a lightweight local sandbox for AI agents: every write undoable,
|
|
4
|
+
nothing leaves the machine without passing the doorman.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
Requires Node >= 22 and Linux with unprivileged user namespaces (bwrap)
|
|
9
|
+
for sandboxes; the proxy and CLI run anywhere Node runs.
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install barebox
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
`primitives.json` (shipped at package root) lists every public primitive
|
|
16
|
+
with its contract. Use it to pick imports; the JSDoc on each export is
|
|
17
|
+
the full reference.
|
|
18
|
+
|
|
19
|
+
## 60-second quickstart
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npx sbx --help
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
```js
|
|
26
|
+
import { createProxy, launch } from "barebox";
|
|
27
|
+
import { mkdtempSync } from "node:fs";
|
|
28
|
+
import { tmpdir } from "node:os";
|
|
29
|
+
import { join } from "node:path";
|
|
30
|
+
// one sandboxed agent: walls up, front door on, locked drawers masked.
|
|
31
|
+
// The agent's socket must already be listening: create the front door,
|
|
32
|
+
// then add the agent to it.
|
|
33
|
+
const runtime = mkdtempSync(join(tmpdir(), "sbx-"));
|
|
34
|
+
const proj = mkdtempSync(join(tmpdir(), "proj-"));
|
|
35
|
+
const proxy = createProxy({ runtime, port: 0, logFile: join(runtime, "mitm.log") });
|
|
36
|
+
await proxy.ready;
|
|
37
|
+
const child = launch({ runtime, agent: "fx", proj, command: ["bash", "-c", "echo hi"], socket: proxy.addAgent("fx"), caFile: proxy.caFile });
|
|
38
|
+
await new Promise((r) => child.on("close", r));
|
|
39
|
+
await proxy.close();
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
```js
|
|
43
|
+
import { createProxy } from "barebox";
|
|
44
|
+
import { mkdtempSync } from "node:fs";
|
|
45
|
+
import { tmpdir } from "node:os";
|
|
46
|
+
import { join } from "node:path";
|
|
47
|
+
// the front door: terminates agent TLS, logs every request, parks holds.
|
|
48
|
+
// The TCP port is opt-in for tests (bound to 127.0.0.1); agents connect
|
|
49
|
+
// over their own unix socket: proxy.addAgent("fx") -> <runtime>/socks/fx.sock
|
|
50
|
+
const runtime = mkdtempSync(join(tmpdir(), "sbx-"));
|
|
51
|
+
const proxy = createProxy({ runtime, port: 0, logFile: join(runtime, "mitm.log") });
|
|
52
|
+
await proxy.ready;
|
|
53
|
+
await proxy.close();
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Holds (human approval)
|
|
57
|
+
|
|
58
|
+
Start the proxy with a hold rule, then decide from a second terminal
|
|
59
|
+
through the file checkpoint (`<runtime>/asks` + `<runtime>/answers`):
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
SBX_RUNTIME=/tmp/sbx npx sbx pending
|
|
63
|
+
SBX_RUNTIME=/tmp/sbx npx sbx approve h1
|
|
64
|
+
SBX_RUNTIME=/tmp/sbx npx sbx deny h2 "reason here"
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Held requests wait (default 120 s, `never` supported); approve forwards,
|
|
68
|
+
deny and timeout answer 403 with the reason. These commands need the proxy
|
|
69
|
+
to be alive: with no live proxy on the runtime `sbx pending`, `approve` and
|
|
70
|
+
`deny` exit 1 and say so, because nothing would read the answer.
|
|
71
|
+
|
|
72
|
+
## One call: `run()` and `sbx run`
|
|
73
|
+
|
|
74
|
+
`run()` starts the proxy, sandboxes one command, answers holds and returns
|
|
75
|
+
the exit code with the ask and audit trail. Modes: `ask`, `auto` (default),
|
|
76
|
+
`trust`. Payment destinations (`/checkout`, `/payment`, `/orders`,
|
|
77
|
+
`/purchase`) hold in every mode; `ask` and `auto` also hold every
|
|
78
|
+
non-GET/HEAD request (an interim rule until the policy module lands).
|
|
79
|
+
|
|
80
|
+
```js no-run
|
|
81
|
+
import { run } from "barebox";
|
|
82
|
+
const { exit, asks, audit, diff, runtime } = await run({
|
|
83
|
+
proj: "/path/to/project",
|
|
84
|
+
command: ["bash", "-c", "echo hi"],
|
|
85
|
+
mode: "auto",
|
|
86
|
+
overlay: true, // writes land on the undo layer; `diff` lists them
|
|
87
|
+
onAsk: async (ask) => ({ decision: "deny", reason: "not today" }), // omit for the file checkpoint
|
|
88
|
+
});
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
sbx run [--mode ask|auto|trust] [--json] [--overlay] -- <cmd> [...]
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
`sbx run` uses the current directory as the project and `SBX_RUNTIME` as the
|
|
96
|
+
runtime (a short temp dir otherwise, printed on stderr). It prints an `ask`
|
|
97
|
+
line when a request parks and a `decided` line when it ends, then `done`;
|
|
98
|
+
with `--json` stdout carries only JSON lines. Its exit code mirrors the
|
|
99
|
+
agent's.
|
|
100
|
+
|
|
101
|
+
## Undo layer
|
|
102
|
+
|
|
103
|
+
`overlay: true` (`sbx run --overlay`) mounts a per-run upper over the
|
|
104
|
+
project: the agent sees the real files, every write lands on the upper.
|
|
105
|
+
Review and press it down from the same runtime:
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
SBX_RUNTIME=/tmp/sbx npx sbx diff [--agent <name>] # A/M/D, conflicts flagged
|
|
109
|
+
SBX_RUNTIME=/tmp/sbx npx sbx commit [--skip-conflicts] # refuses on conflicts by default
|
|
110
|
+
SBX_RUNTIME=/tmp/sbx npx sbx rollback # throw the paper away
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
A path the project changed after the run started is a conflict: commit
|
|
114
|
+
refuses all of it unless `--skip-conflicts`. `node_modules` is invisible to
|
|
115
|
+
the layer (extend with `SBX_OVERLAY_IGNORE=a,b`). Commit strips setuid/setgid
|
|
116
|
+
and does not keep mtimes; a killed commit leaves a `.sbx-commit-*` folder in
|
|
117
|
+
the project that blocks the next diff/commit/run until you remove it. The
|
|
118
|
+
library equivalents are `diffOverlay`, `commitOverlay` and `rollbackOverlay`.
|
|
119
|
+
The overlay 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.
|
|
120
|
+
|
|
121
|
+
## Gotchas
|
|
122
|
+
|
|
123
|
+
- Agent socket paths must fit the ~108-byte unix limit: `launch()` throws
|
|
124
|
+
with the path and its length past 107 chars. Keep `runtime` short.
|
|
125
|
+
- `launch({ caFile })` is what makes HTTPS work inside: it binds a combined
|
|
126
|
+
bundle (system roots + barebox CA) and sets `SSL_CERT_FILE`,
|
|
127
|
+
`NODE_EXTRA_CA_CERTS`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`,
|
|
128
|
+
`GIT_SSL_CAINFO`. Without it every HTTPS call from inside fails
|
|
129
|
+
verification. Only `ca.pem` enters the sandbox, never the key.
|
|
130
|
+
- Certificates live in `<runtime>/certs` (`runtime` is required). There is no `certDir` option and no control socket: decisions flow through `<runtime>/asks` + `<runtime>/answers` or `hold.onAsk`.
|
|
131
|
+
- The upstream wall answers `403` for loopback, link-local (incl. `169.254.169.254`), the host's own addresses, private LAN ranges and unresolvable names. Every DNS answer is checked and the dial is pinned to the checked IP; test-only options live under `unsafeTestOnly` (`allowLoopback`, `resolveUpstream`) and production never sets them.
|
|
132
|
+
- The audit log (`logFile`) is set to `0600` every time a proxy starts. The values of `Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie`, `X-Api-Key`, `X-Auth-Token` and `Api-Key` are logged as `[redacted]`; other headers and bodies are logged as-is unless your `redact` hook shapes them (it runs after the built-in scrub).
|
|
133
|
+
- One proxy per runtime: `createProxy` throws "in use by pid N" (`run()` rejects, `sbx run` exits 1) while a live proxy owns the runtime. The claim is held by the proxy process and the kernel frees it when the process dies, so a crashed proxy never blocks the runtime. Use another `SBX_RUNTIME`, or leave it unset for a fresh one.
|
|
134
|
+
- `launch()` starts the agent in the project dir, in a new session (no controlling terminal). Locked drawers are 21 credential stores (see `LOCKED_PATHS` in `src/launcher.js`); the agent's own model credentials in `~/.claude` stay readable until keys move out of its reach.
|
|
135
|
+
- `sbx` exits 0 ok, 1 unknown id / refused / no live proxy / run failure, 2 usage; `sbx run` mirrors the agent's exit code.
|
|
136
|
+
- 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.
|
|
137
|
+
|
|
138
|
+
## What this package does not do
|
|
139
|
+
|
|
140
|
+
Enforcement policy (which requests hold) arrives in a later module; until
|
|
141
|
+
then holds follow the interim rules above (a path rule for `createProxy`;
|
|
142
|
+
payment destinations plus non-GET/HEAD for `run()`). The hold decision never
|
|
143
|
+
sees the request body, so card numbers in a body are not caught yet. No Docker, no MCP server, no macOS/Windows —
|
|
144
|
+
Linux only. POC harnesses live in `poc/` in the repo and never ship.
|
package/package.json
CHANGED
|
@@ -1,14 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "barebox",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.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": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/hamr0/barebox.git"
|
|
9
|
+
},
|
|
10
|
+
"type": "module",
|
|
11
|
+
"main": "./src/index.js",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./types/index.d.ts",
|
|
15
|
+
"default": "./src/index.js"
|
|
16
|
+
},
|
|
17
|
+
"./primitives.json": "./primitives.json"
|
|
18
|
+
},
|
|
19
|
+
"bin": {
|
|
20
|
+
"sbx": "src/cli.js"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"src",
|
|
24
|
+
"types",
|
|
25
|
+
"primitives.json",
|
|
26
|
+
"barebox.context.md",
|
|
27
|
+
"README.md",
|
|
28
|
+
"LICENSE",
|
|
29
|
+
"CHANGELOG.md"
|
|
30
|
+
],
|
|
31
|
+
"primitives": "./primitives.json",
|
|
7
32
|
"engines": {
|
|
8
33
|
"node": ">=22"
|
|
9
34
|
},
|
|
10
35
|
"scripts": {
|
|
11
36
|
"poc:m0": "bash poc/m0/run-m0.sh",
|
|
12
|
-
"redteam:m0": "bash poc/m0/redteam.sh"
|
|
37
|
+
"redteam:m0": "bash poc/m0/redteam.sh",
|
|
38
|
+
"bench": "node scripts/bench.mjs",
|
|
39
|
+
"test": "env -u NODE_USE_ENV_PROXY -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u FTP_PROXY -u http_proxy -u https_proxy -u all_proxy -u ftp_proxy node --test --import ./test/setup-env.mjs \"test/*.test.mjs\"",
|
|
40
|
+
"typecheck": "tsc --noEmit && tsc -p tsconfig.scripts.json",
|
|
41
|
+
"build:types": "tsc",
|
|
42
|
+
"build:primitives": "node scripts/gen-primitives.mjs",
|
|
43
|
+
"check:primitives": "node scripts/gen-primitives.mjs --check",
|
|
44
|
+
"prepack": "npm run build:types",
|
|
45
|
+
"prepublishOnly": "npm run build:primitives && npm run build:types"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@types/node": "22",
|
|
49
|
+
"typescript": "5"
|
|
13
50
|
}
|
|
14
51
|
}
|
package/primitives.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"package": "barebox",
|
|
3
|
+
"primitives": [
|
|
4
|
+
{
|
|
5
|
+
"name": "commitOverlay",
|
|
6
|
+
"category": "overlay",
|
|
7
|
+
"when": "Reach for this to press one run's tracing paper down: it stages the sandbox's changes and swaps them into the project by rename, refusing loudly on mid-run conflicts.",
|
|
8
|
+
"import": "import { commitOverlay } from 'barebox'",
|
|
9
|
+
"signature": "commitOverlay(opts: object) => {committed: string[], skipped: {path: string, reason: string}[]}",
|
|
10
|
+
"fails": "Throws (writing nothing) when any changed file was also changed in the project mid-run, unless onConflict is `skip`; throws on unsupported file kinds, on a project that moved mid-commit, and when bubblewrap is older than 0.11.0. A phase-2 failure undoes every journaled step: a full undo reports `nothing was applied`, a partial one throws `SBX_COMMIT_FAILED` listing exactly the steps not undone and keeping the commit folder (originals in `old/`) named in the error. Setuid/setgid bits are stripped from committed modes; mtimes are not preserved. A killed commit leaves a folder that blocks the next diff/commit/setup until removed.",
|
|
11
|
+
"example": "import { commitOverlay } from \"barebox\";\nconst { committed, skipped } = commitOverlay({ runtime: \"/tmp/sbx-abc\", agent: \"agent\" });\nconsole.log(`committed ${committed.length} file(s), skipped ${skipped.length}`);"
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
"name": "createProxy",
|
|
15
|
+
"category": "proxy",
|
|
16
|
+
"when": "Reach for this HARNESS-ONLY to run the front door: it terminates agent TLS, sees every request, and parks the ones a human must decide. It decides nothing itself; pair with the launcher for sandboxes and `sbx` for decisions.",
|
|
17
|
+
"import": "import { createProxy } from 'barebox'",
|
|
18
|
+
"signature": "createProxy(opts: ProxyOptions)",
|
|
19
|
+
"fails": "Throws synchronously on a missing `logFile` or `runtime`. Throws when another live proxy owns the runtime; the claim dies with its process; nothing is ever taken over. At runtime, dead upstreams, malformed input, over-cap and timed-out holds all become loud logged HTTP errors, never silence and never a crash. A second proxy on the same port rejects `ready`, never crashes the process.",
|
|
20
|
+
"example": "import { createProxy } from \"barebox\";\nconst proxy = createProxy({ port: 0, runtime: \"./sbx-runtime\", logFile: \"./mitm.log\" });\nconst { port } = await proxy.ready;\nawait proxy.close();"
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
"name": "diffOverlay",
|
|
24
|
+
"category": "overlay",
|
|
25
|
+
"when": "Reach for this to review one run's tracing paper: it lists every file the sandboxed run added, modified or deleted, flagging the ones the project changed meanwhile.",
|
|
26
|
+
"import": "import { diffOverlay } from 'barebox'",
|
|
27
|
+
"signature": "diffOverlay(opts: object) => OverlayChange[]",
|
|
28
|
+
"fails": "Throws when no overlay exists for the agent, when the project is gone, when a leftover commit folder blocks, when bubblewrap is older than 0.11.0, or when the overlay view cannot be mounted; never writes anything.",
|
|
29
|
+
"example": "import { diffOverlay } from \"barebox\";\nconst changes = diffOverlay({ runtime: \"/tmp/sbx-abc\", agent: \"agent\" });\nfor (const c of changes) console.log(c.status, c.path, c.conflict ? \"(CONFLICT)\" : \"\");"
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
"name": "launch",
|
|
33
|
+
"category": "launcher",
|
|
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
|
+
"import": "import { launch } from 'barebox'",
|
|
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.",
|
|
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
|
+
},
|
|
40
|
+
{
|
|
41
|
+
"name": "rollbackOverlay",
|
|
42
|
+
"category": "overlay",
|
|
43
|
+
"when": "Reach for this to throw one run's tracing paper away: it drops every sandboxed change and leaves the project exactly as it was.",
|
|
44
|
+
"import": "import { rollbackOverlay } from 'barebox'",
|
|
45
|
+
"signature": "rollbackOverlay(opts: object) => {discarded: OverlayChange[], exact: boolean, why: string|null}",
|
|
46
|
+
"fails": "Throws when no overlay exists for the agent or its record is corrupt, or when the overlay folder cannot be removed even after a permission repair (the error names the folder). Listing the changes never throws and never invents entries: an unlistable upper reports `discarded: []` with the reasons in `why`. Removal depends on neither listing nor the first permission pass: a partial failure retries removal once after a fresh permission pass. Dropping the upper never touches the project.",
|
|
47
|
+
"example": "import { rollbackOverlay } from \"barebox\";\nconst { discarded } = rollbackOverlay({ runtime: \"/tmp/sbx-abc\", agent: \"agent\" });\nconsole.log(`discarded ${discarded.length} change(s)`);"
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
"name": "run",
|
|
51
|
+
"category": "run",
|
|
52
|
+
"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
|
+
"import": "import { run } from 'barebox'",
|
|
54
|
+
"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.",
|
|
56
|
+
"example": "import { run } from \"barebox\";\nconst { exit, asks, audit } = await run({ proj: \"/tmp/proj\", command: [\"bash\", \"-c\", \"echo hi\"] });"
|
|
57
|
+
}
|
|
58
|
+
]
|
|
59
|
+
}
|
package/src/certs.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// certs.js — owns the CA and per-host certificates on disk.
|
|
2
|
+
//
|
|
3
|
+
// The proxy mints a certificate for every host the agent talks to, on first
|
|
4
|
+
// CONNECT. Nothing is pre-generated: a fresh runtime dir works on any host.
|
|
5
|
+
// Minting shells out to `openssl` (the PRD decision: no JS crypto for X.509).
|
|
6
|
+
import { execFile } from 'node:child_process';
|
|
7
|
+
import { mkdirSync, chmodSync, existsSync, writeFileSync, rmSync } from 'node:fs';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
|
|
10
|
+
/** Hostname/IP spelling both the mint cache and the proxy wall accept. Single definition (see proxy.js). */
|
|
11
|
+
export const HOST_RE = /^[A-Za-z0-9.-]+$/;
|
|
12
|
+
|
|
13
|
+
function sh(file, args) {
|
|
14
|
+
return new Promise((resolve, reject) => {
|
|
15
|
+
execFile(file, args, (err, stdout, stderr) => {
|
|
16
|
+
if (err) reject(new Error(`${file} ${args[0]} failed: ${(stderr || err.message).trim()}`));
|
|
17
|
+
else resolve(stdout);
|
|
18
|
+
});
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// In-flight mints, so concurrent CONNECTs to a new host mint once.
|
|
23
|
+
const inflight = new Map();
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Create the CA in `dir` unless it already exists. Safe to call twice:
|
|
27
|
+
* an existing `ca.pem` is reused, never regenerated.
|
|
28
|
+
*
|
|
29
|
+
* @param {string} dir directory that holds `ca.key` / `ca.pem`
|
|
30
|
+
* @returns {Promise<{ keyPath: string, certPath: string }>} paths of the CA key and cert
|
|
31
|
+
*/
|
|
32
|
+
export async function ensureCA(dir) {
|
|
33
|
+
mkdirSync(dir, { recursive: true });
|
|
34
|
+
const keyPath = join(dir, 'ca.key');
|
|
35
|
+
const certPath = join(dir, 'ca.pem');
|
|
36
|
+
if (existsSync(certPath)) return { keyPath, certPath };
|
|
37
|
+
await sh('openssl', ['genrsa', '-out', keyPath, '2048']);
|
|
38
|
+
chmodSync(keyPath, 0o600);
|
|
39
|
+
const ext = join(dir, 'ca.ext.tmp');
|
|
40
|
+
writeFileSync(ext,
|
|
41
|
+
'basicConstraints=critical,CA:true\n' +
|
|
42
|
+
'keyUsage=critical,keyCertSign,cRLSign,digitalSignature\n' +
|
|
43
|
+
'subjectKeyIdentifier=hash\n' +
|
|
44
|
+
'authorityKeyIdentifier=keyid:always,issuer\n');
|
|
45
|
+
try {
|
|
46
|
+
await sh('openssl', ['req', '-new', '-key', keyPath, '-out', join(dir, 'ca.csr.tmp'),
|
|
47
|
+
'-subj', '/CN=barebox-ca']);
|
|
48
|
+
await sh('openssl', ['x509', '-req', '-in', join(dir, 'ca.csr.tmp'),
|
|
49
|
+
'-signkey', keyPath, '-sha256', '-days', '825',
|
|
50
|
+
'-out', certPath, '-extfile', ext]);
|
|
51
|
+
} finally {
|
|
52
|
+
rmSync(join(dir, 'ca.csr.tmp'), { force: true });
|
|
53
|
+
rmSync(ext, { force: true });
|
|
54
|
+
}
|
|
55
|
+
return { keyPath, certPath };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Return the key/cert for `host`, minting and caching on disk on first use.
|
|
60
|
+
* Concurrent calls for the same host share one `openssl` run. Key files
|
|
61
|
+
* are created with mode `0600`.
|
|
62
|
+
*
|
|
63
|
+
* @param {string} dir directory holding the CA (see {@link ensureCA})
|
|
64
|
+
* @param {string} host hostname or IP from the CONNECT line
|
|
65
|
+
* @returns {Promise<{ key: Buffer, cert: Buffer }>} PEM buffers for `tls.createSecureContext`
|
|
66
|
+
*/
|
|
67
|
+
export async function certFor(dir, host) {
|
|
68
|
+
if (!HOST_RE.test(host || '')) throw new Error(`certFor: bad host ${JSON.stringify(host)}`);
|
|
69
|
+
const { readFileSync } = await import('node:fs');
|
|
70
|
+
const keyPath = join(dir, `${host}.key`);
|
|
71
|
+
const certPath = join(dir, `${host}.pem`);
|
|
72
|
+
if (existsSync(keyPath) && existsSync(certPath)) {
|
|
73
|
+
return { key: readFileSync(keyPath), cert: readFileSync(certPath) };
|
|
74
|
+
}
|
|
75
|
+
let p = inflight.get(host);
|
|
76
|
+
if (!p) {
|
|
77
|
+
p = mint(dir, host, keyPath, certPath).finally(() => { inflight.delete(host); });
|
|
78
|
+
inflight.set(host, p);
|
|
79
|
+
}
|
|
80
|
+
return p;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function mint(dir, host, keyPath, certPath) {
|
|
84
|
+
const { readFileSync } = await import('node:fs');
|
|
85
|
+
await ensureCA(dir);
|
|
86
|
+
// A crashed mint must not leave half a pair behind that later reads as valid.
|
|
87
|
+
rmSync(keyPath, { force: true });
|
|
88
|
+
rmSync(certPath, { force: true });
|
|
89
|
+
await sh('openssl', ['genrsa', '-out', keyPath, '2048']);
|
|
90
|
+
chmodSync(keyPath, 0o600);
|
|
91
|
+
const san = /^\d+\.\d+\.\d+\.\d+$/.test(host) ? `IP:${host}` : `DNS:${host}`;
|
|
92
|
+
const ext = join(dir, `${host}.ext.tmp`);
|
|
93
|
+
const csr = join(dir, `${host}.csr.tmp`);
|
|
94
|
+
writeFileSync(ext,
|
|
95
|
+
'basicConstraints=CA:false\n' +
|
|
96
|
+
'keyUsage=digitalSignature,keyEncipherment\n' +
|
|
97
|
+
'extendedKeyUsage=serverAuth\n' +
|
|
98
|
+
`subjectAltName=${san}\n`);
|
|
99
|
+
const { keyPath: caKey, certPath: caCert } = await ensureCA(dir);
|
|
100
|
+
try {
|
|
101
|
+
await sh('openssl', ['req', '-new', '-key', keyPath, '-out', csr, '-subj', `/CN=${host}`]);
|
|
102
|
+
await sh('openssl', ['x509', '-req', '-in', csr, '-CA', caCert, '-CAkey', caKey,
|
|
103
|
+
'-CAcreateserial', '-days', '825', '-sha256', '-out', certPath, '-extfile', ext]);
|
|
104
|
+
} finally {
|
|
105
|
+
rmSync(csr, { force: true });
|
|
106
|
+
rmSync(ext, { force: true });
|
|
107
|
+
}
|
|
108
|
+
return { key: readFileSync(keyPath), cert: readFileSync(certPath) };
|
|
109
|
+
}
|