barebox 0.3.0 → 0.4.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 +23 -0
- package/README.md +3 -3
- package/barebox.context.md +12 -7
- package/package.json +1 -1
- package/primitives.json +1 -1
- package/src/certs.js +22 -2
- package/src/cli.js +2 -2
- package/src/holds.js +168 -9
- package/src/overlay.js +54 -2
- package/src/proxy.js +80 -23
- package/src/run.js +10 -4
- package/src/runtime.js +33 -1
- package/src/wall.js +92 -31
- package/types/holds.d.ts +13 -3
- package/types/overlay.d.ts +8 -0
- package/types/proxy.d.ts +1 -1
- package/types/runtime.d.ts +19 -0
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,29 @@ 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.4.0] - 2026-10-29
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
- Held requests are one per agent (pre-1.0 behaviour change): each agent has at most one held request being read or parked; later ones wait in line, unread, in order. At most 16 wait; the next gets `429 hold queue full`.
|
|
12
|
+
- The hold deadline counts from arrival (default 120 s, `never` supported), time in line and reading the body included; a request past its deadline is denied `hold timeout` whether waiting, sending, or parked.
|
|
13
|
+
- `proxy.removeAgent(name)` ends that agent's open connections, and its held requests end `deny` / `client gone` at once. `run()` calls it when the sandbox exits, so shutting down no longer races a held request into a `proxy closing` log line.
|
|
14
|
+
- An existing runtime dir you don't own (e.g. `SBX_RUNTIME=/tmp`, which 0.3.0 accepted) is now refused with a message naming the dir, its owner and a subdir to use, such as `/tmp/sbx`.
|
|
15
|
+
- 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.
|
|
16
|
+
|
|
17
|
+
### Security
|
|
18
|
+
|
|
19
|
+
- The upstream wall checks an IPv4 embedded in IPv6 in every spelling: IPv4-mapped (`::ffff:7f00:1` as well as `::ffff:127.0.0.1`) and compat forms, uncompressed loopback (`0:0:0:0:0:0:0:1`), NAT64 `64:ff9b::/96` (local-use `64:ff9b:1::/48` denied outright) and 6to4 `2002::/16`. NAT64 and 6to4 of public sites stay reachable.
|
|
20
|
+
- Runtime folders are owner-only (0700) whatever the umask: the runtime root, `asks/`, `answers/` and `socks/`. A runtime dir you own is tightened to 0700.
|
|
21
|
+
- Each minted certificate gets a random 128-bit serial instead of a shared serial file (`ca.srl`) that concurrent mints could corrupt (a failed mint reached the agent as a 502); at most 4 mints run at once.
|
|
22
|
+
|
|
23
|
+
### Fixed
|
|
24
|
+
|
|
25
|
+
- `createProxy` throws synchronously on an unopenable `logFile` and releases the runtime. A later audit-log write error prints one `sbx: audit log … write failed` line to stderr and the proxy keeps running.
|
|
26
|
+
- The `sbx run` "answer with" hint quotes the runtime path, so it is safe to copy-paste.
|
|
27
|
+
- Overlay hashing reads files in 1 MiB chunks, so very large files no longer exhaust memory.
|
|
28
|
+
- `run()` releases the runtime when the agent socket can't be created; the claim no longer stays held refusing a second `run()` on the same runtime as "in use".
|
|
29
|
+
|
|
7
30
|
## [0.3.0] - 2026-10-28
|
|
8
31
|
|
|
9
32
|
Breaking changes (pre-1.0): the control socket, `createProxy`'s `certDir` and `allowUpstream`, `run()`'s low-level options, the hold queue's `approve`/`deny`/`size` and the top-level `allowLoopback` option are removed or moved; `runtime` is now required. Each is marked **Breaking** below.
|
package/README.md
CHANGED
|
@@ -76,7 +76,7 @@ The agent works in your house:
|
|
|
76
76
|
- **Identity** is the socket, not a header the agent could fake. One socket per agent, all into one proxy.
|
|
77
77
|
- **HTTPS inspection** uses a local CA that exists only inside the sandbox; the proxy reads method, URL, headers and body, then forwards.
|
|
78
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.
|
|
79
|
+
- **Approvals** come from a second terminal (`sbx pending`, `sbx approve <id>`, `sbx deny <id>`). Timeout means deny, with a clear `403` reason. One held request per agent at a time: later ones wait in line (16 at most, then `429 hold queue full`), and the deadline counts from arrival.
|
|
80
80
|
|
|
81
81
|
## Numbers
|
|
82
82
|
|
|
@@ -85,9 +85,9 @@ Measured, not estimated. Fedora, kernel 7.2, bubblewrap 0.12.0, Node 22.
|
|
|
85
85
|
| | barebox (measured) | [srt](https://github.com/anthropic-experimental/sandbox-runtime) 0.0.81 (measured) |
|
|
86
86
|
|---|---|---|
|
|
87
87
|
| Memory per sandbox | **7.8 MB** mean, 7.9 MB max (20 concurrent) | ~100 MB |
|
|
88
|
-
| Proxy | one shared, **~60 MB idle, ~
|
|
88
|
+
| Proxy | one shared, **~60 MB idle, ~78 MB loaded** (20 agents, each with 1 parked + 16 waiting; within the ≤ 80 MB budget) | one per sandbox |
|
|
89
89
|
| Start + exit | **10 ms** (M0 POC; unmeasured on the rewrite — TODO re-measure) | 1.87–2.05 s |
|
|
90
|
-
| 20 agents | ~
|
|
90
|
+
| 20 agents | ~234 MB (rough sum: ~78 MB proxy + 20 × 7.8 MB) | ~2 GB |
|
|
91
91
|
|
|
92
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
93
|
|
package/barebox.context.md
CHANGED
|
@@ -64,10 +64,14 @@ SBX_RUNTIME=/tmp/sbx npx sbx approve h1
|
|
|
64
64
|
SBX_RUNTIME=/tmp/sbx npx sbx deny h2 "reason here"
|
|
65
65
|
```
|
|
66
66
|
|
|
67
|
-
Held requests wait (default 120 s, `never` supported)
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
67
|
+
Held requests wait (default 120 s, `never` supported), counting from arrival:
|
|
68
|
+
time spent in line and reading the body counts too, and a request past its
|
|
69
|
+
deadline is denied `hold timeout` whether waiting, sending, or parked. Each
|
|
70
|
+
agent holds at most one request being read or parked; later ones wait in
|
|
71
|
+
line, unread, in order — at most 16, the next gets `429 hold queue full`.
|
|
72
|
+
Approve forwards, deny and timeout answer 403 with the reason. These commands
|
|
73
|
+
need the proxy to be alive: with no live proxy on the runtime `sbx pending`,
|
|
74
|
+
`approve` and `deny` exit 1 and say so, because nothing would read the answer.
|
|
71
75
|
|
|
72
76
|
## One call: `run()` and `sbx run`
|
|
73
77
|
|
|
@@ -127,9 +131,10 @@ The overlay needs bubblewrap >= 0.11.0 for `--overlay` / `sbx diff|commit|rollba
|
|
|
127
131
|
`NODE_EXTRA_CA_CERTS`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`,
|
|
128
132
|
`GIT_SSL_CAINFO`. Without it every HTTPS call from inside fails
|
|
129
133
|
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
|
|
132
|
-
- The
|
|
134
|
+
- 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.
|
|
135
|
+
- 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`.
|
|
136
|
+
- 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.
|
|
137
|
+
- `createProxy` throws synchronously on an unopenable `logFile` (a directory, a missing parent, no permission) and releases the runtime. The runtime root, `asks/`, `answers/` 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 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
138
|
- 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
139
|
- `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
140
|
- `sbx` exits 0 ok, 1 unknown id / refused / no live proxy / run failure, 2 usage; `sbx run` mirrors the agent's exit code.
|
package/package.json
CHANGED
package/primitives.json
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"when": "Reach for this HARNESS-ONLY to run the front door: it terminates agent TLS, sees every request, and parks the ones a human must decide. It decides nothing itself; pair with the launcher for sandboxes and `sbx` for decisions.",
|
|
17
17
|
"import": "import { createProxy } from 'barebox'",
|
|
18
18
|
"signature": "createProxy(opts: ProxyOptions)",
|
|
19
|
-
"fails": "Throws synchronously on a missing `logFile` or `runtime`. Throws when another live proxy owns the runtime; the claim dies with its process; nothing is ever taken over. At runtime, dead upstreams, malformed input, over-cap and timed-out holds all become loud logged HTTP errors, never silence and never a crash. A second proxy on the same port rejects `ready`, never crashes the process.",
|
|
19
|
+
"fails": "Throws synchronously on a missing or unopenable `logFile` or `runtime`. Throws when another live proxy owns the runtime; the claim dies with its process; nothing is ever taken over. At runtime, dead upstreams, malformed input, over-cap and timed-out holds all become loud logged HTTP errors, never silence and never a crash. A second proxy on the same port rejects `ready`, never crashes the process.",
|
|
20
20
|
"example": "import { createProxy } from \"barebox\";\nconst proxy = createProxy({ port: 0, runtime: \"./sbx-runtime\", logFile: \"./mitm.log\" });\nconst { port } = await proxy.ready;\nawait proxy.close();"
|
|
21
21
|
},
|
|
22
22
|
{
|
package/src/certs.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import { execFile } from 'node:child_process';
|
|
7
7
|
import { mkdirSync, chmodSync, existsSync, writeFileSync, rmSync } from 'node:fs';
|
|
8
8
|
import { join } from 'node:path';
|
|
9
|
+
import { randomBytes } from 'node:crypto';
|
|
9
10
|
|
|
10
11
|
/** Hostname/IP spelling both the mint cache and the proxy wall accept. Single definition (see proxy.js). */
|
|
11
12
|
export const HOST_RE = /^[A-Za-z0-9.-]+$/;
|
|
@@ -22,6 +23,25 @@ function sh(file, args) {
|
|
|
22
23
|
// In-flight mints, so concurrent CONNECTs to a new host mint once.
|
|
23
24
|
const inflight = new Map();
|
|
24
25
|
|
|
26
|
+
// At most this many mints run at once: each is several `openssl` processes.
|
|
27
|
+
const MAX_MINTS = 4;
|
|
28
|
+
let minting = 0;
|
|
29
|
+
/** @type {Array<() => void>} */
|
|
30
|
+
const mintQueue = [];
|
|
31
|
+
|
|
32
|
+
/** @template T @param {() => Promise<T>} fn @returns {Promise<T>} fn's result, run once a mint slot is free */
|
|
33
|
+
async function withMintSlot(fn) {
|
|
34
|
+
if (minting >= MAX_MINTS) await new Promise((resolve) => mintQueue.push(() => resolve(undefined)));
|
|
35
|
+
else minting++;
|
|
36
|
+
try {
|
|
37
|
+
return await fn();
|
|
38
|
+
} finally {
|
|
39
|
+
// Hand the slot straight to the next waiter, else free it.
|
|
40
|
+
const next = mintQueue.shift();
|
|
41
|
+
if (next) next(); else minting--;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
25
45
|
/**
|
|
26
46
|
* Create the CA in `dir` unless it already exists. Safe to call twice:
|
|
27
47
|
* an existing `ca.pem` is reused, never regenerated.
|
|
@@ -74,7 +94,7 @@ export async function certFor(dir, host) {
|
|
|
74
94
|
}
|
|
75
95
|
let p = inflight.get(host);
|
|
76
96
|
if (!p) {
|
|
77
|
-
p = mint(dir, host, keyPath, certPath).finally(() => { inflight.delete(host); });
|
|
97
|
+
p = withMintSlot(() => mint(dir, host, keyPath, certPath)).finally(() => { inflight.delete(host); });
|
|
78
98
|
inflight.set(host, p);
|
|
79
99
|
}
|
|
80
100
|
return p;
|
|
@@ -100,7 +120,7 @@ async function mint(dir, host, keyPath, certPath) {
|
|
|
100
120
|
try {
|
|
101
121
|
await sh('openssl', ['req', '-new', '-key', keyPath, '-out', csr, '-subj', `/CN=${host}`]);
|
|
102
122
|
await sh('openssl', ['x509', '-req', '-in', csr, '-CA', caCert, '-CAkey', caKey,
|
|
103
|
-
'-
|
|
123
|
+
'-set_serial', '0x' + randomBytes(16).toString('hex'), '-days', '825', '-sha256', '-out', certPath, '-extfile', ext]);
|
|
104
124
|
} finally {
|
|
105
125
|
rmSync(csr, { force: true });
|
|
106
126
|
rmSync(ext, { force: true });
|
package/src/cli.js
CHANGED
|
@@ -30,7 +30,7 @@ import { parseArgs } from 'node:util';
|
|
|
30
30
|
import { writeFileAtomic } from './holds.js';
|
|
31
31
|
import { run as sandboxRun } from './run.js';
|
|
32
32
|
import { diffOverlay, commitOverlay, rollbackOverlay } from './overlay.js';
|
|
33
|
-
import { assertAgentName, createRuntime, runtimePaths, runtimeLive, safe } from './runtime.js';
|
|
33
|
+
import { assertAgentName, createRuntime, runtimePaths, runtimeLive, safe, shellQuote } from './runtime.js';
|
|
34
34
|
|
|
35
35
|
const USAGE = 'usage: sbx [--help] | pending | approve <id> | deny <id> [reason] | diff [--agent <name>] | commit [--agent <name>] [--skip-conflicts] | rollback [--agent <name>] | run [--mode ask|auto|trust] [--json] [--overlay] -- <cmd> [...]';
|
|
36
36
|
|
|
@@ -179,7 +179,7 @@ async function run(args) {
|
|
|
179
179
|
if (json) out(JSON.stringify({ ev: 'decided', id: c.id, decision: c.decision, reason: c.reason }));
|
|
180
180
|
else out(`decided ${c.id} ${c.decision}${c.reason ? ` (${c.reason})` : ''}`);
|
|
181
181
|
};
|
|
182
|
-
err(`runtime ${runtime} (answer with: SBX_RUNTIME=${runtime} sbx approve <id>)`);
|
|
182
|
+
err(`runtime ${runtime} (answer with: SBX_RUNTIME=${shellQuote(runtime)} sbx approve <id>)`);
|
|
183
183
|
/** @type {{ exit: number, diff: { path: string }[] } | null} */
|
|
184
184
|
let result = null;
|
|
185
185
|
try {
|
package/src/holds.js
CHANGED
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
// must write atomically (tmp file + rename); readers never see partials.
|
|
45
45
|
import fs from 'node:fs';
|
|
46
46
|
import path from 'node:path';
|
|
47
|
-
import { runtimePaths } from './runtime.js';
|
|
47
|
+
import { ensurePrivateDir, runtimePaths } from './runtime.js';
|
|
48
48
|
|
|
49
49
|
/** Body preview cap for `asks/<id>.json` (bytes). */
|
|
50
50
|
export const ASK_BODY_LIMIT = 4096;
|
|
@@ -52,6 +52,9 @@ export const ASK_BODY_LIMIT = 4096;
|
|
|
52
52
|
/** Default answer poll interval in ms (PRD Q9). */
|
|
53
53
|
export const DEFAULT_POLL_MS = 250;
|
|
54
54
|
|
|
55
|
+
/** At most this many held requests wait in line per agent; the next is refused. */
|
|
56
|
+
const MAX_WAITING_PER_AGENT = 16;
|
|
57
|
+
|
|
55
58
|
/**
|
|
56
59
|
* A parked request, as returned by {@link pending}. Plain objects only —
|
|
57
60
|
* the queue itself never leaves this module. No body: returning whole 1 MB
|
|
@@ -204,7 +207,9 @@ export function normalizeDecision(input, { approveAlias = false } = {}) {
|
|
|
204
207
|
* in `createProxy` (a second live proxy on the same runtime never starts):
|
|
205
208
|
* on the file channel the queue owns `asks/` and `answers/` for its
|
|
206
209
|
* runtime, clearing both at start and removing its asks on close, so no
|
|
207
|
-
* answer outlives its queue.
|
|
210
|
+
* answer outlives its queue. One parked request per agent: `reserve` hands
|
|
211
|
+
* out the agent's hold slot before a held body is read, and the slot passes
|
|
212
|
+
* to the next waiter when the parked entry leaves by any path.
|
|
208
213
|
*
|
|
209
214
|
* @param {object} opts
|
|
210
215
|
* @param {(o: Record<string, unknown>) => void} opts.log audit-log writer
|
|
@@ -218,7 +223,7 @@ export function normalizeDecision(input, { approveAlias = false } = {}) {
|
|
|
218
223
|
* @param {OnEvent|null} [opts.onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon
|
|
219
224
|
* @param {(entry: object) => void} opts.onApprove forward the parked request upstream
|
|
220
225
|
* @param {(entry: object, reason: string) => void} opts.onDeny refuse the parked request
|
|
221
|
-
* @returns {{ add: (entry: object) => string, decide: (req: { agent: string, method: string, url: string, headers: Record<string, string | string[] | undefined> }) => string | null, abandon: (id: string) => void, abandonSocket: (sock: object) => void, pending: () => HeldRequest[], close: () => void }} queue handle
|
|
226
|
+
* @returns {{ add: (entry: object) => string|null, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string) => void }) => { state: 'now'|'queued'|'full', arrivedAt: number, cancel: () => void }, decide: (req: { agent: string, method: string, url: string, headers: Record<string, string | string[] | undefined> }) => string | null, abandon: (id: string) => void, abandonSocket: (sock: object) => void, pending: () => HeldRequest[], close: () => void }} queue handle
|
|
222
227
|
*/
|
|
223
228
|
export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
224
229
|
maxBody = 1048576, runtime = null, onAsk = null, pollMs = DEFAULT_POLL_MS,
|
|
@@ -248,8 +253,8 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
248
253
|
}
|
|
249
254
|
const paths = runtime ? runtimePaths(runtime) : null;
|
|
250
255
|
if (paths) {
|
|
251
|
-
|
|
252
|
-
|
|
256
|
+
ensurePrivateDir(paths.asksDir);
|
|
257
|
+
ensurePrivateDir(paths.answersDir);
|
|
253
258
|
}
|
|
254
259
|
// A dead queue's leftovers must never decide the next queue's holds
|
|
255
260
|
// (ids restart at h1): clear both folders at start, logging one audit
|
|
@@ -278,6 +283,65 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
278
283
|
let n = 0;
|
|
279
284
|
/** @type {Map<string, object>} */
|
|
280
285
|
const queue = new Map();
|
|
286
|
+
/**
|
|
287
|
+
* One hold slot per agent: `holder` is the reservation holding it (or the
|
|
288
|
+
* parked entry's marker), `line` the FIFO of waiting reservation handles.
|
|
289
|
+
*
|
|
290
|
+
* @type {Map<string, { holder: object|null, line: Array<object> }>}
|
|
291
|
+
*/
|
|
292
|
+
const slots = new Map();
|
|
293
|
+
/** Internal reserve state by returned handle identity. @type {WeakMap<object, { agent: string, onReady: () => void, onExpire: (reason: string) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean }>} */
|
|
294
|
+
const handleState = new WeakMap();
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* The one expiry path for every reservation timer: mark it done, take it
|
|
298
|
+
* out of the line or hand its slot to the next waiter (whose own timer
|
|
299
|
+
* keeps running from its arrival), then expire it. Once.
|
|
300
|
+
*
|
|
301
|
+
* @param {string} agent agent name
|
|
302
|
+
* @param {object} handle the reservation's handle
|
|
303
|
+
* @param {string} reason expiry reason
|
|
304
|
+
* @returns {void}
|
|
305
|
+
*/
|
|
306
|
+
function expireReservation(agent, handle, reason) {
|
|
307
|
+
const st = handleState.get(handle);
|
|
308
|
+
if (!st || st.done) return;
|
|
309
|
+
st.done = true;
|
|
310
|
+
st.timer = null;
|
|
311
|
+
const s = slots.get(agent);
|
|
312
|
+
if (s) {
|
|
313
|
+
if (s.holder === handle) {
|
|
314
|
+
releaseSlot(agent);
|
|
315
|
+
} else {
|
|
316
|
+
const i = s.line.indexOf(handle);
|
|
317
|
+
if (i >= 0) s.line.splice(i, 1);
|
|
318
|
+
if (!s.holder && s.line.length === 0) slots.delete(agent);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
st.onExpire(reason);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Drop the current holder and hand the slot to the next waiter in line,
|
|
326
|
+
* or forget the agent when nobody waits. A promoted waiter keeps its own
|
|
327
|
+
* arrival timer: nothing here arms, clears or resets one.
|
|
328
|
+
*
|
|
329
|
+
* @param {string} agent agent name
|
|
330
|
+
* @returns {void}
|
|
331
|
+
*/
|
|
332
|
+
function releaseSlot(agent) {
|
|
333
|
+
const s = slots.get(agent);
|
|
334
|
+
if (!s) return;
|
|
335
|
+
s.holder = null;
|
|
336
|
+
const next = s.line.shift();
|
|
337
|
+
if (!next) {
|
|
338
|
+
slots.delete(agent);
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
s.holder = next;
|
|
342
|
+
const hst = handleState.get(next);
|
|
343
|
+
if (hst) hst.onReady();
|
|
344
|
+
}
|
|
281
345
|
|
|
282
346
|
const pub = (h) => ({
|
|
283
347
|
id: h.id, agent: h.agent, method: h.method, url: h.url, rule: h.note,
|
|
@@ -322,6 +386,7 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
322
386
|
if (!h) return `unknown ${id}`;
|
|
323
387
|
queue.delete(id);
|
|
324
388
|
if (h.timer) clearTimeout(h.timer);
|
|
389
|
+
if (h.slot) releaseSlot(h.agent);
|
|
325
390
|
removeAskFile(id);
|
|
326
391
|
const decision = approved ? 'allow' : 'deny';
|
|
327
392
|
if (approved) {
|
|
@@ -415,23 +480,103 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
415
480
|
if (pollTimer && typeof pollTimer.unref === 'function') pollTimer.unref();
|
|
416
481
|
|
|
417
482
|
const holds = {
|
|
418
|
-
|
|
483
|
+
/**
|
|
484
|
+
* Park a held request. With `slot` (from `reserve`) the parked entry
|
|
485
|
+
* takes over that slot, clearing the reservation's timer; with
|
|
486
|
+
* `arrivedAt` the deadline counts from arrival, not from now. A
|
|
487
|
+
* finished slot (expired, cancelled, closed, or no longer the holder)
|
|
488
|
+
* parks nothing and returns `null`. Without `slot`, parks exactly as
|
|
489
|
+
* before, without limit.
|
|
490
|
+
*
|
|
491
|
+
* @param {object} entry queue entry
|
|
492
|
+
* @returns {string|null} hold id, or null for a finished slot
|
|
493
|
+
*/
|
|
494
|
+
add({ agent, method, url, headers, body, sock, cres, note, slot, arrivedAt }) {
|
|
495
|
+
const hst = typeof slot === 'object' && slot !== null ? handleState.get(slot) : undefined;
|
|
496
|
+
const s = slots.get(agent);
|
|
497
|
+
if (slot && (!hst || hst.done || !s || s.holder !== slot)) return null;
|
|
419
498
|
const id = `h${++n}`;
|
|
420
499
|
const ms = deadlineMs();
|
|
500
|
+
const t0 = typeof arrivedAt === 'number' ? arrivedAt : Date.now();
|
|
421
501
|
const entry = {
|
|
422
|
-
id, agent, method, url, headers, body, sock, cres, note, t0
|
|
502
|
+
id, agent, method, url, headers, body, sock, cres, note, t0,
|
|
503
|
+
slot: null,
|
|
423
504
|
timer: ms === null ? null
|
|
424
|
-
: setTimeout(() => settle(id, false, 'hold timeout'), ms),
|
|
505
|
+
: setTimeout(() => settle(id, false, 'hold timeout'), Math.max(0, ms - (Date.now() - t0))),
|
|
425
506
|
};
|
|
426
507
|
// Unref: a parked `never` hold must not keep the process alive by itself.
|
|
427
508
|
if (entry.timer?.unref) entry.timer.unref();
|
|
509
|
+
if (slot && hst && s && s.holder === slot) {
|
|
510
|
+
if (hst.timer) clearTimeout(hst.timer);
|
|
511
|
+
hst.timer = null;
|
|
512
|
+
hst.consumed = true;
|
|
513
|
+
s.holder = { parked: id };
|
|
514
|
+
entry.slot = slot;
|
|
515
|
+
}
|
|
428
516
|
queue.set(id, entry);
|
|
429
517
|
log({ ev: 'hold', id, agent, method, url, reason: note ?? undefined,
|
|
430
|
-
timeoutMs: ms, waiting: queue.size });
|
|
518
|
+
timeoutMs: ms, waiting: queue.size, queued: s ? s.line.length : 0 });
|
|
431
519
|
void park(entry, ms, note ?? '');
|
|
432
520
|
return id;
|
|
433
521
|
},
|
|
434
522
|
|
|
523
|
+
/**
|
|
524
|
+
* Ask for this agent's hold slot before reading a held request's body.
|
|
525
|
+
* @param {string} agent
|
|
526
|
+
* @param {{ onReady: () => void, onExpire: (reason: string) => void }} cbs
|
|
527
|
+
* @returns {{ state: 'now'|'queued'|'full', arrivedAt: number, cancel: () => void }}
|
|
528
|
+
*/
|
|
529
|
+
reserve(agent, { onReady, onExpire }) {
|
|
530
|
+
const arrivedAt = Date.now();
|
|
531
|
+
// Internal slot state, keyed by the returned handle's identity: `add`
|
|
532
|
+
// receives that same object as `slot`, so holder comparisons use it.
|
|
533
|
+
// The one deadline timer lives here, armed below for 'now' and
|
|
534
|
+
// 'queued' alike; expiry runs through `expireReservation` only.
|
|
535
|
+
/** @type {{ agent: string, onReady: () => void, onExpire: (reason: string) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean }} */
|
|
536
|
+
const st = { agent, onReady, onExpire, timer: null, consumed: false, done: false };
|
|
537
|
+
const s0 = slots.get(agent);
|
|
538
|
+
/** @type {'now'|'queued'|'full'} */
|
|
539
|
+
const state = !s0 ? 'now' : (s0.line.length >= MAX_WAITING_PER_AGENT ? 'full' : 'queued');
|
|
540
|
+
const handle = {
|
|
541
|
+
state,
|
|
542
|
+
arrivedAt,
|
|
543
|
+
cancel() {
|
|
544
|
+
if (st.done) return;
|
|
545
|
+
st.done = true;
|
|
546
|
+
if (st.timer) clearTimeout(st.timer);
|
|
547
|
+
st.timer = null;
|
|
548
|
+
if (st.consumed) return;
|
|
549
|
+
const s = slots.get(agent);
|
|
550
|
+
if (!s) return;
|
|
551
|
+
if (s.holder === handle) {
|
|
552
|
+
releaseSlot(agent);
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
const i = s.line.indexOf(handle);
|
|
556
|
+
if (i >= 0) {
|
|
557
|
+
s.line.splice(i, 1);
|
|
558
|
+
if (!s.holder && s.line.length === 0) slots.delete(agent);
|
|
559
|
+
}
|
|
560
|
+
},
|
|
561
|
+
};
|
|
562
|
+
handleState.set(handle, st);
|
|
563
|
+
if (state === 'now') {
|
|
564
|
+
slots.set(agent, { holder: handle, line: [] });
|
|
565
|
+
} else if (state === 'full') {
|
|
566
|
+
log({ ev: 'hold-queue-full', agent });
|
|
567
|
+
return handle;
|
|
568
|
+
} else {
|
|
569
|
+
if (!s0) throw new Error(`reserve: no slot record for ${agent}`);
|
|
570
|
+
s0.line.push(handle);
|
|
571
|
+
}
|
|
572
|
+
const ms = deadlineMs();
|
|
573
|
+
if (ms !== null) {
|
|
574
|
+
st.timer = setTimeout(() => expireReservation(agent, handle, 'hold timeout'), ms);
|
|
575
|
+
if (st.timer.unref) st.timer.unref();
|
|
576
|
+
}
|
|
577
|
+
return handle;
|
|
578
|
+
},
|
|
579
|
+
|
|
435
580
|
// The client went away: drop its holds so no later answer can forward
|
|
436
581
|
// a request nobody is listening for.
|
|
437
582
|
abandon(id) {
|
|
@@ -439,6 +584,7 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
439
584
|
if (!h) return;
|
|
440
585
|
queue.delete(id);
|
|
441
586
|
if (h.timer) clearTimeout(h.timer);
|
|
587
|
+
if (h.slot) releaseSlot(h.agent);
|
|
442
588
|
removeAskFile(id);
|
|
443
589
|
log({ ev: 'hold-abandoned', id, agent: h.agent, method: h.method, url: h.url });
|
|
444
590
|
onDeny(h, 'client gone');
|
|
@@ -457,6 +603,19 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
457
603
|
|
|
458
604
|
close() {
|
|
459
605
|
if (pollTimer) clearInterval(pollTimer);
|
|
606
|
+
for (const s of [...slots.values()]) {
|
|
607
|
+
const handles = [...s.line];
|
|
608
|
+
if (s.holder && !('parked' in s.holder)) handles.push(s.holder);
|
|
609
|
+
for (const handle of handles) {
|
|
610
|
+
const hst = handleState.get(handle);
|
|
611
|
+
if (!hst) continue;
|
|
612
|
+
if (hst.timer) clearTimeout(hst.timer);
|
|
613
|
+
hst.timer = null;
|
|
614
|
+
hst.done = true;
|
|
615
|
+
hst.onExpire('proxy closing');
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
slots.clear();
|
|
460
619
|
// settle() removes each ask file: `sbx pending` never lists a dead queue's holds.
|
|
461
620
|
for (const [id] of [...queue]) settle(id, false, 'proxy closing');
|
|
462
621
|
},
|
package/src/overlay.js
CHANGED
|
@@ -14,7 +14,7 @@ import { createHash, randomBytes } from 'node:crypto';
|
|
|
14
14
|
import {
|
|
15
15
|
existsSync, mkdirSync, readdirSync, lstatSync, statSync, accessSync, constants,
|
|
16
16
|
readFileSync, writeFileSync, rmSync, rmdirSync, chmodSync,
|
|
17
|
-
readlinkSync, renameSync, realpathSync,
|
|
17
|
+
readlinkSync, renameSync, realpathSync, openSync, readSync, closeSync,
|
|
18
18
|
} from 'node:fs';
|
|
19
19
|
import { join, dirname } from 'node:path';
|
|
20
20
|
import { fileURLToPath } from 'node:url';
|
|
@@ -109,6 +109,58 @@ function fpOf(e) {
|
|
|
109
109
|
return `${e.type}:${e.hash ?? e.target ?? ''}:${e.mode.toString(8)}`;
|
|
110
110
|
}
|
|
111
111
|
|
|
112
|
+
/**
|
|
113
|
+
* Wrap a filesystem error from hashing: keep the message naming the path,
|
|
114
|
+
* and carry the original over (`cause`, plus its `code` when it has one)
|
|
115
|
+
* so callers like `isPermErr` still see it.
|
|
116
|
+
*
|
|
117
|
+
* @param {string} abs absolute path being hashed
|
|
118
|
+
* @param {unknown} e the original error
|
|
119
|
+
* @returns {never} always throws
|
|
120
|
+
*/
|
|
121
|
+
function hashError(abs, e) {
|
|
122
|
+
const err = new Error(
|
|
123
|
+
`hash failed for ${abs}: ${e instanceof Error ? e.message : String(e)}`,
|
|
124
|
+
{ cause: e });
|
|
125
|
+
if (typeof /** @type {{ code?: unknown }} */ (e)?.code === 'string') {
|
|
126
|
+
/** @type {{ code?: string }} */ (err).code = /** @type {{ code: string }} */ (e).code;
|
|
127
|
+
}
|
|
128
|
+
throw err;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Hash a file in 1 MiB chunks, never whole: a multi-GiB file must not
|
|
133
|
+
* exhaust memory at setup. Errors name the path.
|
|
134
|
+
*
|
|
135
|
+
* @param {string} abs absolute path to hash
|
|
136
|
+
* @returns {string} sha256 hex
|
|
137
|
+
*/
|
|
138
|
+
export function hashFile(abs) {
|
|
139
|
+
const hash = createHash('sha256');
|
|
140
|
+
let fd;
|
|
141
|
+
try {
|
|
142
|
+
fd = openSync(abs, 'r');
|
|
143
|
+
} catch (e) {
|
|
144
|
+
throw hashError(abs, e);
|
|
145
|
+
}
|
|
146
|
+
const buf = Buffer.alloc(1024 * 1024);
|
|
147
|
+
try {
|
|
148
|
+
for (;;) {
|
|
149
|
+
let n;
|
|
150
|
+
try {
|
|
151
|
+
n = readSync(fd, buf, 0, buf.length, null);
|
|
152
|
+
} catch (e) {
|
|
153
|
+
throw hashError(abs, e);
|
|
154
|
+
}
|
|
155
|
+
if (n === 0) break;
|
|
156
|
+
hash.update(buf.subarray(0, n));
|
|
157
|
+
}
|
|
158
|
+
} finally {
|
|
159
|
+
try { closeSync(fd); } catch {}
|
|
160
|
+
}
|
|
161
|
+
return hash.digest('hex');
|
|
162
|
+
}
|
|
163
|
+
|
|
112
164
|
/**
|
|
113
165
|
* Build one manifest entry: the single definition of the fingerprint
|
|
114
166
|
* (type + content + mode), shared by the walker and by live re-checks.
|
|
@@ -124,7 +176,7 @@ function entryOf(abs, st, full = true) {
|
|
|
124
176
|
return full
|
|
125
177
|
? {
|
|
126
178
|
type, mode: st.mode & 0o7777,
|
|
127
|
-
hash:
|
|
179
|
+
hash: hashFile(abs),
|
|
128
180
|
}
|
|
129
181
|
: { type, mode: st.mode & 0o7777 };
|
|
130
182
|
}
|
package/src/proxy.js
CHANGED
|
@@ -16,7 +16,7 @@ import fs from 'node:fs';
|
|
|
16
16
|
import path from 'node:path';
|
|
17
17
|
import { ensureCA, certFor, HOST_RE } from './certs.js';
|
|
18
18
|
import { createHolds } from './holds.js';
|
|
19
|
-
import { claimRuntime, runtimePaths } from './runtime.js';
|
|
19
|
+
import { claimRuntime, ensurePrivateDir, runtimePaths } from './runtime.js';
|
|
20
20
|
import { checkUpstream } from './wall.js';
|
|
21
21
|
|
|
22
22
|
const AGENT = Symbol('agent');
|
|
@@ -119,7 +119,7 @@ function scrubSecrets(entry) {
|
|
|
119
119
|
* @param {ProxyOptions} opts
|
|
120
120
|
* @returns live proxy: `ready` resolves when listeners + CA are up; the shape is inferred, see `Proxy`
|
|
121
121
|
* @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.
|
|
122
|
-
* @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.
|
|
122
|
+
* @fails Throws synchronously on a missing or unopenable `logFile` or `runtime`. Throws when another live proxy owns the runtime; the claim dies with its process; nothing is ever taken over. At runtime, dead upstreams, malformed input, over-cap and timed-out holds all become loud logged HTTP errors, never silence and never a crash. A second proxy on the same port rejects `ready`, never crashes the process.
|
|
123
123
|
* @example
|
|
124
124
|
* import { createProxy } from "barebox";
|
|
125
125
|
* const proxy = createProxy({ port: 0, runtime: "./sbx-runtime", logFile: "./mitm.log" });
|
|
@@ -145,12 +145,34 @@ export function createProxy(opts) {
|
|
|
145
145
|
const certDir = runtimePaths(runtime).certsDir;
|
|
146
146
|
const holdMaxBody = hold?.maxBody ?? 1048576;
|
|
147
147
|
|
|
148
|
-
|
|
149
|
-
//
|
|
150
|
-
//
|
|
151
|
-
|
|
148
|
+
// Open the audit log synchronously: a bad `logFile` (a directory, a
|
|
149
|
+
// missing parent, no permission) throws here, where the claim can still
|
|
150
|
+
// be released — not later as an uncaught stream error.
|
|
151
|
+
let logFd;
|
|
152
|
+
try {
|
|
153
|
+
logFd = fs.openSync(logFile, 'a', 0o600);
|
|
154
|
+
} catch (e) {
|
|
155
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
156
|
+
releaseClaim();
|
|
157
|
+
throw new Error(`createProxy: cannot open logFile ${logFile}: ${msg}`);
|
|
158
|
+
}
|
|
159
|
+
const logStream = fs.createWriteStream(logFile, { fd: logFd });
|
|
160
|
+
// `openSync`'s mode is masked by the umask and doesn't apply to an
|
|
161
|
+
// existing file: a 0644 log from an older run would stay world-readable
|
|
162
|
+
// while new lines append, so fix it up on every start.
|
|
152
163
|
try { fs.chmodSync(logFile, 0o600); } catch {}
|
|
153
|
-
|
|
164
|
+
let logFailed = false;
|
|
165
|
+
logStream.on('error', (e) => {
|
|
166
|
+
if (logFailed) return;
|
|
167
|
+
logFailed = true;
|
|
168
|
+
console.error(`sbx: audit log ${logFile} write failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
169
|
+
});
|
|
170
|
+
// After close() ends the stream a late line (a socket torn down by close)
|
|
171
|
+
// is dropped on purpose: a write after end() would destroy the stream.
|
|
172
|
+
const log = (o) => {
|
|
173
|
+
if (logStream.writableEnded) return;
|
|
174
|
+
logStream.write(JSON.stringify(redact(scrubSecrets(o))) + '\n');
|
|
175
|
+
};
|
|
154
176
|
let trust = null;
|
|
155
177
|
if (upstreamCa) {
|
|
156
178
|
let extra;
|
|
@@ -390,20 +412,43 @@ export function createProxy(opts) {
|
|
|
390
412
|
headers: { ...creq.headers }, stream: creq, cres });
|
|
391
413
|
return;
|
|
392
414
|
}
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
415
|
+
// One held request per agent reads its body at a time; the rest wait
|
|
416
|
+
// unread in line. No body listener (it would resume the stream) until
|
|
417
|
+
// `onReady`. A request that never parks frees its slot when `cres` closes.
|
|
418
|
+
creq.pause();
|
|
419
|
+
const readHeld = () => {
|
|
420
|
+
creq.on('data', (c) => {
|
|
421
|
+
size += c.length;
|
|
422
|
+
if (size > holdMaxBody) { over = true; return; }
|
|
423
|
+
chunks.push(c);
|
|
424
|
+
});
|
|
425
|
+
creq.on('error', () => { denyRes(cres, 502, 'client body failed'); });
|
|
426
|
+
creq.on('end', () => {
|
|
427
|
+
if (over) { denyRes(cres, 403, 'body too large to hold'); return; }
|
|
428
|
+
const body = finishLog();
|
|
429
|
+
// Parked: the tunnel stays open until the ask channel decides. The
|
|
430
|
+
// hold reason travels as `note` so the ask file carries its `rule`.
|
|
431
|
+
// null: the reservation already expired and onExpire answered 403.
|
|
432
|
+
queue.add({ agent, method, url: urlStr,
|
|
433
|
+
headers: { ...creq.headers }, body, sock, cres, note: reason,
|
|
434
|
+
slot, arrivedAt: slot.arrivedAt });
|
|
435
|
+
});
|
|
436
|
+
creq.resume();
|
|
437
|
+
};
|
|
438
|
+
const slot = queue.reserve(agent, {
|
|
439
|
+
onReady: readHeld,
|
|
440
|
+
onExpire: (why) => { denyRes(cres, 403, `denied: ${why}`); creq.resume(); },
|
|
406
441
|
});
|
|
442
|
+
if (slot.state === 'full') {
|
|
443
|
+
denyRes(cres, 429, 'hold queue full');
|
|
444
|
+
creq.resume();
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
// The client may have died during the wall's DNS await, before this
|
|
448
|
+
// listener existed: its 'close' is already past, so release here.
|
|
449
|
+
if (sock.destroyed) { slot.cancel(); return; }
|
|
450
|
+
cres.on('close', () => slot.cancel());
|
|
451
|
+
if (slot.state === 'now') readHeld();
|
|
407
452
|
}
|
|
408
453
|
// Idle tunnels die here; a request in flight is never idle by definition.
|
|
409
454
|
server.keepAliveTimeout = clientIdleMs;
|
|
@@ -517,7 +562,7 @@ export function createProxy(opts) {
|
|
|
517
562
|
const sockPath = runtimePaths(runtime).socket(name);
|
|
518
563
|
if (agentServers.has(name)) return sockPath;
|
|
519
564
|
try { fs.unlinkSync(sockPath); } catch {}
|
|
520
|
-
|
|
565
|
+
ensurePrivateDir(path.dirname(sockPath));
|
|
521
566
|
const srv = net.createServer((sock) => {
|
|
522
567
|
if (closed) { sock.destroy(); return; }
|
|
523
568
|
admit(sock, name);
|
|
@@ -530,11 +575,19 @@ export function createProxy(opts) {
|
|
|
530
575
|
return sockPath;
|
|
531
576
|
}
|
|
532
577
|
|
|
578
|
+
// Ends the agent's door AND its open connections: its parked holds end
|
|
579
|
+
// synchronously as deny / client gone (no waiting on the socket's async
|
|
580
|
+
// 'close'), then each socket is destroyed.
|
|
533
581
|
function removeAgent(name) {
|
|
534
582
|
const srv = agentServers.get(name);
|
|
535
583
|
if (!srv) return;
|
|
536
584
|
agentServers.delete(name);
|
|
537
585
|
srv.close();
|
|
586
|
+
for (const s of [...clients]) {
|
|
587
|
+
if (s[AGENT] !== name) continue;
|
|
588
|
+
holds?.abandonSocket(s);
|
|
589
|
+
s.destroy();
|
|
590
|
+
}
|
|
538
591
|
try { fs.unlinkSync(runtimePaths(runtime).socket(name)); } catch {}
|
|
539
592
|
}
|
|
540
593
|
|
|
@@ -554,8 +607,12 @@ export function createProxy(opts) {
|
|
|
554
607
|
logStream.end();
|
|
555
608
|
/** @type {Promise<void>} */
|
|
556
609
|
const flushed = new Promise((resolve) => {
|
|
557
|
-
if (logStream.writableFinished) resolve();
|
|
558
|
-
else
|
|
610
|
+
if (logStream.writableFinished || logStream.destroyed) resolve();
|
|
611
|
+
else {
|
|
612
|
+
// A destroyed stream emits 'close', never 'finish'.
|
|
613
|
+
logStream.once('finish', () => resolve());
|
|
614
|
+
logStream.once('close', () => resolve());
|
|
615
|
+
}
|
|
559
616
|
});
|
|
560
617
|
await flushed;
|
|
561
618
|
releaseClaim();
|
package/src/run.js
CHANGED
|
@@ -186,13 +186,16 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
|
186
186
|
await proxy.close().catch(() => {});
|
|
187
187
|
throw e;
|
|
188
188
|
}
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
//
|
|
192
|
-
//
|
|
189
|
+
/** @type {string|undefined} */
|
|
190
|
+
let sock;
|
|
191
|
+
// `addAgent` and `launch` run INSIDE the try: a synchronous throw there
|
|
192
|
+
// (a broken socket folder, uncommitted overlay changes, a runtime inside
|
|
193
|
+
// the project) must still close the proxy — otherwise its listening
|
|
194
|
+
// sockets keep this process alive forever.
|
|
193
195
|
/** @type {number} */
|
|
194
196
|
let exit;
|
|
195
197
|
try {
|
|
198
|
+
sock = proxy.addAgent(agent);
|
|
196
199
|
const child = launch({
|
|
197
200
|
runtime: rt, agent, proj, command,
|
|
198
201
|
socket: sock, caFile: proxy.caFile,
|
|
@@ -207,6 +210,9 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
|
207
210
|
child.on('close', (code) => resolve(code ?? 1));
|
|
208
211
|
});
|
|
209
212
|
} finally {
|
|
213
|
+
// The sandbox is gone: end the agent's holds as client gone now, not
|
|
214
|
+
// as 'proxy closing' if close() beats the sockets' async 'close'.
|
|
215
|
+
if (sock) proxy.removeAgent(agent);
|
|
210
216
|
await proxy.close();
|
|
211
217
|
}
|
|
212
218
|
// M2.5 item 4: the result carries the M4 diff. Without overlay there is no
|
package/src/runtime.js
CHANGED
|
@@ -90,6 +90,26 @@ export function runtimeTempDir(scratch, prefix) {
|
|
|
90
90
|
return fs.mkdtempSync(path.join(scratch, `${prefix}-`));
|
|
91
91
|
}
|
|
92
92
|
|
|
93
|
+
/**
|
|
94
|
+
* Make a runtime dir owner-only whatever the umask: `mode` is masked by
|
|
95
|
+
* the umask and doesn't apply to an existing dir, hence the `chmod`. An
|
|
96
|
+
* existing dir you own is tightened to 0700; one you don't own (`/tmp`,
|
|
97
|
+
* root-owned, shared) is refused, since it can't be made private.
|
|
98
|
+
*
|
|
99
|
+
* @param {string} dir dir to create or fix up
|
|
100
|
+
* @returns {void}
|
|
101
|
+
* @throws {Error} when the dir exists and is owned by another uid
|
|
102
|
+
*/
|
|
103
|
+
export function ensurePrivateDir(dir) {
|
|
104
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
105
|
+
const owner = fs.statSync(dir).uid;
|
|
106
|
+
const me = /** @type {number} */ (process.getuid?.());
|
|
107
|
+
if (owner !== me) {
|
|
108
|
+
throw new Error(`runtime dir ${dir} is owned by uid ${owner}, not you (uid ${me}): use a dir of your own, e.g. ${path.join(dir, 'sbx')}`);
|
|
109
|
+
}
|
|
110
|
+
fs.chmodSync(dir, 0o700);
|
|
111
|
+
}
|
|
112
|
+
|
|
93
113
|
/** @param {string} owner owner file path @returns {unknown} the pid it names, or 'unknown' when missing, empty or garbage */
|
|
94
114
|
function pidOf(owner) {
|
|
95
115
|
try {
|
|
@@ -170,7 +190,7 @@ export function runtimeLive(runtime) {
|
|
|
170
190
|
* @returns {() => void} `release()`: unlinks the owner file only when it holds our pid, then closes the lock; idempotent per claim
|
|
171
191
|
*/
|
|
172
192
|
export function claimRuntime(runtime) {
|
|
173
|
-
|
|
193
|
+
ensurePrivateDir(runtime);
|
|
174
194
|
const real = fs.realpathSync(runtime);
|
|
175
195
|
const owner = runtimePaths(real).owner;
|
|
176
196
|
const name = lockName(runtime);
|
|
@@ -220,6 +240,18 @@ export function safe(s) {
|
|
|
220
240
|
.replace(/[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '');
|
|
221
241
|
}
|
|
222
242
|
|
|
243
|
+
/**
|
|
244
|
+
* Quote a path for pasting into a shell: safe spellings come back
|
|
245
|
+
* unchanged, anything else is single-quoted with `'` escaped.
|
|
246
|
+
*
|
|
247
|
+
* @param {string} s path to quote
|
|
248
|
+
* @returns {string} shell-safe spelling
|
|
249
|
+
*/
|
|
250
|
+
export function shellQuote(s) {
|
|
251
|
+
if (/^[A-Za-z0-9_\/.,:@%+=-]+$/.test(s)) return s;
|
|
252
|
+
return `'` + s.replace(/'/g, `'\\''`) + `'`;
|
|
253
|
+
}
|
|
254
|
+
|
|
223
255
|
/**
|
|
224
256
|
* Every path in a runtime dir. The one place that names them.
|
|
225
257
|
*
|
package/src/wall.js
CHANGED
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
//
|
|
4
4
|
// Default-deny for loopback, link-local (incl. cloud metadata 169.254/16),
|
|
5
5
|
// the host's own addresses, and private LAN ranges (RFC 1918, CGNAT
|
|
6
|
-
// 100.64/10, IPv6 ULA fc00::/7).
|
|
6
|
+
// 100.64/10, IPv6 ULA fc00::/7). An IPv4 embedded in IPv6 is checked too, in
|
|
7
|
+
// every spelling: mapped, compat, uncompressed, NAT64 (RFC 6052, RFC 8215)
|
|
8
|
+
// and 6to4 (RFC 3056). The check runs AFTER DNS resolution, so a
|
|
7
9
|
// hostname that resolves to 127.0.0.1 is denied exactly like the literal.
|
|
8
10
|
// Unresolvable names are denied too (fail closed, never 502-then-dial).
|
|
9
11
|
// Only the TEST-ONLY `unsafeTestOnly.allowLoopback` (loopback + unspecified)
|
|
@@ -22,17 +24,76 @@ function normIp(ip) {
|
|
|
22
24
|
return s;
|
|
23
25
|
}
|
|
24
26
|
|
|
25
|
-
/** Embedded IPv4 in `::ffff:1.2.3.4`, or null. */
|
|
26
|
-
function mappedV4(ip) {
|
|
27
|
-
const m = ip.match(/^(?:.*:)?(\d+\.\d+\.\d+\.\d+)$/);
|
|
28
|
-
return m && net.isIP(m[1]) === 4 ? m[1] : null;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
27
|
function v4Parts(ip) {
|
|
32
28
|
return ip.split('.').map((p) => parseInt(p, 10));
|
|
33
29
|
}
|
|
34
30
|
|
|
35
|
-
/**
|
|
31
|
+
/**
|
|
32
|
+
* Parse IPv6 into its 8 groups, handling `::` anywhere and a trailing
|
|
33
|
+
* dotted quad (`::ffff:1.2.3.4`, `64:ff9b::1.2.3.4`).
|
|
34
|
+
*
|
|
35
|
+
* @param {string} ip normalized IP spelling
|
|
36
|
+
* @returns {number[]|null} 8 groups (0–0xffff), or null when not IPv6
|
|
37
|
+
*/
|
|
38
|
+
function v6Groups(ip) {
|
|
39
|
+
if (net.isIP(ip) !== 6) return null;
|
|
40
|
+
const dbl = ip.indexOf('::');
|
|
41
|
+
if (dbl >= 0 && ip.indexOf('::', dbl + 2) >= 0) return null;
|
|
42
|
+
const parts = (s) => s.split(':').filter((p) => p !== '');
|
|
43
|
+
const head = dbl >= 0 ? parts(ip.slice(0, dbl)) : ip.split(':');
|
|
44
|
+
const tail = dbl >= 0 ? parts(ip.slice(dbl + 2)) : [];
|
|
45
|
+
const val = (s) => {
|
|
46
|
+
if (s.includes('.')) {
|
|
47
|
+
if (net.isIP(s) !== 4) return null;
|
|
48
|
+
const p = s.split('.').map((x) => parseInt(x, 10));
|
|
49
|
+
return [(p[0] << 8) | p[1], (p[2] << 8) | p[3]];
|
|
50
|
+
}
|
|
51
|
+
if (!/^[0-9a-f]{1,4}$/.test(s)) return null;
|
|
52
|
+
return [parseInt(s, 16)];
|
|
53
|
+
};
|
|
54
|
+
/** @type {number[]} */
|
|
55
|
+
const hGroups = [];
|
|
56
|
+
/** @type {number[]} */
|
|
57
|
+
const tGroups = [];
|
|
58
|
+
for (const [list, out] of [[head, hGroups], [tail, tGroups]]) {
|
|
59
|
+
for (const s of list) {
|
|
60
|
+
const v = val(s);
|
|
61
|
+
if (!v) return null;
|
|
62
|
+
out.push(...v);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (dbl < 0) return hGroups.length === 8 ? hGroups : null;
|
|
66
|
+
if (hGroups.length + tGroups.length > 8) return null;
|
|
67
|
+
return [...hGroups, ...new Array(8 - hGroups.length - tGroups.length).fill(0), ...tGroups];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Dotted IPv4 from two groups. @param {number[]} g groups @param {number} i first group @returns {string} */
|
|
71
|
+
function v4Of(g, i) {
|
|
72
|
+
return `${(g[i] >> 8) & 255}.${g[i] & 255}.${(g[i + 1] >> 8) & 255}.${g[i + 1] & 255}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Why a dotted IPv4 is denied, or null when it may go through. The one IPv4
|
|
77
|
+
* rule set: plain IPv4 and every embedded IPv4 use this function.
|
|
78
|
+
*
|
|
79
|
+
* @param {string} v4 dotted IPv4
|
|
80
|
+
* @param {boolean} allowLoopback test-only opt-in for loopback + unspecified
|
|
81
|
+
* @returns {string|null} `loopback` / `unspecified` / `link-local` / `host-local` / `private`, or null
|
|
82
|
+
*/
|
|
83
|
+
function v4Reason(v4, allowLoopback) {
|
|
84
|
+
const [a, b] = v4Parts(v4);
|
|
85
|
+
if (a === 127) return allowLoopback ? null : 'loopback';
|
|
86
|
+
if (a === 0) return allowLoopback ? null : 'unspecified';
|
|
87
|
+
if (a === 169 && b === 254) return 'link-local';
|
|
88
|
+
if (a === 10) return 'private';
|
|
89
|
+
if (a === 172 && b >= 16 && b <= 31) return 'private';
|
|
90
|
+
if (a === 192 && b === 168) return 'private';
|
|
91
|
+
if (a === 100 && b >= 64 && b <= 127) return 'private';
|
|
92
|
+
if (localIps().has(v4)) return 'host-local';
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** This machine's own interface addresses: IPv6 keyed by parsed groups, IPv4 dotted (see `normIp`). */
|
|
36
97
|
function localIps() {
|
|
37
98
|
const out = new Set();
|
|
38
99
|
let ifs = {};
|
|
@@ -45,7 +106,10 @@ function localIps() {
|
|
|
45
106
|
}
|
|
46
107
|
for (const addrs of Object.values(ifs)) {
|
|
47
108
|
for (const a of addrs ?? []) {
|
|
48
|
-
if (a
|
|
109
|
+
if (!a || !a.address) continue;
|
|
110
|
+
const norm = normIp(a.address);
|
|
111
|
+
const g = v6Groups(norm);
|
|
112
|
+
out.add(g ? g.join(':') : norm);
|
|
49
113
|
}
|
|
50
114
|
}
|
|
51
115
|
return out;
|
|
@@ -60,28 +124,25 @@ function localIps() {
|
|
|
60
124
|
*/
|
|
61
125
|
export function denyReasonForIp(rawIp, allowLoopback) {
|
|
62
126
|
const ip = normIp(rawIp);
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
if (
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
if (localIps().has(ip)) return 'host-local';
|
|
83
|
-
return null;
|
|
84
|
-
}
|
|
127
|
+
if (net.isIP(ip) === 4) return v4Reason(ip, allowLoopback);
|
|
128
|
+
const g = v6Groups(ip);
|
|
129
|
+
if (!g) return null;
|
|
130
|
+
const zero = (a, b) => g.slice(a, b).every((x) => x === 0);
|
|
131
|
+
if (zero(0, 8)) return allowLoopback ? null : 'unspecified';
|
|
132
|
+
if (zero(0, 7) && g[7] === 1) return allowLoopback ? null : 'loopback';
|
|
133
|
+
// IPv4-mapped ::ffff:0:0/96, then compat ::/96: the embedded IPv4 decides.
|
|
134
|
+
if (zero(0, 5) && g[5] === 0xffff) return v4Reason(v4Of(g, 6), allowLoopback);
|
|
135
|
+
if (zero(0, 6)) return v4Reason(v4Of(g, 6), allowLoopback);
|
|
136
|
+
// NAT64 64:ff9b::/96: the embedded IPv4 decides. Local-use 64:ff9b:1::/48
|
|
137
|
+
// is private outright: the IPv4 position depends on the prefix length,
|
|
138
|
+
// which the wall can't know.
|
|
139
|
+
if (g[0] === 0x64 && g[1] === 0xff9b && zero(2, 6)) return v4Reason(v4Of(g, 6), allowLoopback);
|
|
140
|
+
if (g[0] === 0x64 && g[1] === 0xff9b && g[2] === 1) return 'private';
|
|
141
|
+
// 6to4 2002::/16: the next 32 bits are the IPv4.
|
|
142
|
+
if (g[0] === 0x2002) return v4Reason(v4Of(g, 1), allowLoopback);
|
|
143
|
+
if ((g[0] & 0xffc0) === 0xfe80) return 'link-local';
|
|
144
|
+
if ((g[0] & 0xfe00) === 0xfc00) return 'private';
|
|
145
|
+
if (localIps().has(g.join(':'))) return 'host-local';
|
|
85
146
|
return null;
|
|
86
147
|
}
|
|
87
148
|
|
package/types/holds.d.ts
CHANGED
|
@@ -82,7 +82,9 @@ export function normalizeDecision(input: {
|
|
|
82
82
|
* in `createProxy` (a second live proxy on the same runtime never starts):
|
|
83
83
|
* on the file channel the queue owns `asks/` and `answers/` for its
|
|
84
84
|
* runtime, clearing both at start and removing its asks on close, so no
|
|
85
|
-
* answer outlives its queue.
|
|
85
|
+
* answer outlives its queue. One parked request per agent: `reserve` hands
|
|
86
|
+
* out the agent's hold slot before a held body is read, and the slot passes
|
|
87
|
+
* to the next waiter when the parked entry leaves by any path.
|
|
86
88
|
*
|
|
87
89
|
* @param {object} opts
|
|
88
90
|
* @param {(o: Record<string, unknown>) => void} opts.log audit-log writer
|
|
@@ -96,7 +98,7 @@ export function normalizeDecision(input: {
|
|
|
96
98
|
* @param {OnEvent|null} [opts.onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon
|
|
97
99
|
* @param {(entry: object) => void} opts.onApprove forward the parked request upstream
|
|
98
100
|
* @param {(entry: object, reason: string) => void} opts.onDeny refuse the parked request
|
|
99
|
-
* @returns {{ add: (entry: object) => string, decide: (req: { agent: string, method: string, url: string, headers: Record<string, string | string[] | undefined> }) => string | null, abandon: (id: string) => void, abandonSocket: (sock: object) => void, pending: () => HeldRequest[], close: () => void }} queue handle
|
|
101
|
+
* @returns {{ add: (entry: object) => string|null, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string) => void }) => { state: 'now'|'queued'|'full', arrivedAt: number, cancel: () => void }, decide: (req: { agent: string, method: string, url: string, headers: Record<string, string | string[] | undefined> }) => string | null, abandon: (id: string) => void, abandonSocket: (sock: object) => void, pending: () => HeldRequest[], close: () => void }} queue handle
|
|
100
102
|
*/
|
|
101
103
|
export function createHolds({ log, shouldHold, match, timeoutMs, maxBody, runtime, onAsk, pollMs, onEvent, onApprove, onDeny }: {
|
|
102
104
|
log: (o: Record<string, unknown>) => void;
|
|
@@ -111,7 +113,15 @@ export function createHolds({ log, shouldHold, match, timeoutMs, maxBody, runtim
|
|
|
111
113
|
onApprove: (entry: object) => void;
|
|
112
114
|
onDeny: (entry: object, reason: string) => void;
|
|
113
115
|
}): {
|
|
114
|
-
add: (entry: object) => string;
|
|
116
|
+
add: (entry: object) => string | null;
|
|
117
|
+
reserve: (agent: string, cbs: {
|
|
118
|
+
onReady: () => void;
|
|
119
|
+
onExpire: (reason: string) => void;
|
|
120
|
+
}) => {
|
|
121
|
+
state: "now" | "queued" | "full";
|
|
122
|
+
arrivedAt: number;
|
|
123
|
+
cancel: () => void;
|
|
124
|
+
};
|
|
115
125
|
decide: (req: {
|
|
116
126
|
agent: string;
|
|
117
127
|
method: string;
|
package/types/overlay.d.ts
CHANGED
|
@@ -13,6 +13,14 @@ export function overlaySupportError(versionOutput: string): Error | null;
|
|
|
13
13
|
* @fails Throws `the overlay needs bubblewrap >= 0.11.0 (found X)` when bwrap is older or its version is unreadable. A missing bwrap does not throw here: the real bwrap call then fails as it always did.
|
|
14
14
|
*/
|
|
15
15
|
export function assertOverlaySupport(): void;
|
|
16
|
+
/**
|
|
17
|
+
* Hash a file in 1 MiB chunks, never whole: a multi-GiB file must not
|
|
18
|
+
* exhaust memory at setup. Errors name the path.
|
|
19
|
+
*
|
|
20
|
+
* @param {string} abs absolute path to hash
|
|
21
|
+
* @returns {string} sha256 hex
|
|
22
|
+
*/
|
|
23
|
+
export function hashFile(abs: string): string;
|
|
16
24
|
/** The one walker: project, upper, merged view. Skips ignored/commit dirs (never descended); strict UTF-8 names (non-UTF-8 refused loudly); unreadable entries are refused loudly (never chmodded readable).
|
|
17
25
|
*
|
|
18
26
|
* @param {string} root directory to walk
|
package/types/proxy.d.ts
CHANGED
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
* @param {ProxyOptions} opts
|
|
59
59
|
* @returns live proxy: `ready` resolves when listeners + CA are up; the shape is inferred, see `Proxy`
|
|
60
60
|
* @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.
|
|
61
|
-
* @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.
|
|
61
|
+
* @fails Throws synchronously on a missing or unopenable `logFile` or `runtime`. Throws when another live proxy owns the runtime; the claim dies with its process; nothing is ever taken over. At runtime, dead upstreams, malformed input, over-cap and timed-out holds all become loud logged HTTP errors, never silence and never a crash. A second proxy on the same port rejects `ready`, never crashes the process.
|
|
62
62
|
* @example
|
|
63
63
|
* import { createProxy } from "barebox";
|
|
64
64
|
* const proxy = createProxy({ port: 0, runtime: "./sbx-runtime", logFile: "./mitm.log" });
|
package/types/runtime.d.ts
CHANGED
|
@@ -40,6 +40,17 @@ export function createRuntime(): string;
|
|
|
40
40
|
* @returns {string} the new dir
|
|
41
41
|
*/
|
|
42
42
|
export function runtimeTempDir(scratch: string, prefix: string): string;
|
|
43
|
+
/**
|
|
44
|
+
* Make a runtime dir owner-only whatever the umask: `mode` is masked by
|
|
45
|
+
* the umask and doesn't apply to an existing dir, hence the `chmod`. An
|
|
46
|
+
* existing dir you own is tightened to 0700; one you don't own (`/tmp`,
|
|
47
|
+
* root-owned, shared) is refused, since it can't be made private.
|
|
48
|
+
*
|
|
49
|
+
* @param {string} dir dir to create or fix up
|
|
50
|
+
* @returns {void}
|
|
51
|
+
* @throws {Error} when the dir exists and is owned by another uid
|
|
52
|
+
*/
|
|
53
|
+
export function ensurePrivateDir(dir: string): void;
|
|
43
54
|
/**
|
|
44
55
|
* The abstract-socket name of a runtime's claim lock. Hashes the real path,
|
|
45
56
|
* device and inode, so a symlinked path finds the same lock and a recreated
|
|
@@ -86,6 +97,14 @@ export function claimRuntime(runtime: string): () => void;
|
|
|
86
97
|
* @returns {string} printable text with no VT sequences, C0/C1 controls, or bidi controls
|
|
87
98
|
*/
|
|
88
99
|
export function safe(s: unknown): string;
|
|
100
|
+
/**
|
|
101
|
+
* Quote a path for pasting into a shell: safe spellings come back
|
|
102
|
+
* unchanged, anything else is single-quoted with `'` escaped.
|
|
103
|
+
*
|
|
104
|
+
* @param {string} s path to quote
|
|
105
|
+
* @returns {string} shell-safe spelling
|
|
106
|
+
*/
|
|
107
|
+
export function shellQuote(s: string): string;
|
|
89
108
|
/**
|
|
90
109
|
* Every path in a runtime dir. The one place that names them.
|
|
91
110
|
*
|