barebox 0.1.0 → 0.2.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 ADDED
@@ -0,0 +1,37 @@
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.2.0] - 2026-10-27
8
+
9
+ Graduation rewrite: the M0-M2 POCs become a library.
10
+
11
+ ### Added
12
+
13
+ - `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.
14
+ - 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.
15
+ - Hold queue: requests park for approve/deny or time out; holds abandoned by a disconnecting client are dropped; `maxBody` caps queued bodies.
16
+ - `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).
17
+ - `sbx` CLI: `pending`, `approve`, `deny`, `--help`, defined exit codes; socket from `SBX_SOCK` or `SBX_RUNTIME`, with no cwd default.
18
+ - `npm run bench`: per-sandbox and proxy RSS benchmark.
19
+ - TypeScript types, `primitives.json` and `barebox.context.md`.
20
+
21
+ ### Changed
22
+
23
+ - `createProxy` throws unless `certDir` and the control socket live inside `runtime` (real paths compared).
24
+
25
+ ### Fixed
26
+
27
+ - POST/PUT bodies to real hostnames no longer hang; the client stream is paused until the upstream pipe is attached.
28
+
29
+ ### Security
30
+
31
+ - Audit log is created 0600 and `Authorization` headers are scrubbed from logged lines.
32
+
33
+ ## [0.1.0] - 2026-10-26
34
+
35
+ ### Added
36
+
37
+ - Reserved `barebox` on npm; repo scaffold (docs, M0 throwaway POC, publish workflow).
package/README.md CHANGED
@@ -1,10 +1,155 @@
1
- # barebox
1
+ ```
2
+ ┌──────────────┐
3
+ │ agent inside │
4
+ │ r w x │── doorman ──▶ world
5
+ └──────────────┘
6
+ read undo ask
2
7
 
3
- Lightweight local sandbox for AI agents: an agent runs on your machine with your
4
- real tools, every write is undoable, and nothing leaves the machine without
5
- passing a doorman. You're asked only when something irreversible is about to happen.
8
+ barebox
9
+ ```
6
10
 
7
- Status: M0 (walls + front door) proven and red-teamed, POC-grade. See
8
- [the PRD](docs/product/agent-sandbox-prd.md) and [poc/m0](poc/m0).
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
- `bin/sbx` and the test suite arrive with the graduation rewrite (after M2).
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:** POC. The walls (M0), HTTPS inspection (M1), and hold-and-ask (M2) are proven and measured. The npm package is a name reservation — the API lands with the graduation rewrite next. 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.
45
+ - **Locked drawers (r).** It reads most things. `~/.ssh`, `~/secrets`, `~/.gnupg`, browser profiles stay shut.
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 |
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/product/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 | |
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. Published 0.1.0 is the reservation scaffold — nothing to import yet.
116
+
117
+ ## Try the POCs
118
+
119
+ Linux with `bwrap`, `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,76 @@
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 { launch } from "barebox";
27
+ // one sandboxed agent: walls up, front door on :3128, locked drawers masked.
28
+ // The agent's socket must already be listening: proxy.addAgent("fx").
29
+ const child = launch({ runtime: "/tmp/sbx", agent: "fx", proj: "/tmp/proj", command: ["bash", "-c", "echo hi"] });
30
+ await new Promise((r) => child.on("close", r));
31
+ ```
32
+
33
+ ```js
34
+ import { createProxy } from "barebox";
35
+ // the front door: terminates agent TLS, logs every request, parks holds.
36
+ // The TCP port is opt-in for tests (bound to 127.0.0.1); agents connect
37
+ // over their own unix socket: proxy.addAgent("fx") -> <runtime>/socks/fx.sock
38
+ const proxy = createProxy({ port: 3129, certDir: "./certs", logFile: "./mitm.log" });
39
+ await proxy.ready;
40
+ await proxy.close();
41
+ ```
42
+
43
+ ## Holds (human approval)
44
+
45
+ Start the proxy with a hold rule and a control socket, then decide from a
46
+ second terminal:
47
+
48
+ ```bash
49
+ SBX_SOCK=/tmp/sbx/ctl.sock npx sbx pending
50
+ SBX_SOCK=/tmp/sbx/ctl.sock npx sbx approve h1
51
+ SBX_SOCK=/tmp/sbx/ctl.sock npx sbx deny h2 "reason here"
52
+ ```
53
+
54
+ Held requests wait (default 120 s, `never` supported); approve forwards,
55
+ deny and timeout answer 403 with the reason.
56
+
57
+ ## Gotchas
58
+
59
+ - Agent socket paths must fit the ~108-byte unix limit: `launch()` throws
60
+ with the path and its length past 107 chars. Keep `runtime` short.
61
+ - `launch({ caFile })` is what makes HTTPS work inside: it binds a combined
62
+ bundle (system roots + barebox CA) and sets `SSL_CERT_FILE`,
63
+ `NODE_EXTRA_CA_CERTS`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`,
64
+ `GIT_SSL_CAINFO`. Without it every HTTPS call from inside fails
65
+ verification. Only `ca.pem` enters the sandbox, never the key.
66
+ - `createProxy` throws if `certDir` or `controlSocket` is not inside `runtime` (real paths, so symlinks don't help): the launcher masks only the runtime dir, and `ca.key` / the approve socket must stay behind it. The default `<runtime>/certs` always passes.
67
+ - 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; `allowLoopback` is test-only.
68
+ - The audit log (`logFile`) is created `0600`, but only when the file is new. `Authorization` and `Proxy-Authorization` values are logged as `[redacted]`; other headers (cookies, API-key headers) and bodies are logged as-is unless your `redact` hook shapes them (it runs after the built-in scrub).
69
+ - `sbx` exits 0 ok, 1 unknown id / refused / socket failure, 2 usage.
70
+ - 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.
71
+
72
+ ## What this package does not do
73
+
74
+ Enforcement policy (which requests hold) arrives in a later module; this
75
+ release parks by path rule. No Docker, no MCP server, no macOS/Windows —
76
+ 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.1.0",
3
+ "version": "0.2.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
- "type": "commonjs",
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",
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
  }
@@ -0,0 +1,23 @@
1
+ {
2
+ "package": "barebox",
3
+ "primitives": [
4
+ {
5
+ "name": "createProxy",
6
+ "category": "proxy",
7
+ "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.",
8
+ "import": "import { createProxy } from 'barebox'",
9
+ "signature": "createProxy(opts: ProxyOptions)",
10
+ "fails": "Throws synchronously on a missing `logFile` (or neither `certDir` nor `runtime`). 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.",
11
+ "example": "import { createProxy } from \"barebox\";\nconst proxy = createProxy({ port: 0, certDir: \"./certs\", logFile: \"./mitm.log\" });\nconst { port } = await proxy.ready;\nawait proxy.close();"
12
+ },
13
+ {
14
+ "name": "launch",
15
+ "category": "launcher",
16
+ "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.",
17
+ "import": "import { launch } from 'barebox'",
18
+ "signature": "launch(opts: object) => ChildProcess",
19
+ "fails": "Throws synchronously on a missing/empty `runtime`, `agent`, `proj`, or `command`, on a bad agent name, on an over-long socket path, when `socket` disagrees with `<runtime>/socks/<agent>.sock`, or when `runtime` IS `HOME` or the project dir (its sockets could not be hidden from the agent). The child fails at runtime (nonzero exit) when `bwrap` or `socat` is missing inside, or when nothing listens on the agent socket.",
20
+ "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"
21
+ }
22
+ ]
23
+ }
package/src/certs.js ADDED
@@ -0,0 +1,108 @@
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
+ const HOST_RE = /^[A-Za-z0-9.-]+$/;
11
+
12
+ function sh(file, args) {
13
+ return new Promise((resolve, reject) => {
14
+ execFile(file, args, (err, stdout, stderr) => {
15
+ if (err) reject(new Error(`${file} ${args[0]} failed: ${(stderr || err.message).trim()}`));
16
+ else resolve(stdout);
17
+ });
18
+ });
19
+ }
20
+
21
+ // In-flight mints, so concurrent CONNECTs to a new host mint once.
22
+ const inflight = new Map();
23
+
24
+ /**
25
+ * Create the CA in `dir` unless it already exists. Safe to call twice:
26
+ * an existing `ca.pem` is reused, never regenerated.
27
+ *
28
+ * @param {string} dir directory that holds `ca.key` / `ca.pem`
29
+ * @returns {Promise<{ keyPath: string, certPath: string }>} paths of the CA key and cert
30
+ */
31
+ export async function ensureCA(dir) {
32
+ mkdirSync(dir, { recursive: true });
33
+ const keyPath = join(dir, 'ca.key');
34
+ const certPath = join(dir, 'ca.pem');
35
+ if (existsSync(certPath)) return { keyPath, certPath };
36
+ await sh('openssl', ['genrsa', '-out', keyPath, '2048']);
37
+ chmodSync(keyPath, 0o600);
38
+ const ext = join(dir, 'ca.ext.tmp');
39
+ writeFileSync(ext,
40
+ 'basicConstraints=critical,CA:true\n' +
41
+ 'keyUsage=critical,keyCertSign,cRLSign,digitalSignature\n' +
42
+ 'subjectKeyIdentifier=hash\n' +
43
+ 'authorityKeyIdentifier=keyid:always,issuer\n');
44
+ try {
45
+ await sh('openssl', ['req', '-new', '-key', keyPath, '-out', join(dir, 'ca.csr.tmp'),
46
+ '-subj', '/CN=barebox-ca']);
47
+ await sh('openssl', ['x509', '-req', '-in', join(dir, 'ca.csr.tmp'),
48
+ '-signkey', keyPath, '-sha256', '-days', '825',
49
+ '-out', certPath, '-extfile', ext]);
50
+ } finally {
51
+ rmSync(join(dir, 'ca.csr.tmp'), { force: true });
52
+ rmSync(ext, { force: true });
53
+ }
54
+ return { keyPath, certPath };
55
+ }
56
+
57
+ /**
58
+ * Return the key/cert for `host`, minting and caching on disk on first use.
59
+ * Concurrent calls for the same host share one `openssl` run. Key files
60
+ * are created with mode `0600`.
61
+ *
62
+ * @param {string} dir directory holding the CA (see {@link ensureCA})
63
+ * @param {string} host hostname or IP from the CONNECT line
64
+ * @returns {Promise<{ key: Buffer, cert: Buffer }>} PEM buffers for `tls.createSecureContext`
65
+ */
66
+ export async function certFor(dir, host) {
67
+ if (!HOST_RE.test(host || '')) throw new Error(`certFor: bad host ${JSON.stringify(host)}`);
68
+ const { readFileSync } = await import('node:fs');
69
+ const keyPath = join(dir, `${host}.key`);
70
+ const certPath = join(dir, `${host}.pem`);
71
+ if (existsSync(keyPath) && existsSync(certPath)) {
72
+ return { key: readFileSync(keyPath), cert: readFileSync(certPath) };
73
+ }
74
+ let p = inflight.get(host);
75
+ if (!p) {
76
+ p = mint(dir, host, keyPath, certPath).finally(() => { inflight.delete(host); });
77
+ inflight.set(host, p);
78
+ }
79
+ return p;
80
+ }
81
+
82
+ async function mint(dir, host, keyPath, certPath) {
83
+ const { readFileSync } = await import('node:fs');
84
+ await ensureCA(dir);
85
+ // A crashed mint must not leave half a pair behind that later reads as valid.
86
+ rmSync(keyPath, { force: true });
87
+ rmSync(certPath, { force: true });
88
+ await sh('openssl', ['genrsa', '-out', keyPath, '2048']);
89
+ chmodSync(keyPath, 0o600);
90
+ const san = /^\d+\.\d+\.\d+\.\d+$/.test(host) ? `IP:${host}` : `DNS:${host}`;
91
+ const ext = join(dir, `${host}.ext.tmp`);
92
+ const csr = join(dir, `${host}.csr.tmp`);
93
+ writeFileSync(ext,
94
+ 'basicConstraints=CA:false\n' +
95
+ 'keyUsage=digitalSignature,keyEncipherment\n' +
96
+ 'extendedKeyUsage=serverAuth\n' +
97
+ `subjectAltName=${san}\n`);
98
+ const { keyPath: caKey, certPath: caCert } = await ensureCA(dir);
99
+ try {
100
+ await sh('openssl', ['req', '-new', '-key', keyPath, '-out', csr, '-subj', `/CN=${host}`]);
101
+ await sh('openssl', ['x509', '-req', '-in', csr, '-CA', caCert, '-CAkey', caKey,
102
+ '-CAcreateserial', '-days', '825', '-sha256', '-out', certPath, '-extfile', ext]);
103
+ } finally {
104
+ rmSync(csr, { force: true });
105
+ rmSync(ext, { force: true });
106
+ }
107
+ return { key: readFileSync(keyPath), cert: readFileSync(certPath) };
108
+ }
package/src/cli.js ADDED
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env node
2
+ // sbx — second-terminal CLI for the hold queue:
3
+ // sbx pending | approve <id> | deny <id> [reason]
4
+ // Talks to the proxy over its unix control socket. The socket path comes
5
+ // from SBX_SOCK, else from SBX_RUNTIME as `<runtime>/ctl.sock`. There is no
6
+ // cwd-relative default: missing both is a usage error (exit 2).
7
+ import net from 'node:net';
8
+ import path from 'node:path';
9
+
10
+ const USAGE = 'usage: sbx [--help] | pending | approve <id> | deny <id> [reason]';
11
+ // Exit codes: 0 ok, 1 unknown id / refused / socket failure, 2 usage.
12
+ const [cmd, ...args] = process.argv.slice(2);
13
+ if (!cmd || cmd === '--help' || cmd === '-h') {
14
+ console.log(USAGE);
15
+ process.exit(cmd ? 0 : 2);
16
+ }
17
+ if (!['pending', 'approve', 'deny'].includes(cmd) || (cmd !== 'pending' && !args[0])) {
18
+ console.log(USAGE);
19
+ process.exit(2);
20
+ }
21
+ const sockPath = process.env.SBX_SOCK
22
+ || (process.env.SBX_RUNTIME ? path.join(process.env.SBX_RUNTIME, 'ctl.sock') : null);
23
+ if (!sockPath) {
24
+ console.log(USAGE);
25
+ process.exit(2);
26
+ }
27
+
28
+ const s = net.connect(sockPath, () => { s.write([cmd, ...args].join(' ') + '\n'); });
29
+ s.setTimeout(5000, () => {
30
+ console.log('ctl timed out waiting for the proxy');
31
+ s.destroy();
32
+ process.exit(1);
33
+ });
34
+ let out = '';
35
+ s.on('data', (ch) => { out += ch.toString('latin1'); });
36
+ s.on('end', () => {
37
+ if (cmd === 'pending') {
38
+ const items = JSON.parse(out || '[]');
39
+ if (!items.length) { console.log('nothing held'); return; }
40
+ for (const h of items) {
41
+ console.log(`${h.id} ${h.agent} ${h.method} ${h.url} (${h.waitingSec}s) body=${h.body}`);
42
+ }
43
+ return;
44
+ }
45
+ console.log(out.trim());
46
+ if (/^unknown /.test(out.trim())) process.exit(1);
47
+ });
48
+ s.on('error', (e) => { console.log(`ctl failed: ${e.message}`); process.exit(1); });