barebox 0.3.0 → 0.5.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/labels.js ADDED
@@ -0,0 +1,88 @@
1
+ // labels.js — the only reader of rwxmap label folders (`labels` in the config).
2
+ // Per vendor the rwxmap CLI writes `<v>.rwxmap.json` (the gate file: the
3
+ // letters barebox uses) and `<v>.rwxmap.review.json` (the sidecar the matcher
4
+ // reads). Letters come from the gate file only, never from the sidecar.
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import { matcherFrom } from 'rwxmap/match';
9
+
10
+ const REVIEW = '.rwxmap.review.json';
11
+ const GATE = '.rwxmap.json';
12
+
13
+ /** @param {string} file @returns {any} parsed JSON, errors naming the file */
14
+ function readJson(file) {
15
+ try {
16
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
17
+ } catch (e) {
18
+ throw new Error(`${file}: ${e instanceof Error ? e.message : String(e)}`);
19
+ }
20
+ }
21
+
22
+ /**
23
+ * Load every label folder: the matcher for request keys and the tools table
24
+ * (key to `{ letter, marker }`) from the gate files. Call once at startup so a
25
+ * bad file fails the run before any agent starts.
26
+ *
27
+ * @param {object} cfg
28
+ * @param {string[]} [cfg.labels] folders the rwxmap CLI wrote (`~/` means `$HOME`)
29
+ * @param {Record<string, string[]>} [cfg.tenants] vendor to tenant base URLs, replacing the sidecar's `servers`
30
+ * @param {NodeJS.ProcessEnv} [env] environment for `$HOME`
31
+ * @returns {{ matcher: ReturnType<typeof matcherFrom>, tools: Record<string, any>, dirs: string[] }} `dirs` are the absolute folders (the launcher masks them)
32
+ * @throws {Error} naming the file or folder on a missing gate or review file, a duplicate key, an unknown tenant vendor or a bad sidecar
33
+ */
34
+ export function loadLabels({ labels = [], tenants = {} }, env = process.env) {
35
+ const home = env.HOME || os.homedir();
36
+ /** @type {Record<string, any>} */
37
+ const tools = {};
38
+ /** @type {Record<string, string>} key to the gate file that defined it */
39
+ const origin = {};
40
+ /** @type {any[]} */
41
+ const sidecars = [];
42
+ /** @type {Map<string, string>} sidecar vendor to review file path */
43
+ const vendors = new Map();
44
+ /** @type {string[]} */
45
+ const dirs = [];
46
+ for (const raw of labels) {
47
+ const dir = path.resolve(raw === '~' ? home : raw.startsWith('~/') ? path.join(home, raw.slice(2)) : raw);
48
+ dirs.push(dir);
49
+ let names;
50
+ try {
51
+ names = fs.readdirSync(dir).filter((n) => n.endsWith(REVIEW)).sort();
52
+ } catch (e) {
53
+ throw new Error(`labels folder ${dir}: ${e instanceof Error ? e.message : String(e)}`);
54
+ }
55
+ if (!names.length) throw new Error(`labels folder ${dir}: no *${REVIEW} file`);
56
+ for (const n of names) {
57
+ const review = path.join(dir, n);
58
+ const gateFile = path.join(dir, n.slice(0, -REVIEW.length) + GATE);
59
+ if (!fs.existsSync(gateFile)) throw new Error(`${review}: missing its gate file ${gateFile}`);
60
+ const side = readJson(review);
61
+ const gate = readJson(gateFile);
62
+ const t = gate?.bareguard?.tools;
63
+ if (t === null || typeof t !== 'object' || Array.isArray(t)) {
64
+ throw new Error(`${gateFile}: no bareguard.tools object`);
65
+ }
66
+ for (const [k, v] of Object.entries(t)) {
67
+ if (Object.hasOwn(tools, k)) throw new Error(`${gateFile}: key "${k}" is also defined in ${origin[k]}`);
68
+ tools[k] = v;
69
+ origin[k] = gateFile;
70
+ }
71
+ const tenant = side?.vendor !== undefined ? tenants[side.vendor] : undefined;
72
+ if (tenant) side.servers = tenant;
73
+ if (side?.vendor !== undefined) vendors.set(side.vendor, review);
74
+ sidecars.push({ side, review });
75
+ }
76
+ }
77
+ for (const v of Object.keys(tenants)) {
78
+ if (!vendors.has(v)) throw new Error(`tenants: vendor "${v}" is in no labels folder`);
79
+ }
80
+ let matcher;
81
+ try {
82
+ matcher = matcherFrom(sidecars.map((s) => s.side));
83
+ } catch (e) {
84
+ // matcherFrom does not say which file; name the files (pre-0.8.0 message passes through).
85
+ throw new Error(`${sidecars.map((s) => s.review).join(', ')}: ${e instanceof Error ? e.message : String(e)}`);
86
+ }
87
+ return { matcher, tools, dirs };
88
+ }
package/src/launcher.js CHANGED
@@ -7,6 +7,7 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, statSync, writeFileSync
7
7
  import { join, relative, dirname } from 'node:path';
8
8
  import { assertAgentName, isInside, realPathOf, runtimePaths } from './runtime.js';
9
9
  import { assertOverlaySupport, setupOverlay } from './overlay.js';
10
+ import { configPath } from './config.js';
10
11
 
11
12
  // Locked drawers (relative to $HOME): masked wherever they exist — a folder
12
13
  // with an empty tmpfs, a file with /dev/null (bwrap cannot mount a tmpfs on
@@ -53,12 +54,14 @@ const LOCKED_PATHS = [
53
54
  * spellings; a target outside `$HOME` and the project is not bound into the
54
55
  * sandbox at all, so there is nothing to mask.
55
56
  *
56
- * @param {string} abs the locked path under `$HOME`
57
+ * @param {string} abs the locked path (under `$HOME` or the project to matter)
57
58
  * @param {string} home `$HOME`
58
59
  * @param {string} proj project dir
59
60
  * @returns {string[]} `--tmpfs <dir>` or `--dev-bind /dev/null <file>`, or `[]`
60
61
  */
61
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 [];
62
65
  let target = abs;
63
66
  let st;
64
67
  try {
@@ -131,6 +134,7 @@ export function buildCaBundle(runtime, caFile) {
131
134
  * @param {object} [opts.extraEnv] extra environment entries for the inside
132
135
  * @param {string|null} [opts.socket] agent socket path, as returned by `proxy.addAgent` (default `<runtime>/socks/<agent>.sock`; the two must agree)
133
136
  * @param {string|null} [opts.caFile] barebox CA cert path (from `proxy.caFile`); when set, the sandbox trusts it for HTTPS alongside the system roots
137
+ * @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)
134
138
  * @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)`
135
139
  * @param {string[]} [opts.overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
136
140
  * @returns {import('node:child_process').ChildProcess} the bwrap child (stdio piped); `close` gives its exit code
@@ -142,7 +146,7 @@ export function buildCaBundle(runtime, caFile) {
142
146
  * await new Promise((r) => child.on("close", r)); // child.exitCode === 0
143
147
  */
144
148
  export function launch({ runtime, agent, proj, command, proxyPort = 3128,
145
- extraEnv = {}, socket = null, caFile = null, overlay = false, overlayIgnore }) {
149
+ extraEnv = {}, socket = null, caFile = null, overlay = false, overlayIgnore, maskDirs = [] }) {
146
150
  for (const [k, v] of Object.entries({ runtime, agent, proj })) {
147
151
  if (typeof v !== 'string' || !v) throw new Error(`launch: ${k} must be a non-empty string`);
148
152
  }
@@ -198,6 +202,11 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
198
202
  // or a project that contains one of these paths (a project that IS $HOME,
199
203
  // or holds its own `.ssh`) would leak the real drawer through the overlay.
200
204
  for (const p of LOCKED_PATHS) args.push(...lockMask(`${home}/${p}`, home, proj));
205
+ // barebox's own config: settings the agent must neither read nor edit.
206
+ // Masked wherever it resolves (XDG_CONFIG_HOME may move it).
207
+ args.push(...lockMask(dirname(configPath(process.env)), home, proj));
208
+ // The label folders (the letters live there) get the same mask.
209
+ for (const d of maskDirs) args.push(...lockMask(d, home, proj));
201
210
  // The runtime tree holds the file-checkpoint dirs (`asks/`, `answers/`
202
211
  // — the approve/deny capability) and every agent's socket (identity). A
203
212
  // read-only bind does NOT stop connect(2) to a unix socket, so wherever
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: createHash('sha256').update(readFileSync(abs)).digest('hex'),
179
+ hash: hashFile(abs),
128
180
  }
129
181
  : { type, mode: st.mode & 0o7777 };
130
182
  }
package/src/policy.js ADDED
@@ -0,0 +1,138 @@
1
+ // policy.js — the one owner of what each mode lets through.
2
+ //
3
+ // Every request becomes one bareguard action and one `gate.check()`. The
4
+ // mode only chooses the agent's letters and which unheld letters ask:
5
+ // ask -> holds "r--", asks for w and x
6
+ // auto -> holds "rw-", asks for x
7
+ // trust -> holds "rwx", asks for nothing
8
+ // A request is one tool: `<vendor>.<operationId>` when a label file documents
9
+ // it (letters come from the gate file), `<host>.POST <path>` for a known model
10
+ // endpoint (`r`), else `http.<METHOD>`: GET and HEAD are `r`; POST, PUT, PATCH
11
+ // and DELETE are `x`. A tool that is not listed is denied (`rwx.unlisted`) in
12
+ // every mode. The card/payment floor
13
+ // is `flags`: it asks in every mode, trust included.
14
+ import { Gate } from 'bareguard';
15
+ import { matcherFrom } from 'rwxmap/match';
16
+
17
+ /** The mode names, in the order the CLI and config list them. */
18
+ export const MODES = ['ask', 'auto', 'trust'];
19
+
20
+ const MODE_RULES = {
21
+ ask: { letters: 'r--', askUnheld: ['w', 'x'] },
22
+ auto: { letters: 'rw-', askUnheld: ['x'] },
23
+ trust: { letters: 'rwx', askUnheld: [] },
24
+ };
25
+
26
+ // One map for every gate (the grant comes from each gate's letters, never
27
+ // from the action).
28
+ const TOOLS = {
29
+ 'http.GET': 'r',
30
+ 'http.HEAD': 'r',
31
+ 'http.POST': 'x',
32
+ 'http.PUT': 'x',
33
+ 'http.PATCH': 'x',
34
+ 'http.DELETE': 'x',
35
+ };
36
+
37
+ /** Model-call endpoints per host (`host[:port]`); each is `POST` and reads (`r`). */
38
+ const MODEL_PATHS = {
39
+ 'api.anthropic.com': ['/v1/messages', '/v1/messages/count_tokens'],
40
+ 'api.openai.com': ['/v1/chat/completions', '/v1/responses', '/v1/embeddings'],
41
+ };
42
+ const LOCAL_LLM_PATHS = ['/api/chat', '/api/generate', '/api/embed',
43
+ '/v1/chat/completions', '/v1/completions'];
44
+
45
+ /** The matcher used when no label files are loaded: every request is request-only. */
46
+ export const emptyMatcher = matcherFrom([]);
47
+
48
+ /**
49
+ * The one tools table of a runtime: the `http.*` tools, the model endpoints
50
+ * (`r`) and the label tools. Model keys come from `matcher.match()` itself so
51
+ * there is no second key builder.
52
+ *
53
+ * @param {Record<string, any>} [labelTools] the label files' gate-file tools (`{ key: { letter, marker } }`)
54
+ * @param {string[]} [localLlm] `host:port` pairs of local model servers
55
+ * @returns {Record<string, any>} tool name to letter
56
+ */
57
+ export function buildTools(labelTools = {}, localLlm = []) {
58
+ /** @type {Record<string, any>} */
59
+ const models = {};
60
+ const add = (scheme, host, paths) => {
61
+ for (const p of paths) models[emptyMatcher.match('POST', `${scheme}://${host}${p}`).key] = 'r';
62
+ };
63
+ for (const [host, paths] of Object.entries(MODEL_PATHS)) add('https', host, paths);
64
+ for (const hp of localLlm) add('http', hp, LOCAL_LLM_PATHS);
65
+ return { ...TOOLS, ...models, ...labelTools };
66
+ }
67
+
68
+ /**
69
+ * The tool name for one request. A spec key (a label file documents it) is
70
+ * used as is, even if the gate file lacks it (then the gate denies it:
71
+ * fail closed). A request-only key is used only when it is a known model
72
+ * endpoint; everything else is `http.<METHOD>`. Never the matcher's letter.
73
+ *
74
+ * @param {{ match: (method: string, url: string) => { key: string, source: string } }} matcher
75
+ * @param {Record<string, any>} tools the runtime's tools table
76
+ * @param {string} method HTTP method
77
+ * @param {string} url full request URL
78
+ * @returns {string} the tool name
79
+ */
80
+ export function toolFor(matcher, tools, method, url) {
81
+ try {
82
+ const r = matcher.match(method, url);
83
+ if (r.source === 'spec' || Object.hasOwn(tools, r.key)) return r.key;
84
+ } catch { /* not an http(s) URL: fall through */ }
85
+ return `http.${method}`;
86
+ }
87
+
88
+ /** @type {Record<string, Record<string, 'ask' | 'deny'>>} */
89
+ const FLAGS = { cardLike: { true: 'ask' }, paymentPath: { true: 'ask' } };
90
+
91
+ /** Payment-destination path fragments: the URL-visible half of the floor (PRD section 2). */
92
+ const PAYMENT_PATHS = ['/checkout', '/payment', '/orders', '/purchase'];
93
+
94
+ /**
95
+ * True when the URL's path names a payment destination (the floor's
96
+ * URL-visible half). An unparsable URL is not one.
97
+ *
98
+ * @param {string} url full request URL
99
+ * @returns {boolean} whether the path contains a payment fragment
100
+ */
101
+ export function paymentPath(url) {
102
+ let pathname;
103
+ try {
104
+ pathname = new URL(url).pathname.toLowerCase();
105
+ } catch {
106
+ return false;
107
+ }
108
+ return PAYMENT_PATHS.some((p) => pathname.includes(p));
109
+ }
110
+
111
+ /**
112
+ * Build and initialise one agent's gate.
113
+ *
114
+ * @param {object} opts
115
+ * @param {string} opts.agent agent name (the gate's rwx agent)
116
+ * @param {string} opts.mode `ask` | `auto` | `trust`
117
+ * @param {string} opts.auditPath bareguard audit file (shared by every gate of a runtime)
118
+ * @param {Record<string, any>} [opts.tools] the runtime's tools table (default: the `http.*` tools)
119
+ * @param {(event: any) => Promise<{ decision: 'allow' | 'deny', reason?: string }>} opts.humanChannel resolves every ask
120
+ * @returns {Promise<Gate>} an initialised gate
121
+ */
122
+ export async function gateFor({ agent, mode, auditPath, humanChannel, tools = TOOLS }) {
123
+ if (!MODES.includes(mode)) {
124
+ throw new Error(`policy: mode must be ${MODES.join('|')}, got ${JSON.stringify(mode)}`);
125
+ }
126
+ const { letters, askUnheld } = MODE_RULES[mode];
127
+ const gate = new Gate({
128
+ audit: { path: auditPath },
129
+ rwx: { agent, agents: { [agent]: letters }, tools, askUnheld },
130
+ // The mode letters plus the card/payment floor are the whole policy; bareguard's
131
+ // default word patterns scan the URL and method and would fire before rwx.
132
+ content: { askPatterns: [], denyPatterns: [] },
133
+ flags: FLAGS,
134
+ humanChannel,
135
+ });
136
+ await gate.init();
137
+ return gate;
138
+ }