barebox 0.6.0 → 0.8.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/launcher.js CHANGED
@@ -5,7 +5,7 @@
5
5
  import { spawn } from 'node:child_process';
6
6
  import { accessSync, constants, existsSync, lstatSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
7
7
  import { join, relative, dirname, delimiter } from 'node:path';
8
- import { assertAgentName, isInside, realPathOf, runtimePaths } from './runtime.js';
8
+ import { assertAgentName, hostNode, isInside, realPathOf, runtimePaths, usrLinks } from './runtime.js';
9
9
  import { assertOverlaySupport, setupOverlay } from './overlay.js';
10
10
  import { configPath } from './config.js';
11
11
 
@@ -47,28 +47,30 @@ const LOCKED_PATHS = [
47
47
  '.cargo/credentials.toml',
48
48
  ];
49
49
 
50
+ const SYSTEM_PATH = ['/usr/bin', '/bin', '/usr/sbin'];
51
+
50
52
  /**
51
53
  * The bwrap args that mask one locked path, or none when it does not exist.
52
54
  * A symlinked drawer (dotfile managers) is masked at its real target, which
53
55
  * is where bwrap lands a mount anyway, so the content is shut at both
54
- * spellings; a target outside `$HOME` and the project is not bound into the
55
- * sandbox at all, so there is nothing to mask.
56
+ * spellings; a target outside every bound root is not in the sandbox at all,
57
+ * so there is nothing to mask.
56
58
  *
57
- * @param {string} abs the locked path (under `$HOME` or the project to matter)
58
- * @param {string} home `$HOME`
59
- * @param {string} proj project dir
59
+ * @param {string} abs the locked path (under a bound root to matter)
60
+ * @param {string[]} roots the paths the sandbox binds in: `$HOME`, the project, `/etc`, `/usr` and the Node install
60
61
  * @returns {string[]} `--tmpfs <dir>` or `--dev-bind /dev/null <file>`, or `[]`
61
62
  */
62
- function lockMask(abs, home, proj) {
63
- // Neither under $HOME nor the project: not bound into the sandbox at all.
64
- if (!isInside(home, abs) && !isInside(proj, abs)) return [];
63
+ function lockMask(abs, roots) {
64
+ const bound = (p) => roots.some((r) => isInside(r, p));
65
+ // Under no bound root: not in the sandbox at all.
66
+ if (!bound(abs)) return [];
65
67
  let target = abs;
66
68
  let st;
67
69
  try {
68
70
  st = lstatSync(abs);
69
71
  if (st.isSymbolicLink()) {
70
72
  target = realPathOf(abs);
71
- if (!isInside(home, target) && !isInside(proj, target)) return [];
73
+ if (!bound(target)) return [];
72
74
  st = statSync(target);
73
75
  }
74
76
  } catch {
@@ -135,7 +137,8 @@ export function buildCaBundle(runtime, caFile) {
135
137
  }
136
138
 
137
139
  /**
138
- * Start one sandboxed agent. The agent sees a read-only `/usr` and `/etc`,
140
+ * Start one sandboxed agent. The agent sees a read-only `/usr` and `/etc`
141
+ * (and the host's `/bin`, `/sbin`, `/lib`, `/lib64`, mirrored),
139
142
  * its project and home read-only, the locked drawers masked, no network of
140
143
  * its own, and a single front door: anything sent to `localhost:<proxyPort>`
141
144
  * is carried out through this agent's socket to the proxy. The agent starts
@@ -155,19 +158,20 @@ export function buildCaBundle(runtime, caFile) {
155
158
  * @param {{ pass?: string[], set?: Record<string, string>, placeholders?: Record<string, string> }} [opts.env] the inside's environment (M5). The host environment never reaches it except: a short default list (`TERM`, `COLORTERM`, `LANG`, `LANGUAGE`, `LC_*`, `TZ`, `USER`, `LOGNAME`, `SHELL`, `EDITOR`, `PAGER`), the host variables named in `pass`, the values in `set`, and one placeholder per secret under its own name (`placeholders`, name to value). Set in that order, then `extraEnv`.
156
159
  * @param {string|null} [opts.socket] agent socket path, as returned by `proxy.addAgent` (default `<runtime>/socks/<agent>.sock`; the two must agree)
157
160
  * @param {string|null} [opts.caFile] barebox CA cert path (from `proxy.caFile`); when set, the sandbox trusts it for HTTPS alongside the system roots
161
+ * @param {string} [opts.nodeExec] the node executable to run inside (default: this process's `process.execPath`). The install is a `bin/` layout's parent dir (npm and global CLIs live there) or, for any other layout, the exec's own dir. It is bound read-only with the exec's dir first on the inside PATH, unless already visible there (under `/usr`, `$HOME` or the project). Never bound when it is `/`, `$HOME` or above it: then it is not on PATH either (see `hostNode` in `src/runtime.js`). A runtime or project under the install is masked or mounted over it, so the bind never exposes either
158
162
  * @param {string[]} [opts.maskDirs] extra folders hidden from the agent exactly like barebox's config dir (the `labels` folders: the agent must not read or rewrite a letter)
159
163
  * @param {boolean} [opts.overlay] when true, mount a per-run overlay upper over the project (M4 tracing paper) instead of binding it read-only; diff/commit/rollback address it as `runtimePaths(runtime).overlay(agent)`
160
164
  * @param {string[]} [opts.overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
161
165
  * @returns {import('node:child_process').ChildProcess} the bwrap child (stdio piped); `close` gives its exit code
162
166
  * @when Reach for this to HARNESS-ONLY start one sandboxed agent run: it creates the sandbox the agent lives in. It does not decide anything; combine with the proxy for the front door and the gate (M3) for policy. Pass overlay:true for a writable tracing-paper run (M4). The agent starts in the project dir.
163
- * @fails Throws synchronously on a missing/empty `runtime`, `agent`, `proj`, or `command`, on a bad agent name, on a non-integer `proxyPort`, on an over-long socket path, when `socket` disagrees with `<runtime>/socks/<agent>.sock`, when `runtime` IS `HOME` or the project dir (its sockets could not be hidden from the agent), or with overlay on when the runtime sits inside the project or uncommitted changes linger. The child fails at runtime (nonzero exit) when `bwrap` or `socat` is missing inside, or when nothing listens on the agent socket.
167
+ * @fails Throws synchronously on a missing/empty `runtime`, `agent`, `proj`, or `command`, on a bad agent name, on a non-integer `proxyPort`, on an over-long socket path, when `socket` disagrees with `<runtime>/socks/<agent>.sock`, when `runtime` IS `HOME`, the project dir, `/etc`, `/usr` or the bound Node install dir (its sockets could not be hidden from the agent), or with overlay on when the runtime sits inside the project or uncommitted changes linger. The child fails at runtime (nonzero exit) when `bwrap` or `socat` is missing inside, or when nothing listens on the agent socket.
164
168
  * @example
165
169
  * import { launch } from "barebox";
166
170
  * const child = launch({ runtime: "/tmp/sbx", agent: "fx", proj: "/tmp/proj", command: ["bash", "-c", "echo hi"] });
167
171
  * await new Promise((r) => child.on("close", r)); // child.exitCode === 0
168
172
  */
169
173
  export function launch({ runtime, agent, proj, command, proxyPort = 3128,
170
- extraEnv = {}, env = {}, socket = null, caFile = null, overlay = false, overlayIgnore, maskDirs = [] }) {
174
+ extraEnv = {}, env = {}, socket = null, caFile = null, overlay = false, overlayIgnore, maskDirs = [], nodeExec = process.execPath }) {
171
175
  for (const [k, v] of Object.entries({ runtime, agent, proj })) {
172
176
  if (typeof v !== 'string' || !v) throw new Error(`launch: ${k} must be a non-empty string`);
173
177
  }
@@ -195,14 +199,25 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
195
199
  ov = setupOverlay({ runtime, agent, proj, ignore: overlayIgnore });
196
200
  }
197
201
  const home = process.env.HOME || '/root';
202
+ // A Node outside /usr and $HOME (nvm, a CI toolcache) is bound read-only too, so the host's
203
+ // node and its global CLIs run inside.
204
+ const { bin: nodeBin, bind: nodeBind } = hostNode(nodeExec, home, proj);
205
+ // Every path the sandbox binds in from the host: the locked drawers and mask folders are
206
+ // hidden wherever they sit under one of these.
207
+ const links = usrLinks();
208
+ const roots = [home, proj, '/etc', '/usr', ...links.bound, ...(nodeBind ? [nodeBind] : [])];
198
209
  const args = [
199
210
  '--unshare-pid', '--unshare-uts', '--unshare-ipc', '--unshare-net',
200
211
  '--die-with-parent',
201
212
  '--proc', '/proc', '--dev', '/dev', '--tmpfs', '/tmp',
202
213
  '--ro-bind', '/usr', '/usr',
203
- '--symlink', 'usr/lib64', '/lib64',
214
+ ...links.args,
204
215
  '--ro-bind', '/etc', '/etc',
205
- // $HOME first, the project second: a project under $HOME would otherwise
216
+ // The Node install first: a project or runtime inside it must win over it.
217
+ // It never holds $HOME and is never inside $HOME, /usr or the project (then
218
+ // it is not bound), so the only overlap is a project or runtime under it.
219
+ ...(nodeBind ? ['--ro-bind', nodeBind, nodeBind] : []),
220
+ // $HOME next, the project after: a project under $HOME would otherwise
206
221
  // vanish under the home bind (bwrap mounts cover what is below them —
207
222
  // the later mount wins where they overlap). The project mount (overlay
208
223
  // or read-only) therefore lands on top of the read-only home.
@@ -222,12 +237,12 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
222
237
  // Locked drawers AFTER the project mount: the tmpfs mask must land on top,
223
238
  // or a project that contains one of these paths (a project that IS $HOME,
224
239
  // or holds its own `.ssh`) would leak the real drawer through the overlay.
225
- for (const p of LOCKED_PATHS) args.push(...lockMask(`${home}/${p}`, home, proj));
240
+ for (const p of LOCKED_PATHS) args.push(...lockMask(`${home}/${p}`, roots));
226
241
  // barebox's own config: settings the agent must neither read nor edit.
227
242
  // Masked wherever it resolves (XDG_CONFIG_HOME may move it).
228
- args.push(...lockMask(dirname(configPath(process.env)), home, proj));
243
+ args.push(...lockMask(dirname(configPath(process.env)), roots));
229
244
  // The label folders (the letters live there) get the same mask.
230
- for (const d of maskDirs) args.push(...lockMask(d, home, proj));
245
+ for (const d of maskDirs) args.push(...lockMask(d, roots));
231
246
  // The runtime tree holds the file-checkpoint dirs (`asks/`, `answers/`
232
247
  // — the approve/deny capability) and every agent's socket (identity). A
233
248
  // read-only bind does NOT stop connect(2) to a unix socket, so wherever
@@ -246,21 +261,21 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
246
261
  // resolved), so a runtime passed as a symlink from outside $HOME/proj
247
262
  // can still land inside it and stay visible through the ro-binds — the
248
263
  // mask below covers that spelling too.
249
- const hm = join(home);
250
- const pr = join(proj);
264
+ // Every root the sandbox binds: (real path, the spelling bwrap sees).
265
+ const bases = roots.map((r) => [realPathOf(join(r)), join(r)]);
251
266
  const realRt = realPathOf(join(runtime));
252
- const realHm = realPathOf(hm);
253
- const realPr = realPathOf(pr);
254
267
  // One real-path comparison: a lexically-equal spelling resolves to the
255
268
  // same real path, so it is subsumed here.
256
- if (realRt === realHm || realRt === realPr) {
257
- throw new Error(`launch: runtime must not be ${realRt === realHm ? 'HOME' : 'the project dir'} itself (its sockets cannot be hidden there)`);
269
+ const same = bases.findIndex(([realBase]) => realRt === realBase);
270
+ if (same >= 0) {
271
+ const what = same === 0 ? 'HOME' : same === 1 ? 'the project dir' : roots[same] === nodeBind ? 'the Node install dir' : roots[same];
272
+ throw new Error(`launch: runtime must not be ${what} itself (its sockets cannot be hidden there)`);
258
273
  }
259
- // Mask the sandbox-visible spelling join(home, relative(realHome, realRt))
260
- // (likewise proj): where nothing is a symlink this IS the lexical path,
261
- // so no separate lexical mask is needed.
262
- for (const [realBase, baseSpelling] of [[realHm, hm], [realPr, pr]]) {
263
- if (realRt !== realBase && isInside(realBase, realRt)) {
274
+ // Mask the sandbox-visible spelling join(root, relative(realRoot, realRt)):
275
+ // where nothing is a symlink this IS the lexical path, so no separate
276
+ // lexical mask is needed.
277
+ for (const [realBase, baseSpelling] of bases) {
278
+ if (isInside(realBase, realRt)) {
264
279
  const m = join(baseSpelling, relative(realBase, realRt));
265
280
  if (!args.includes(m)) args.push('--tmpfs', m);
266
281
  }
@@ -279,7 +294,10 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
279
294
  }
280
295
  args.push(
281
296
  '--setenv', 'HOME', home,
282
- '--setenv', 'PATH', '/usr/bin:/bin:/usr/sbin',
297
+ // ~/.local/bin (where `claude` installs) goes last, so it never shadows a system tool; no new
298
+ // exposure: the dir is already visible through the read-only $HOME bind.
299
+ '--setenv', 'PATH', [...(!nodeBin || SYSTEM_PATH.includes(nodeBin) ? [] : [nodeBin]), ...SYSTEM_PATH,
300
+ ...(existsSync(`${home}/.local/bin`) ? [`${home}/.local/bin`] : [])].join(':'),
283
301
  '--setenv', 'HTTP_PROXY', `http://127.0.0.1:${proxyPort}`,
284
302
  '--setenv', 'HTTPS_PROXY', `http://127.0.0.1:${proxyPort}`,
285
303
  '--setenv', 'http_proxy', `http://127.0.0.1:${proxyPort}`,
@@ -303,8 +321,10 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
303
321
  for (const [k, v] of Object.entries(env.placeholders ?? {})) args.push('--setenv', k, String(v));
304
322
  for (const [k, v] of Object.entries(extraEnv)) args.push('--setenv', k, String(v));
305
323
  const door = String(proxyPort);
324
+ // `-lf /dev/null` drops socat's own log: an early-closed connection prints harmless `E` lines.
325
+ // Safe because a bridge that failed to start is still caught below by the door probe (exit 99).
306
326
  const inner = 'ip link set lo up 2>/dev/null; ' +
307
- `socat TCP-LISTEN:${door},bind=127.0.0.1,reuseaddr,fork UNIX-CONNECT:/run/sbx/agent.sock & ` +
327
+ `socat -lf /dev/null TCP-LISTEN:${door},bind=127.0.0.1,reuseaddr,fork UNIX-CONNECT:/run/sbx/agent.sock & ` +
308
328
  `ok=; for i in $(seq 1 50); do (echo > /dev/tcp/127.0.0.1/${door}) 2>/dev/null && { ok=1; break; }; sleep 0.1; done; ` +
309
329
  '[ -n "$ok" ] || exit 99; exec "$@"';
310
330
  const child = spawn(bwrapBin(), [...args, '/usr/bin/bash', '-c', inner, 'bash', ...command],
package/src/overlay.js CHANGED
@@ -18,7 +18,7 @@ import {
18
18
  } from 'node:fs';
19
19
  import { join, dirname } from 'node:path';
20
20
  import { fileURLToPath } from 'node:url';
21
- import { assertAgentName, runtimeTempDir, runtimePaths, safe } from './runtime.js';
21
+ import { assertAgentName, hostNode, runtimeTempDir, runtimePaths, safe, usrLinks } from './runtime.js';
22
22
 
23
23
  /** One reviewed file change: what the sandbox did at `path`, and whether the project changed underneath it mid-run.
24
24
  *
@@ -468,16 +468,16 @@ function bwrapWalk({ lower, upper, work, ignore, scratch, stageDir = null, upper
468
468
  // /usr). Its prefix is bound read-only when /usr does not already show it.
469
469
  const node = realpathSync(process.execPath);
470
470
  const underUsr = node === '/usr' || node.startsWith('/usr/');
471
- const nodeParent = dirname(node);
472
- const nodePrefix = nodeParent.endsWith('/bin') ? dirname(nodeParent) : nodeParent;
471
+ // Only the install dir: this trusted walker binds even `/` (see below), so `refused` is ignored.
472
+ const nodePrefix = hostNode(node, process.env.HOME || '/root').dir;
473
473
  try {
474
474
  // No output cap (stdout carries no data) and no time limit: the walk
475
475
  // is finite (`lstat`, never following symlinks), and killing a commit's
476
476
  // extraction halfway helps nobody.
477
477
  // Mount order is the design, stated once here. bwrap applies mounts in
478
478
  // argument order, so a later mount lands on top of an earlier one:
479
- // a. host paths at their own paths, read-only — /usr (+ the /lib64
480
- // symlink), srcDir, and nodePrefix when node isn't under /usr;
479
+ // a. host paths at their own paths, read-only — /usr (+ the /bin /sbin
480
+ // /lib /lib64 links), srcDir, and nodePrefix when node isn't under /usr;
481
481
  // b. then everything the walk creates — the overlay over <merged>,
482
482
  // and the output folders.
483
483
  // A host bind placed after the overlay would hide it whenever the
@@ -490,7 +490,7 @@ function bwrapWalk({ lower, upper, work, ignore, scratch, stageDir = null, upper
490
490
  // `/` is correct, merely exposing the host read-only to our own walker.
491
491
  const res = spawnSync('bwrap',
492
492
  ['--die-with-parent', '--unshare-all', '--new-session',
493
- '--ro-bind', '/usr', '/usr', '--symlink', 'usr/lib64', '/lib64',
493
+ '--ro-bind', '/usr', '/usr', ...usrLinks().args,
494
494
  '--ro-bind', srcDir, srcDir,
495
495
  ...(underUsr ? [] : ['--ro-bind', nodePrefix, nodePrefix]),
496
496
  '--overlay-src', lower, '--overlay', upper, work, merged,
package/src/policy.js CHANGED
@@ -57,12 +57,33 @@ export const emptyMatcher = matcherFrom([]);
57
57
  export function buildTools(labelTools = {}, localLlm = []) {
58
58
  /** @type {Record<string, any>} */
59
59
  const models = {};
60
+ for (const k of modelKeys(localLlm)) models[k] = 'r';
61
+ return { ...TOOLS, ...models, ...labelTools };
62
+ }
63
+
64
+ /** @param {string[]} localLlm @returns {Set<string>} every model endpoint's tool key */
65
+ function modelKeys(localLlm) {
66
+ const keys = new Set();
60
67
  const add = (scheme, host, paths) => {
61
- for (const p of paths) models[emptyMatcher.match('POST', `${scheme}://${host}${p}`).key] = 'r';
68
+ for (const p of paths) keys.add(emptyMatcher.match('POST', `${scheme}://${host}${p}`).key);
62
69
  };
63
70
  for (const [host, paths] of Object.entries(MODEL_PATHS)) add('https', host, paths);
64
71
  for (const hp of localLlm) add('http', hp, LOCAL_LLM_PATHS);
65
- return { ...TOOLS, ...models, ...labelTools };
72
+ return keys;
73
+ }
74
+
75
+ /**
76
+ * The tool keys that are model calls (they skip the card floor). A label
77
+ * tool that shares a key wins in `buildTools`, so it is not a model here.
78
+ *
79
+ * @param {Record<string, any>} [labelTools] the label files' gate-file tools
80
+ * @param {string[]} [localLlm] `host:port` pairs of local model servers
81
+ * @returns {Set<string>} model tool keys
82
+ */
83
+ export function modelTools(labelTools = {}, localLlm = []) {
84
+ const keys = modelKeys(localLlm);
85
+ for (const k of Object.keys(labelTools)) keys.delete(k);
86
+ return keys;
66
87
  }
67
88
 
68
89
  /**
package/src/prompt.js ADDED
@@ -0,0 +1,118 @@
1
+ // prompt.js — the same-terminal question for `sbx run`. Turns an ask record
2
+ // into a plain-language question on `output` and reads one answer line from
3
+ // `input`. It never writes answer files itself: it calls `answer(id,
4
+ // decision, reason)`, which the CLI binds to its one answer writer.
5
+ //
6
+ // Stale vs fresh: a line is an answer only if it arrives while a question is
7
+ // open, and it answers THAT question's id. Input that arrives with no
8
+ // question open is dropped (so a `y` typed during h1 never approves h2), and
9
+ // once a hold is decided elsewhere nothing is written for it.
10
+ import { safe } from './runtime.js';
11
+
12
+ const BODY_CHARS = 200;
13
+ const EOL = /\r\n|\r|\n/;
14
+ const YES = new Set(['y', 'yes']);
15
+
16
+ /** @typedef {{ id: string, agent?: string, method: string, url: string, rule: string, letter: string, bodyPreview?: string, expiresAt?: string|null }} AskRecord */
17
+
18
+ /**
19
+ * Plain-language lines for one ask record. Every agent-controlled byte goes
20
+ * through `safe()`.
21
+ *
22
+ * @param {AskRecord} ask the parked request
23
+ * @param {number} [now] clock for the countdown, injectable
24
+ * @returns {string[]} the question, one string per line
25
+ */
26
+ export function questionLines(ask, now = Date.now()) {
27
+ const method = safe(ask.method).toUpperCase();
28
+ let host;
29
+ try { host = safe(new URL(ask.url).host); } catch { host = safe(ask.url); }
30
+ const verb = method === 'POST' ? 'SEND data to'
31
+ : method === 'PUT' || method === 'PATCH' ? 'CHANGE data on'
32
+ : method === 'DELETE' ? 'DELETE data on'
33
+ : `make a ${method} request to`;
34
+ const rule = safe(ask.rule);
35
+ const why = rule === 'flags.cardLike' ? 'it contains what looks like a card number'
36
+ : rule === 'flags.paymentPath' ? 'the address looks like a payment'
37
+ : ask.letter === 'w' ? 'a change (reversible: the vendor says it can be undone)'
38
+ : ask.letter === 'x' ? "a change barebox can't undo"
39
+ : rule;
40
+ const left = ask.expiresAt ? Math.max(0, Math.round((Date.parse(ask.expiresAt) - now) / 1000)) : null;
41
+ const lines = [
42
+ `⏸ ${safe(ask.agent) || 'agent'} wants to ${verb} ${host}`,
43
+ ` Why: ${why}`,
44
+ ` URL: ${method} ${safe(ask.url)}`,
45
+ ];
46
+ const body = safe(ask.bodyPreview).slice(0, BODY_CHARS);
47
+ if (body) lines.push(` Data: ${body}`);
48
+ lines.push(` Allow? [y/N] (${safe(ask.id)})${left === null || Number.isNaN(left) ? '' : ` — no answer in ${left} s means No`}`);
49
+ return lines;
50
+ }
51
+
52
+ /**
53
+ * The terminal prompt. One question open at a time. `ask()` opens a question
54
+ * and returns true, or returns false when one is already open (or the prompt
55
+ * is closed) so the caller prints the plain `ask` line instead; `decided()`
56
+ * closes the question when the hold ended some other way, `close()` releases
57
+ * `input`.
58
+ *
59
+ * @param {{ input: import('node:stream').Readable, output: { write: (s: string) => unknown }, answer: (id: string, decision: 'allow'|'deny', reason?: string) => boolean|void }} opts streams and the answer writer
60
+ * @returns {{ ask: (ask: AskRecord) => boolean, decided: (e: { id: string, decision: string, reason?: string }) => void, close: () => void }} the prompt
61
+ */
62
+ export function createTerminalPrompt({ input, output, answer }) {
63
+ /** @type {AskRecord|null} */
64
+ let open = null;
65
+ let buf = '';
66
+ let closed = false;
67
+ const say = (/** @type {string} */ s) => { output.write(`${s}\n`); };
68
+
69
+ const onLine = (/** @type {string} */ line) => {
70
+ if (!open) return; // unreachable at runtime (onData checks); narrows the type for tsc
71
+ const { id } = open;
72
+ open = null; // closed before the write: one answer per question
73
+ const yes = YES.has(line.trim().toLowerCase());
74
+ try {
75
+ const written = answer(id, yes ? 'allow' : 'deny', yes ? undefined : 'denied at the terminal') !== false;
76
+ say(!written ? 'answered elsewhere' : yes ? '✓ allowed' : '✗ denied');
77
+ } catch {
78
+ // The hold ended (or the runtime went) before this write; the run goes on.
79
+ }
80
+ };
81
+
82
+ const onData = (/** @type {string|Buffer} */ chunk) => {
83
+ if (!open) return;
84
+ buf += String(chunk);
85
+ for (let m = EOL.exec(buf); m && open; m = EOL.exec(buf)) {
86
+ const line = buf.slice(0, m.index);
87
+ buf = buf.slice(m.index + m[0].length);
88
+ onLine(line);
89
+ }
90
+ };
91
+
92
+ input.setEncoding?.('utf8');
93
+ input.on('data', onData);
94
+
95
+ return {
96
+ ask(ask) {
97
+ if (closed || open) return false;
98
+ open = ask;
99
+ buf = ''; // a half-typed line from before the question is stale
100
+ for (const l of questionLines(open)) say(l);
101
+ return true;
102
+ },
103
+ decided(e) {
104
+ if (open?.id !== e.id) return;
105
+ open = null; // closed before anything else: no answer can follow
106
+ const why = safe(e.reason);
107
+ say(why === 'hold timeout' ? `timed out: ${safe(e.decision)}`
108
+ : why === 'client gone' || why === 'proxy closing' ? `agent gone: ${safe(e.decision)}`
109
+ : `answered elsewhere: ${safe(e.decision)}${why ? ` (${why})` : ''}`);
110
+ },
111
+ close() {
112
+ closed = true;
113
+ open = null;
114
+ input.removeListener('data', onData);
115
+ input.pause();
116
+ },
117
+ };
118
+ }
package/src/proxy.js CHANGED
@@ -21,9 +21,9 @@ import { ensureCA, certFor, HOST_RE } from './certs.js';
21
21
  import { createCardScanner } from './cardscan.js';
22
22
  import { ASK_BODY_LIMIT, DEFAULT_HOLD_MAX_BODY, bodyPreview, createHolds } from './holds.js';
23
23
  import { claimRuntime, ensurePrivateDir, runtimePaths } from './runtime.js';
24
- import { paymentPath, toolFor, buildTools, emptyMatcher } from './policy.js';
24
+ import { paymentPath, toolFor, buildTools, modelTools, emptyMatcher } from './policy.js';
25
25
  import { checkUpstream } from './wall.js';
26
- import { findPlaceholders, applySecrets } from './secrets.js';
26
+ import { findPlaceholders, urlPlaceholders, applySecrets } from './secrets.js';
27
27
  import { Gate } from 'bareguard';
28
28
 
29
29
  const AGENT = Symbol('agent');
@@ -37,6 +37,8 @@ const WORK_BODY_LIMIT = 65536;
37
37
  // Small teams: one proxy serves at most this many agents (the TCP door's
38
38
  // 'tcp' agent is not counted); more agents means another proxy.
39
39
  const MAX_AGENTS = 40;
40
+ // Agents that browse many hosts must not grow the proxy without limit: one TLS context per host, at most this many.
41
+ const MAX_MITM_CONTEXTS = 256;
40
42
  const EMPTY = Buffer.alloc(0);
41
43
  const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
42
44
  'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade']);
@@ -137,6 +139,7 @@ export function createProxy(opts) {
137
139
  // One tools table and one matcher per runtime, shared by every gate.
138
140
  const matcher = labels?.matcher ?? emptyMatcher;
139
141
  const tools = buildTools(labels?.tools, [...allowLocal]);
142
+ const models = modelTools(labels?.tools, [...allowLocal]);
140
143
  if (!logFile) throw new Error('createProxy: logFile is required');
141
144
  if (typeof runtime !== 'string' || !runtime) throw new Error('createProxy: runtime is required');
142
145
  // One live proxy per runtime, enforced here: claimed before the hold
@@ -251,6 +254,10 @@ export function createProxy(opts) {
251
254
  /** @type {Set<import('node:http').ClientRequest>} */
252
255
  const upstreams = new Set();
253
256
  const agentServers = new Map();
257
+ // host -> the MITM SecureContext, built once from the minted cert. Certs are valid 825 days and never
258
+ // re-minted while their files exist, so an entry cannot go stale within this proxy's life.
259
+ /** @type {Map<string, import('node:tls').SecureContext>} */
260
+ const mitmContexts = new Map();
254
261
  /** @type {import('node:net').Server|null} */
255
262
  let tcp = null;
256
263
  let closed = false;
@@ -685,6 +692,15 @@ export function createProxy(opts) {
685
692
  denyRes(cres, 403, 'denied: secret.scheme');
686
693
  return;
687
694
  }
695
+ // Keys are swapped in headers only: a placeholder in the URL is refused,
696
+ // not sent as a literal that the API would answer 401 for no visible reason.
697
+ const inUrl = secrets.length ? urlPlaceholders(url.pathname + url.search, secrets) : [];
698
+ if (inUrl.length) {
699
+ for (const name of inUrl) log({ ev: 'secret', agent, rid, name, host: url.hostname, swapped: false });
700
+ try { creq.resume(); } catch {}
701
+ denyRes(cres, 403, 'denied: secret.url');
702
+ return;
703
+ }
688
704
  /** The headers to forward: the real values in, one audit line per swap. @param {Record<string, string | string[] | undefined>} headers */
689
705
  const withSecrets = (headers) => {
690
706
  if (!found.length) return headers;
@@ -731,14 +747,16 @@ export function createProxy(opts) {
731
747
  const ctx = { agent, method, url: urlStr, headers: { ...creq.headers }, creq, cres, tee,
732
748
  hasBody, chunks: [], over: false, freeWork, asked: false, status: null, heldId: null,
733
749
  endAsk: null };
750
+ // A model call is never card-scanned (user decision, Nov 2); the floor keeps every other request.
751
+ const tool = toolFor(matcher, tools, method, urlStr);
734
752
  let cardLike = false;
735
753
  if (hasBody) {
736
754
  if (await readWorkBody(ctx)) return;
737
755
  // Past 64 KB the body streams on unscanned (known gap).
738
- if (!ctx.over) cardLike = createCardScanner().push(Buffer.concat(ctx.chunks));
756
+ if (!ctx.over && !models.has(tool)) cardLike = createCardScanner().push(Buffer.concat(ctx.chunks));
739
757
  }
740
758
  // The body never goes in the action: bareguard writes the action to its audit file.
741
- const action = { type: 'net', tool: toolFor(matcher, tools, method, urlStr), url: urlStr, method, agent,
759
+ const action = { type: 'net', tool, url: urlStr, method, agent,
742
760
  cardLike, paymentPath: paymentPath(urlStr), rid };
743
761
  inflightCtx.set(rid, ctx);
744
762
  const g = await gateOf(agent);
@@ -898,6 +916,9 @@ export function createProxy(opts) {
898
916
  sock.removeListener('data', onData);
899
917
  sock.setTimeout(0); // the http.Server owns idle from here
900
918
  if (method === 'CONNECT') {
919
+ // Whoever removes the last data listener pauses: a flowing socket with no
920
+ // listener drops what arrives (a hello sent before the 200) and what is pushed back.
921
+ sock.pause();
901
922
  handleConnect(sock, target, buf.subarray(i + 4), agent);
902
923
  } else {
903
924
  // Plain HTTP (absolute- or origin-form): same parser, same handler.
@@ -924,18 +945,47 @@ export function createProxy(opts) {
924
945
  denyRaw(sock, 403, verdict.reason);
925
946
  return;
926
947
  }
927
- let creds;
928
- try {
929
- creds = await certFor(certDir, host);
930
- } catch (e) {
931
- denyRaw(sock, 502, `no cert for ${host}: ${e.message}`);
932
- return;
933
- }
934
948
  if (closed || sock.destroyed) return;
935
949
  try { sock.write('HTTP/1.1 200 Connection established\r\n\r\n'); }
936
950
  catch { return; }
937
- if (rest.length) sock.unshift(rest);
938
- const st = new tls.TLSSocket(sock, { isServer: true, key: creds.key, cert: creds.cert });
951
+ // One reader of the first byte: 0x16 is a TLS handshake (decrypt it);
952
+ // anything else is plain HTTP inside the tunnel (Node's fetch tunnels
953
+ // http:// URLs too) and goes to the server as it is, as `admit` does.
954
+ let first = rest;
955
+ if (!first.length) {
956
+ sock.setTimeout(clientIdleMs, () => sock.destroy());
957
+ first = await new Promise((resolve) => {
958
+ const done = (c) => { sock.off('data', done); sock.off('close', gone); sock.pause(); resolve(c); };
959
+ const gone = () => done(Buffer.alloc(0));
960
+ sock.on('data', done);
961
+ sock.on('close', gone);
962
+ sock.resume(); // paused by admit
963
+ });
964
+ sock.setTimeout(0);
965
+ if (!first.length || closed || sock.destroyed) return;
966
+ }
967
+ sock.unshift(first); // paused: admit paused it, and `done` pauses again
968
+ if (first[0] !== 0x16) {
969
+ sock.resume(); // the http server only adds a data listener
970
+ server.emit('connection', sock);
971
+ return;
972
+ }
973
+ // The cert is minted only for a TLS tunnel. The 200 is already sent, so a
974
+ // failure cannot answer 502: it is logged as the deny it would have been.
975
+ let secureContext = mitmContexts.get(host);
976
+ if (!secureContext) {
977
+ try {
978
+ secureContext = tls.createSecureContext(await certFor(certDir, host));
979
+ } catch (e) {
980
+ log({ ev: 'deny', agent: agentOf(sock), code: 502, note: `no cert for ${host}: ${e.message}` });
981
+ sock.destroy();
982
+ return;
983
+ }
984
+ if (!mitmContexts.has(host) && mitmContexts.size >= MAX_MITM_CONTEXTS) mitmContexts.delete(mitmContexts.keys().next().value);
985
+ mitmContexts.set(host, secureContext);
986
+ }
987
+ if (closed || sock.destroyed) return;
988
+ const st = new tls.TLSSocket(sock, { isServer: true, secureContext });
939
989
  st[AGENT] = agent;
940
990
  st[SECURE] = true;
941
991
  clients.add(st);
package/src/runtime.js CHANGED
@@ -67,6 +67,49 @@ export function isInside(base, p) {
67
67
  return realP.startsWith(prefix);
68
68
  }
69
69
 
70
+ /**
71
+ * Where the host's node sits and what of it to bind so it runs inside the sandbox. An exec in a
72
+ * `bin/` dir (nvm, fnm, toolcache, distro) has its install one dir up, where npm and the global
73
+ * CLIs live; any other layout is its own dir. Never `/`, `$HOME` or an ancestor of it: binding
74
+ * that would hand the sandbox the whole host or every user's home, so it is `refused` and
75
+ * neither bound nor put on PATH.
76
+ *
77
+ * @param {string} execPath absolute path of the node executable
78
+ * @param {string} home the sandbox $HOME
79
+ * @param {string} [proj] the project dir, already visible inside
80
+ * @returns {{dir: string, bin: string|null, bind: string|null, refused: string|null}} `dir` the install folder; `bin` the PATH entry (null when refused); `bind` the dir to bind read-only (null when refused or already under `/usr`, `$HOME` or the project); `refused` a short reason or null
81
+ */
82
+ export function hostNode(execPath, home, proj) {
83
+ const bin = path.dirname(execPath);
84
+ const dir = path.basename(bin) === 'bin' ? path.dirname(bin) : bin;
85
+ if (isInside(dir, home)) { // `/` is inside-of-everything: it lands here too
86
+ return { dir, bin: null, bind: null, refused: 'it contains $HOME or is /' };
87
+ }
88
+ const visible = ['/usr', home, ...(proj ? [proj] : [])].some((r) => isInside(r, dir));
89
+ return { dir, bin, bind: visible ? null : dir, refused: null };
90
+ }
91
+
92
+ /**
93
+ * The host's top-level `/bin`, `/sbin`, `/lib` and `/lib64`, as bwrap args that mirror them
94
+ * inside the sandbox. On a merged-/usr host they are symlinks into `/usr` (`/bin -> usr/bin`),
95
+ * recreated as the same links; a real directory (a non-merged distro) is bound read-only;
96
+ * a missing path is skipped. Without them `#!/bin/sh` scripts and Node's `exec` fail.
97
+ *
98
+ * @param {string} [prefix] prepended to each path when looking at the host (tests point it at a fake root); the inside paths are always `/bin` etc.
99
+ * @returns {{args: string[], bound: string[]}} `args` the bwrap args, to go right after the `/usr` bind; `bound` the real directories bound (they are sandbox roots, so the masks apply under them)
100
+ */
101
+ export function usrLinks(prefix = '') {
102
+ const args = [];
103
+ const bound = [];
104
+ for (const p of ['/bin', '/sbin', '/lib', '/lib64']) {
105
+ let st;
106
+ try { st = fs.lstatSync(prefix + p); } catch { continue; }
107
+ if (st.isSymbolicLink()) args.push('--symlink', fs.readlinkSync(prefix + p), p);
108
+ else if (st.isDirectory()) { args.push('--ro-bind', prefix + p, p); bound.push(p); }
109
+ }
110
+ return { args, bound };
111
+ }
112
+
70
113
  /**
71
114
  * Create a short-lived runtime dir: a short `sbx-` temp dir, keeping unix
72
115
  * socket paths under the ~108-char limit.
@@ -77,6 +120,41 @@ export function createRuntime() {
77
120
  return fs.mkdtempSync(path.join(os.tmpdir(), 'sbx-'));
78
121
  }
79
122
 
123
+ /**
124
+ * The runtime dir of a named sandbox (`sbx run --name <n>`): the name replaces
125
+ * a `SBX_RUNTIME` path for every command. `$XDG_RUNTIME_DIR/barebox/<n>` when
126
+ * that variable names an existing dir you own, else
127
+ * `<tmpdir>/sbx-<uid>/<n>`. The one function that maps a name to a dir.
128
+ *
129
+ * @param {string} name sandbox name (the agent-name rules)
130
+ * @param {NodeJS.ProcessEnv} [env] environment to read `XDG_RUNTIME_DIR` from
131
+ * @param {{ create?: boolean }} [opts] `create`: make the parent and runtime dirs owner-only (0700); off, nothing is touched
132
+ * @returns {string} the runtime dir
133
+ * @throws {Error} on a bad name, a socket path over the 107-byte cap, or a foreign-owned parent
134
+ */
135
+ export function namedRuntime(name, env = process.env, { create = false } = {}) {
136
+ assertAgentName(name);
137
+ const me = /** @type {number} */ (process.getuid?.());
138
+ const xdg = env.XDG_RUNTIME_DIR;
139
+ let usable = false;
140
+ try {
141
+ usable = !!xdg && path.isAbsolute(xdg) && fs.statSync(xdg).isDirectory() && fs.statSync(xdg).uid === me;
142
+ } catch {}
143
+ const parent = usable
144
+ ? path.join(/** @type {string} */ (xdg), 'barebox')
145
+ : path.join(os.tmpdir(), `sbx-${me}`);
146
+ const runtime = path.join(parent, name);
147
+ const sock = path.join(runtime, 'socks', `${name}.sock`);
148
+ if (sock.length > MAX_SOCK_PATH) {
149
+ throw new Error(`sandbox name ${name} makes the socket path too long (${sock.length} > ${MAX_SOCK_PATH}): use a shorter name or a shorter TMPDIR`);
150
+ }
151
+ if (create) {
152
+ ensurePrivateDir(parent);
153
+ ensurePrivateDir(runtime);
154
+ }
155
+ return runtime;
156
+ }
157
+
80
158
  /**
81
159
  * Create a temp dir inside the runtime tree: `mkdtemp` is a runtime-layout
82
160
  * writer, so it lives here, not in `overlay.js`. Used for the merged-view
package/src/secrets.js CHANGED
@@ -66,6 +66,14 @@ function swapIn(v, s) {
66
66
  return v;
67
67
  }
68
68
 
69
+ /**
70
+ * Which secrets' placeholders sit in a request URL (path and query). Keys are swapped in headers only.
71
+ * @param {string} pathAndQuery @param {Secret[]} secrets @returns {string[]} the secrets' names
72
+ */
73
+ export function urlPlaceholders(pathAndQuery, secrets) {
74
+ return secrets.filter((s) => pathAndQuery.includes(s.placeholder)).map((s) => s.name);
75
+ }
76
+
69
77
  /**
70
78
  * Which placeholders a request carries, and whether each is headed for a host its secret is bound to.
71
79
  * Each header value is searched as a substring and, for `Basic <base64>`, decoded.