barebox 0.2.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/src/run.js ADDED
@@ -0,0 +1,226 @@
1
+ // run.js — one-call sandboxed run (M2.5 integration seam).
2
+ //
3
+ // `run()` wraps the low-level parts (`createProxy` + `addAgent` + `launch`,
4
+ // which stay public): one agent, one sandbox, one audit log, exit code out.
5
+ // The caller never touches sockets, ask files, or the hold queue.
6
+ //
7
+ // What `mode` does TODAY (letters are M3's job): the proxy sees requests,
8
+ // not intent, so until the rwxmap + bareguard letter pipeline lands there is
9
+ // no per-letter policy — only this interim hold rule:
10
+ // - the card/payment FLOOR holds in every mode, including `trust`: a
11
+ // request whose path names a payment destination (`/checkout`,
12
+ // `/payment`, `/orders`, `/purchase`). The card-in-body half of the
13
+ // floor is NOT enforced here: the decide seam sees method/URL/headers
14
+ // but never the body, so body inspection waits for M3's in-proxy rules.
15
+ // Known payment DOMAINS are likewise M3 (they need rwxmap).
16
+ // - `ask`/`auto` additionally park every non-GET/HEAD request (the PRD's
17
+ // "unsure? tag it x" default: GET/HEAD = r, anything else = x). The two
18
+ // modes behave identically until M3's `askOn` letters separate them.
19
+ // - `trust` forwards everything else, logged.
20
+ //
21
+ // A passed `onAsk` answers parked requests with no files involved; when it is
22
+ // absent the file checkpoint runs (`<runtime>/asks` + `<runtime>/answers`,
23
+ // answered from a second terminal with `sbx pending/approve/deny`).
24
+ //
25
+ // `asks` is the collected ask records in park order: the queue reports
26
+ // every park and decision through `onEvent`, so no log is re-parsed and no
27
+ // wrapper re-collects. `audit` is the JSONL audit log path, kept after
28
+ // return — the caller owns the runtime dir (including temp-dir cleanup).
29
+ import fs from 'node:fs';
30
+ import { createProxy } from './proxy.js';
31
+ import { createRuntime, runtimePaths } from './runtime.js';
32
+ import { launch } from './launcher.js';
33
+ import { diffOverlay } from './overlay.js';
34
+
35
+ /** Payment-destination path fragments: the URL-visible half of the floor (PRD section 2). */
36
+ const FLOOR_PATHS = ['/checkout', '/payment', '/orders', '/purchase'];
37
+
38
+ /**
39
+ * The card/payment floor, URL-visible half: park payment destinations in
40
+ * every mode. Returns the hold reason, or null to leave the mode rule alone.
41
+ *
42
+ * @param {{ url: string }} req request, as seen by the decide seam
43
+ * @returns {string|null} hold reason, or null
44
+ */
45
+ function floorReason(req) {
46
+ let pathname;
47
+ try {
48
+ pathname = new URL(req.url).pathname.toLowerCase();
49
+ } catch {
50
+ return null;
51
+ }
52
+ for (const fp of FLOOR_PATHS) {
53
+ if (pathname.includes(fp)) return `payment destination (floor): ${fp}`;
54
+ }
55
+ return null;
56
+ }
57
+
58
+ /**
59
+ * The interim x-rule (PRD "everything else"): GET/HEAD forward, any other
60
+ * method parks. Stands in for M3's letters.
61
+ *
62
+ * @param {{ method: string }} req request, as seen by the decide seam
63
+ * @returns {string|null} hold reason, or null
64
+ */
65
+ function methodReason(req) {
66
+ const m = String(req.method || '').toUpperCase();
67
+ return (m === 'GET' || m === 'HEAD') ? null : `method ${m || '?'} is not GET/HEAD (interim x-rule)`;
68
+ }
69
+
70
+ /**
71
+ * Build the hold decision for a mode. Pure: unit-testable without a sandbox.
72
+ *
73
+ * @param {string} mode `ask` | `auto` | `trust`
74
+ * @returns {import('./holds.js').ShouldHold} decision function for the hold queue
75
+ */
76
+ export function shouldHoldForMode(mode) {
77
+ if (mode !== 'ask' && mode !== 'auto' && mode !== 'trust') {
78
+ throw new Error(`run: mode must be ask|auto|trust, got ${JSON.stringify(mode)}`);
79
+ }
80
+ return (req) => floorReason(req)
81
+ ?? (mode === 'trust' ? null : methodReason(req));
82
+ }
83
+
84
+ /**
85
+ * A collected ask record: the parked ask plus how it was decided.
86
+ *
87
+ * @typedef {object} AskRecord
88
+ * @property {string} id hold id (`h<n>`)
89
+ * @property {string} agent agent name (its socket)
90
+ * @property {string} method HTTP method
91
+ * @property {string} url full URL
92
+ * @property {string} rule hold-reason string
93
+ * @property {string} letter always `'x'` until M3 owns letters
94
+ * @property {string} [bodyPreview] request body preview
95
+ * @property {boolean} [truncated] body preview truncation flag
96
+ * @property {string|null} [expiresAt] ISO-8601 UTC deadline, or null
97
+ * @property {string} [decision] `'allow'` | `'deny'`, once decided
98
+ * @property {string} [reason] decision reason, once decided
99
+ */
100
+
101
+ /**
102
+ * Options for {@link run}.
103
+ *
104
+ * @typedef {object} RunOptions
105
+ * @property {string} proj project directory, bound read-only inside the sandbox
106
+ * @property {string[]} command argv to run inside, for example `["bash", "-c", "echo hi"]`
107
+ * @property {string} [mode] `ask` | `auto` (default) | `trust`; see the mode comment at the top of this file
108
+ * @property {import('./holds.js').OnAsk} [onAsk] ask seam; when present no files are involved, otherwise the file checkpoint runs
109
+ * @property {import('./holds.js').OnEvent} [onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon (also feeds `asks`)
110
+ * @property {string} [runtime] runtime dir (created when absent: a short `sbx-*` temp dir, keeping unix socket paths under the ~108-char limit)
111
+ * @property {string} [agent] agent name (default `'agent'`)
112
+ * @property {number|string} [timeoutMs] hold deadline in ms, or `'never'` (default 120000)
113
+ * @property {object} [unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`): everything under it weakens the sandbox wall
114
+ * @property {NodeJS.WritableStream} [stdout] where the agent's stdout goes (default process.stdout)
115
+ * @property {NodeJS.WritableStream} [stderr] where the agent's stderr goes (default process.stderr)
116
+ * @property {boolean} [overlay] when true, mount a per-run overlay upper over the project (M4 tracing paper) instead of binding it read-only; the result's `diff` lists the run's changes for commit/rollback
117
+ * @property {string[]} [overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
118
+ */
119
+
120
+ /**
121
+ * Run one sandboxed agent start-to-finish in a single call.
122
+ *
123
+ * @param {object} opts
124
+ * @param {string} opts.proj project directory, bound read-only inside the sandbox
125
+ * @param {string[]} opts.command argv to run inside, for example `["bash", "-c", "echo hi"]`
126
+ * @param {string} [opts.mode] `ask` | `auto` (default) | `trust`; see the mode comment at the top of this file
127
+ * @param {import('./holds.js').OnAsk|null} [opts.onAsk] ask seam; when present no files are involved, otherwise the file checkpoint runs
128
+ * @param {import('./holds.js').OnEvent|null} [opts.onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon (also feeds `asks`)
129
+ * @param {string|null} [opts.runtime] runtime dir (created when absent: a short `sbx-*` temp dir, keeping unix socket paths under the ~108-char limit)
130
+ * @param {string} [opts.agent] agent name (default `'agent'`)
131
+ * @param {number|string} [opts.timeoutMs] hold deadline in ms, or `'never'` (default 120000)
132
+ * @param {object|null} [opts.unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`)
133
+ * @param {NodeJS.WritableStream|null} [opts.stdout] where the agent's stdout goes (default process.stdout)
134
+ * @param {NodeJS.WritableStream|null} [opts.stderr] where the agent's stderr goes (default process.stderr)
135
+ * @param {boolean} [opts.overlay] when true, mount a per-run overlay upper over the project instead of binding it read-only; the result's `diff` lists the run's changes for commit/rollback
136
+ * @param {string[]} [opts.overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
137
+ * @returns {Promise<{ exit: number, asks: AskRecord[], audit: string, diff: import('./overlay.js').OverlayChange[], runtime: string }>} the agent process exit code, the collected ask records, the JSONL audit log path, the run's overlay diff (M4), and the runtime dir addressing it
138
+ * @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).
139
+ * @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.
140
+ * @example
141
+ * import { run } from "barebox";
142
+ * const { exit, asks, audit } = await run({ proj: "/tmp/proj", command: ["bash", "-c", "echo hi"] });
143
+ */
144
+ export async function run({ proj, command, mode = 'auto', onAsk = null,
145
+ onEvent = null, runtime = null, agent = 'agent', timeoutMs,
146
+ unsafeTestOnly = null, stdout = null, stderr = null,
147
+ overlay = false, overlayIgnore }) {
148
+ if (typeof proj !== 'string' || !proj) throw new Error('run: proj must be a non-empty string');
149
+ if (!fs.existsSync(proj)) throw new Error(`run: proj does not exist: ${proj}`);
150
+ if (!Array.isArray(command) || !command.length) {
151
+ throw new Error('run: command must be a non-empty argv array');
152
+ }
153
+ if (onAsk != null && typeof onAsk !== 'function') {
154
+ throw new Error('run: onAsk must be a function');
155
+ }
156
+ // Mode first: bad input throws before any runtime dir is created.
157
+ const decide = shouldHoldForMode(mode);
158
+ // Short temp dir: agent socket paths inherit it and cap at ~108 chars.
159
+ const rt = runtime ?? createRuntime();
160
+ const audit = runtimePaths(rt).audit;
161
+
162
+ // Outcomes are reported, never reconstructed: the queue's `onEvent`
163
+ // builds the ask records in park order, for both channels alike.
164
+ /** @type {Map<string, AskRecord>} */
165
+ const seen = new Map();
166
+ /** @param {import('./holds.js').HoldEvent} e */
167
+ const recordEvent = (e) => {
168
+ if (e.type === 'ask') {
169
+ seen.set(e.ask.id, { ...e.ask });
170
+ } else if (e.type === 'decided') {
171
+ const prev = seen.get(e.id);
172
+ if (prev) seen.set(e.id, { ...prev, decision: e.decision, reason: e.reason });
173
+ }
174
+ };
175
+ const holdOnEvent = onEvent
176
+ ? (/** @type {import('./holds.js').HoldEvent} */ e) => { recordEvent(e); onEvent(e); }
177
+ : recordEvent;
178
+
179
+ const proxy = createProxy({
180
+ runtime: rt, logFile: audit, unsafeTestOnly,
181
+ hold: { shouldHold: decide, onAsk, timeoutMs, onEvent: holdOnEvent },
182
+ });
183
+ try {
184
+ await proxy.ready;
185
+ } catch (e) {
186
+ await proxy.close().catch(() => {});
187
+ throw e;
188
+ }
189
+ const sock = proxy.addAgent(agent);
190
+ // `launch` runs INSIDE the try: a synchronous throw there (uncommitted
191
+ // overlay changes, a runtime inside the project) must still close the
192
+ // proxy — otherwise its listening sockets keep this process alive forever.
193
+ /** @type {number} */
194
+ let exit;
195
+ try {
196
+ const child = launch({
197
+ runtime: rt, agent, proj, command,
198
+ socket: sock, caFile: proxy.caFile,
199
+ overlay, overlayIgnore,
200
+ });
201
+ const out = stdout ?? process.stdout;
202
+ const err = stderr ?? process.stderr;
203
+ child.stdout?.on('data', (c) => { try { out.write(c); } catch {} });
204
+ child.stderr?.on('data', (c) => { try { err.write(c); } catch {} });
205
+ exit = await new Promise((resolve, reject) => {
206
+ child.on('error', reject);
207
+ child.on('close', (code) => resolve(code ?? 1));
208
+ });
209
+ } finally {
210
+ await proxy.close();
211
+ }
212
+ // M2.5 item 4: the result carries the M4 diff. Without overlay there is no
213
+ // upper, so nothing to review — an empty diff, never null.
214
+ /** @type {import('./overlay.js').OverlayChange[]} */
215
+ let diff = [];
216
+ if (overlay) {
217
+ try {
218
+ diff = diffOverlay({ runtime: rt, agent });
219
+ } catch (e) {
220
+ const err = /** @type {Error & {exit?: number}} */ (e instanceof Error ? e : new Error(String(e)));
221
+ err.exit = exit;
222
+ throw new Error(`run: overlay diff failed after exit ${exit}: ${err.message}`);
223
+ }
224
+ }
225
+ return { exit, asks: [...seen.values()], audit, diff, runtime: rt };
226
+ }
package/src/runtime.js ADDED
@@ -0,0 +1,263 @@
1
+ // runtime.js — the single writer of the runtime folder layout.
2
+ //
3
+ // Every path both sides agree on lives here: the proxy socket, the hold
4
+ // queue's ask/answer files, the certificates dir, the CA bundle, the audit
5
+ // log, and the overlay record. Import layout from here; no other module
6
+ // names these paths. (The sandbox launcher used to import them from the
7
+ // TLS proxy just to get a filename.)
8
+ import crypto from 'node:crypto';
9
+ import fs from 'node:fs';
10
+ import net from 'node:net';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { stripVTControlCharacters } from 'node:util';
14
+
15
+ export const AGENT_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
16
+ // Linux sun_path: 108 bytes including the NUL.
17
+ const MAX_SOCK_PATH = 107;
18
+
19
+ /**
20
+ * Check an agent name before it reaches the filesystem.
21
+ *
22
+ * @param {string} name agent name
23
+ * @returns {void} throws on `../` and friends
24
+ */
25
+ export function assertAgentName(name) {
26
+ if (!AGENT_RE.test(name || '')) {
27
+ throw new Error(`bad agent name ${JSON.stringify(name)}: must match ${AGENT_RE}`);
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Resolve symlinks through the nearest existing ancestor: socket paths may
33
+ * not exist yet, so `realpathSync` on the full path would throw. Walks up
34
+ * to the first existing ancestor, resolves that, then re-attaches the rest.
35
+ *
36
+ * @param {string} p any path, existing or not
37
+ * @returns {string} the real (symlink-free) spelling of `p`
38
+ */
39
+ export function realPathOf(p) {
40
+ const abs = path.resolve(p);
41
+ let cur = abs;
42
+ /** @type {string[]} */
43
+ const rest = [];
44
+ while (!fs.existsSync(cur)) {
45
+ const parent = path.dirname(cur);
46
+ if (parent === cur) break;
47
+ rest.unshift(path.basename(cur));
48
+ cur = parent;
49
+ }
50
+ const real = fs.realpathSync(cur);
51
+ return rest.length ? path.join(real, ...rest) : real;
52
+ }
53
+
54
+ /**
55
+ * True when `p` is `base` or lives under it, compared as real (symlink-free)
56
+ * paths, so a symlinked spelling cannot smuggle a path out.
57
+ *
58
+ * @param {string} base container path
59
+ * @param {string} p path to test
60
+ * @returns {boolean} containment on real paths
61
+ */
62
+ export function isInside(base, p) {
63
+ const realB = realPathOf(base);
64
+ const realP = realPathOf(p);
65
+ if (realP === realB) return true;
66
+ const prefix = realB.endsWith(path.sep) ? realB : realB + path.sep;
67
+ return realP.startsWith(prefix);
68
+ }
69
+
70
+ /**
71
+ * Create a short-lived runtime dir: a short `sbx-` temp dir, keeping unix
72
+ * socket paths under the ~108-char limit.
73
+ *
74
+ * @returns {string} the new runtime dir
75
+ */
76
+ export function createRuntime() {
77
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'sbx-'));
78
+ }
79
+
80
+ /**
81
+ * Create a temp dir inside the runtime tree: `mkdtemp` is a runtime-layout
82
+ * writer, so it lives here, not in `overlay.js`. Used for the merged-view
83
+ * mount (`merged`) and the walker manifest dir (`walk`).
84
+ *
85
+ * @param {string} scratch overlay record dir (`overlay/<agent>`)
86
+ * @param {string} prefix dir prefix (`merged`, `walk`)
87
+ * @returns {string} the new dir
88
+ */
89
+ export function runtimeTempDir(scratch, prefix) {
90
+ return fs.mkdtempSync(path.join(scratch, `${prefix}-`));
91
+ }
92
+
93
+ /** @param {string} owner owner file path @returns {unknown} the pid it names, or 'unknown' when missing, empty or garbage */
94
+ function pidOf(owner) {
95
+ try {
96
+ return JSON.parse(fs.readFileSync(owner, 'utf8'))?.pid ?? 'unknown';
97
+ } catch {
98
+ return 'unknown';
99
+ }
100
+ }
101
+
102
+ /** @param {unknown} pid @returns {boolean} true when a process with that pid is alive */
103
+ function isPidAlive(pid) {
104
+ if (typeof pid !== 'number') return false;
105
+ try {
106
+ process.kill(pid, 0);
107
+ return true;
108
+ } catch (e) {
109
+ return /** @type {{code?: string}} */ (e)?.code === 'EPERM';
110
+ }
111
+ }
112
+
113
+ /** @param {string} runtime runtime dir @param {unknown} pid the holder @returns {Error} the one in-use error */
114
+ function inUseError(runtime, pid) {
115
+ return new Error(
116
+ `runtime ${runtime} is in use by pid ${String(pid)} (one proxy per runtime: use another SBX_RUNTIME, or leave it unset for a fresh one)`);
117
+ }
118
+
119
+ /**
120
+ * The abstract-socket name of a runtime's claim lock. Hashes the real path,
121
+ * device and inode, so a symlinked path finds the same lock and a recreated
122
+ * dir gets a new one.
123
+ *
124
+ * @param {string} runtime runtime dir
125
+ * @returns {string} the abstract socket name
126
+ */
127
+ export function lockName(runtime) {
128
+ const real = fs.realpathSync(runtime);
129
+ const st = fs.statSync(real);
130
+ return '\0barebox-' + crypto.createHash('sha256')
131
+ .update(`${real}\0${st.dev}\0${st.ino}`).digest('hex').slice(0, 32);
132
+ }
133
+
134
+ /**
135
+ * True when a live proxy owns the runtime: something answers on its lock.
136
+ * Never binds, so it can never steal the claim from a proxy that's starting.
137
+ * A runtime that doesn't exist is not live.
138
+ *
139
+ * @param {string} runtime runtime dir
140
+ * @returns {Promise<boolean>} whether the lock connects
141
+ */
142
+ export function runtimeLive(runtime) {
143
+ let name;
144
+ try {
145
+ name = lockName(runtime);
146
+ } catch {
147
+ return Promise.resolve(false);
148
+ }
149
+ return new Promise((resolve) => {
150
+ const sock = net.connect(name);
151
+ sock.on('connect', () => { sock.destroy(); resolve(true); });
152
+ sock.on('error', () => resolve(false));
153
+ });
154
+ }
155
+
156
+ /**
157
+ * Claim one runtime for one live proxy: the single enforcer of "one proxy
158
+ * owns a runtime". The claim is an abstract unix socket the proxy binds for
159
+ * as long as it lives (Linux). The kernel frees it when the process dies,
160
+ * SIGKILL included, so a claim is never stale: nothing is judged, taken
161
+ * over or deleted by hand. The name hashes the real path, device and inode,
162
+ * so a symlinked path finds the same lock and a recreated dir gets a new one.
163
+ * The bind result is synchronous (`server.listening` right after `listen`),
164
+ * so a second claim, in this process or another, throws before the caller
165
+ * touches the runtime. The lock is `unref`'d: it never keeps a process alive.
166
+ * The owner file `{"pid"}` is written by the lock holder only, to name it in
167
+ * the in-use message.
168
+ *
169
+ * @param {string} runtime runtime dir to claim
170
+ * @returns {() => void} `release()`: unlinks the owner file only when it holds our pid, then closes the lock; idempotent per claim
171
+ */
172
+ export function claimRuntime(runtime) {
173
+ fs.mkdirSync(runtime, { recursive: true });
174
+ const real = fs.realpathSync(runtime);
175
+ const owner = runtimePaths(real).owner;
176
+ const name = lockName(runtime);
177
+ const server = net.createServer((c) => c.destroy());
178
+ server.on('error', () => {});
179
+ server.listen(name);
180
+ if (!server.listening) {
181
+ const pid = pidOf(owner);
182
+ if (isPidAlive(pid)) throw inUseError(runtime, pid);
183
+ throw new Error(`runtime ${runtime} could not be locked: no live owner is recorded (another proxy may be starting, or this process cannot bind unix sockets)`);
184
+ }
185
+ server.unref();
186
+ const tmp = `${owner}.tmp-${crypto.randomBytes(8).toString('hex')}`;
187
+ try {
188
+ fs.writeFileSync(tmp, JSON.stringify({ pid: process.pid }), { flag: 'wx', mode: 0o600 });
189
+ fs.renameSync(tmp, owner);
190
+ } catch (e) {
191
+ server.close();
192
+ throw e;
193
+ } finally {
194
+ try { fs.unlinkSync(tmp); } catch {}
195
+ }
196
+ let released = false;
197
+ return () => {
198
+ if (released) return;
199
+ released = true;
200
+ if (pidOf(owner) === process.pid) {
201
+ try { fs.unlinkSync(owner); } catch {}
202
+ }
203
+ server.close();
204
+ };
205
+ }
206
+
207
+ /**
208
+ * Strip terminal control before printing agent-controlled bytes (ask URLs,
209
+ * rules, body previews, overlay paths): an escape sequence smuggled into a
210
+ * preview could otherwise rewrite the approver's terminal line before
211
+ * approval, and bidi controls in an agent-chosen filename could flip how a
212
+ * reviewed path reads.
213
+ *
214
+ * @param {unknown} s value to print
215
+ * @returns {string} printable text with no VT sequences, C0/C1 controls, or bidi controls
216
+ */
217
+ export function safe(s) {
218
+ return stripVTControlCharacters(String(s ?? ''))
219
+ .replace(/[\x00-\x1f\x7f]/g, '')
220
+ .replace(/[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '');
221
+ }
222
+
223
+ /**
224
+ * Every path in a runtime dir. The one place that names them.
225
+ *
226
+ * @param {string} runtime runtime dir
227
+ * @returns {{ socket: (agent: string) => string, asksDir: string, answersDir: string, askFile: (id: string) => string, answerFile: (id: string) => string, certsDir: string, caBundle: string, audit: string, owner: string, overlay: (agent: string) => { base: string, upper: string, work: string, manifest: string } }} layout
228
+ */
229
+ export function runtimePaths(runtime) {
230
+ const asksDir = path.join(runtime, 'asks');
231
+ const answersDir = path.join(runtime, 'answers');
232
+ return {
233
+ owner: path.join(runtime, 'owner'),
234
+ asksDir,
235
+ answersDir,
236
+ askFile: (id) => path.join(asksDir, `${id}.json`),
237
+ answerFile: (id) => path.join(answersDir, `${id}.json`),
238
+ /**
239
+ * The one path both sides agree on: the proxy listens here, the
240
+ * launcher binds it into the sandbox.
241
+ */
242
+ socket: (agent) => {
243
+ assertAgentName(agent);
244
+ const p = path.join(runtime, 'socks', `${agent}.sock`);
245
+ if (p.length > MAX_SOCK_PATH) {
246
+ throw new Error(`agent socket path too long (${p.length} > ${MAX_SOCK_PATH}): ${p}`);
247
+ }
248
+ return p;
249
+ },
250
+ certsDir: path.join(runtime, 'certs'),
251
+ caBundle: path.join(runtime, 'ca-bundle.pem'),
252
+ audit: path.join(runtime, 'audit.jsonl'),
253
+ overlay: (agent) => {
254
+ const base = path.join(runtime, 'overlay', agent);
255
+ return {
256
+ base,
257
+ upper: path.join(base, 'upper'),
258
+ work: path.join(base, 'work'),
259
+ manifest: path.join(base, 'manifest.json'),
260
+ };
261
+ },
262
+ };
263
+ }
package/src/wall.js ADDED
@@ -0,0 +1,156 @@
1
+ // wall.js — the upstream wall: the one place that decides where the proxy
2
+ // may dial.
3
+ //
4
+ // Default-deny for loopback, link-local (incl. cloud metadata 169.254/16),
5
+ // the host's own addresses, and private LAN ranges (RFC 1918, CGNAT
6
+ // 100.64/10, IPv6 ULA fc00::/7). The check runs AFTER DNS resolution, so a
7
+ // hostname that resolves to 127.0.0.1 is denied exactly like the literal.
8
+ // Unresolvable names are denied too (fail closed, never 502-then-dial).
9
+ // Only the TEST-ONLY `unsafeTestOnly.allowLoopback` (loopback + unspecified)
10
+ // lets a denied destination through; only tests pass it. There is no
11
+ // allowPrivate flag and no per-host escape hatch: the wall is default-deny.
12
+ import net from 'node:net';
13
+ import os from 'node:os';
14
+ import { lookup as dnsLookup } from 'node:dns/promises';
15
+
16
+ /** Strip brackets/scope, lowercase: one spelling per address. */
17
+ function normIp(ip) {
18
+ let s = String(ip || '').toLowerCase();
19
+ if (s.startsWith('[') && s.endsWith(']')) s = s.slice(1, -1);
20
+ const pct = s.indexOf('%');
21
+ if (pct >= 0) s = s.slice(0, pct);
22
+ return s;
23
+ }
24
+
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
+ function v4Parts(ip) {
32
+ return ip.split('.').map((p) => parseInt(p, 10));
33
+ }
34
+
35
+ /** This machine's own interface addresses, one spelling (see `normIp`). */
36
+ function localIps() {
37
+ const out = new Set();
38
+ let ifs = {};
39
+ // networkInterfaces() can throw where interfaces are hidden (a sandbox is
40
+ // exactly where the wall matters most): lose host-local, keep the rest.
41
+ try {
42
+ ifs = os.networkInterfaces();
43
+ } catch {
44
+ return out;
45
+ }
46
+ for (const addrs of Object.values(ifs)) {
47
+ for (const a of addrs ?? []) {
48
+ if (a && a.address) out.add(normIp(a.address));
49
+ }
50
+ }
51
+ return out;
52
+ }
53
+
54
+ /**
55
+ * Why `ip` (already resolved) is denied, or null when it may go through.
56
+ *
57
+ * @param {string} rawIp resolved destination IP
58
+ * @param {boolean} allowLoopback test-only opt-in for loopback + unspecified
59
+ * @returns {string|null} `loopback` / `unspecified` / `link-local` / `host-local` / `private`, or null
60
+ */
61
+ export function denyReasonForIp(rawIp, allowLoopback) {
62
+ const ip = normIp(rawIp);
63
+ const v4 = mappedV4(ip) ?? (net.isIP(ip) === 4 ? ip : null);
64
+ if (v4) {
65
+ const [a, b] = v4Parts(v4);
66
+ if (a === 127) return allowLoopback ? null : 'loopback';
67
+ if (a === 0) return allowLoopback ? null : 'unspecified';
68
+ if (a === 169 && b === 254) return 'link-local';
69
+ if (a === 10) return 'private';
70
+ if (a === 172 && b >= 16 && b <= 31) return 'private';
71
+ if (a === 192 && b === 168) return 'private';
72
+ if (a === 100 && b >= 64 && b <= 127) return 'private';
73
+ if (localIps().has(v4)) return 'host-local';
74
+ return null;
75
+ }
76
+ if (net.isIP(ip) === 6) {
77
+ if (ip === '::1') return allowLoopback ? null : 'loopback';
78
+ if (ip === '::') return allowLoopback ? null : 'unspecified';
79
+ const first = parseInt(ip.split(':')[0] || '0', 16);
80
+ if (first >= 0xfe80 && first <= 0xfebf) return 'link-local';
81
+ if (first >= 0xfc00 && first <= 0xfdff) return 'private';
82
+ if (localIps().has(ip)) return 'host-local';
83
+ return null;
84
+ }
85
+ return null;
86
+ }
87
+
88
+ /**
89
+ * Resolve `host` to every IP for the wall. Literals need no DNS.
90
+ * Fail closed: anything that does not resolve is denied, never dialed.
91
+ *
92
+ * @param {string} host CONNECT/request hostname
93
+ * @param {(host: string) => Promise<string[] | string | null>} [stub] test-only DNS stub
94
+ * @returns {Promise<string[] | null>} all resolved IPs, or null when unresolvable
95
+ */
96
+ async function resolveAllUpstream(host, stub) {
97
+ if (net.isIP(host)) return [host];
98
+ try {
99
+ if (typeof stub === 'function') {
100
+ const r = await stub(host);
101
+ if (!r) return null;
102
+ if (Array.isArray(r)) return r.length ? [...r] : null;
103
+ if (typeof r === 'string') return [r];
104
+ return null;
105
+ }
106
+ const all = await dnsLookup(host, { all: true });
107
+ if (!all || !all.length) return null;
108
+ return all.map((a) => a.address);
109
+ } catch {
110
+ return null;
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Order resolved addresses with IPv4 and IPv6 interleaved, keeping DNS order within each family.
116
+ *
117
+ * @param {string[]} ips resolved addresses, already checked against the wall
118
+ * @returns {string[]} dial order, starting with the family DNS listed first
119
+ */
120
+ function interleaveIps(ips) {
121
+ const v4 = ips.filter((ip) => net.isIP(ip) !== 6);
122
+ const v6 = ips.filter((ip) => net.isIP(ip) === 6);
123
+ const [first, second] = net.isIP(ips[0]) === 6 ? [v6, v4] : [v4, v6];
124
+ const out = [];
125
+ while (first.length || second.length) {
126
+ if (first.length) out.push(/** @type {string} */ (first.shift()));
127
+ if (second.length) out.push(/** @type {string} */ (second.shift()));
128
+ }
129
+ return out;
130
+ }
131
+
132
+ /**
133
+ * The wall: resolve every answer, then default-deny loopback/link-local/
134
+ * host-local/private unless the test-only opt-ins allow it. Denies when ANY
135
+ * answer is walled, denies unresolvable names, and pins every checked IP so
136
+ * the dial below tries them in order without resolving a second time (no
137
+ * rebinding, with fallback when the first address refuses).
138
+ *
139
+ * @param {string} host CONNECT/request hostname
140
+ * @param {{ allowLoopback: boolean, resolveUpstream?: (host: string) => Promise<string[] | string | null> }} gate
141
+ * @returns {Promise<{ ok: true, ips: string[] } | { ok: false, ip: string, reason: string }>}
142
+ */
143
+ export async function checkUpstream(host, gate) {
144
+ const ips = await resolveAllUpstream(host, gate.resolveUpstream);
145
+ if (!ips || !ips.length) {
146
+ return { ok: false, ip: host, reason: `unresolvable upstream denied: ${host}` };
147
+ }
148
+ for (const ip of ips) {
149
+ const kind = denyReasonForIp(ip, gate.allowLoopback);
150
+ if (kind) {
151
+ const where = ip === host ? host : `${host} (${ip})`;
152
+ return { ok: false, ip, reason: `${kind} upstream denied: ${where}` };
153
+ }
154
+ }
155
+ return { ok: true, ips: interleaveIps(ips) };
156
+ }
package/types/certs.d.ts CHANGED
@@ -22,3 +22,5 @@ export function certFor(dir: string, host: string): Promise<{
22
22
  key: Buffer;
23
23
  cert: Buffer;
24
24
  }>;
25
+ /** Hostname/IP spelling both the mint cache and the proxy wall accept. Single definition (see proxy.js). */
26
+ export const HOST_RE: RegExp;