barebox 0.4.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/CHANGELOG.md +57 -0
- package/README.md +20 -21
- package/barebox.context.md +126 -11
- package/package.json +6 -1
- package/src/cardscan.js +96 -0
- package/src/cli.js +29 -4
- package/src/config.js +96 -0
- package/src/holds.js +76 -48
- package/src/labels.js +88 -0
- package/src/launcher.js +11 -2
- package/src/policy.js +138 -0
- package/src/proxy.js +568 -161
- package/src/run.js +30 -69
- package/src/runtime.js +7 -2
- package/src/wall.js +12 -6
- package/types/cardscan.d.ts +17 -0
- package/types/cli.d.ts +1 -1
- package/types/config.d.ts +41 -0
- package/types/holds.d.ts +25 -46
- package/types/labels.d.ts +21 -0
- package/types/launcher.d.ts +3 -1
- package/types/policy.d.ts +64 -0
- package/types/proxy.d.ts +82 -33
- package/types/run.d.ts +32 -10
- package/types/runtime.d.ts +3 -1
- package/types/wall.d.ts +4 -2
package/src/holds.js
CHANGED
|
@@ -32,12 +32,18 @@
|
|
|
32
32
|
// (the hold-reason string), `letter`, `bodyPreview` + `truncated`,
|
|
33
33
|
// `waitingSec` (0 at park; readers use the file mtime for a live value),
|
|
34
34
|
// `expiresAt` (ISO-8601 UTC string, or null when `timeoutMs: 'never'`).
|
|
35
|
-
// `
|
|
36
|
-
//
|
|
37
|
-
//
|
|
35
|
+
// `rule` and `letter` come from the gate's ask (`rwx.ask`, `flags.cardLike`,
|
|
36
|
+
// ...; the matched rwx letter, `'x'` when the ask names none): the queue only
|
|
37
|
+
// parks what bareguard's `humanChannel` hands it. Headers are excluded from the
|
|
38
38
|
// payload (they carry Authorization secrets); the body preview is capped at
|
|
39
|
-
// ASK_BODY_LIMIT bytes
|
|
40
|
-
// redaction takes over
|
|
39
|
+
// ASK_BODY_LIMIT bytes with card numbers masked (`bodyPreview`) — M3's
|
|
40
|
+
// bareguard `secrets` redaction takes over the rest.
|
|
41
|
+
//
|
|
42
|
+
// A held request's body lives on disk, never whole in memory: the proxy
|
|
43
|
+
// spools it to `<runtime>/held/<id>` and this queue only keeps the preview
|
|
44
|
+
// and byte count. The file ends with the hold: deny, timeout, abandon and
|
|
45
|
+
// close delete it here (`dropBody`); an approve hands it to the proxy, which
|
|
46
|
+
// deletes it once the upstream has read it.
|
|
41
47
|
//
|
|
42
48
|
// Answer payload (`answers/<id>.json`): `{ decision: 'allow' | 'deny',
|
|
43
49
|
// reason? }`. `'approve'` is accepted as an alias of `'allow'`. Writers
|
|
@@ -45,10 +51,25 @@
|
|
|
45
51
|
import fs from 'node:fs';
|
|
46
52
|
import path from 'node:path';
|
|
47
53
|
import { ensurePrivateDir, runtimePaths } from './runtime.js';
|
|
54
|
+
import { maskCards } from './cardscan.js';
|
|
48
55
|
|
|
49
56
|
/** Body preview cap for `asks/<id>.json` (bytes). */
|
|
50
57
|
export const ASK_BODY_LIMIT = 4096;
|
|
51
58
|
|
|
59
|
+
/** Default cap on a held body (bytes): over it the request is denied at the door. */
|
|
60
|
+
export const DEFAULT_HOLD_MAX_BODY = 52428800;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The one body preview, for the ask file: the first
|
|
64
|
+
* ASK_BODY_LIMIT bytes as utf8, with card numbers masked.
|
|
65
|
+
*
|
|
66
|
+
* @param {Buffer} head the body's first bytes (anything past ASK_BODY_LIMIT is ignored)
|
|
67
|
+
* @returns {string} masked preview
|
|
68
|
+
*/
|
|
69
|
+
export function bodyPreview(head) {
|
|
70
|
+
return maskCards(head.subarray(0, ASK_BODY_LIMIT).toString('utf8'));
|
|
71
|
+
}
|
|
72
|
+
|
|
52
73
|
/** Default answer poll interval in ms (PRD Q9). */
|
|
53
74
|
export const DEFAULT_POLL_MS = 250;
|
|
54
75
|
|
|
@@ -57,7 +78,7 @@ const MAX_WAITING_PER_AGENT = 16;
|
|
|
57
78
|
|
|
58
79
|
/**
|
|
59
80
|
* A parked request, as returned by {@link pending}. Plain objects only —
|
|
60
|
-
* the queue itself never leaves this module. No body: returning whole
|
|
81
|
+
* the queue itself never leaves this module. No body: returning whole
|
|
61
82
|
* bodies from a status call is never needed, and the ask payload in
|
|
62
83
|
* `asks/<id>.json` carries the preview.
|
|
63
84
|
*
|
|
@@ -66,7 +87,7 @@ const MAX_WAITING_PER_AGENT = 16;
|
|
|
66
87
|
* @property {string} agent agent name (its socket), never `c<n>`
|
|
67
88
|
* @property {string} method HTTP method
|
|
68
89
|
* @property {string} url full URL
|
|
69
|
-
* @property {string} rule
|
|
90
|
+
* @property {string} rule the gate's ask rule (hold reason)
|
|
70
91
|
* @property {number} waitingSec seconds since the hold parked
|
|
71
92
|
*/
|
|
72
93
|
|
|
@@ -92,9 +113,9 @@ const MAX_WAITING_PER_AGENT = 16;
|
|
|
92
113
|
* @property {string} agent agent name (its socket)
|
|
93
114
|
* @property {string} method HTTP method
|
|
94
115
|
* @property {string} url full URL
|
|
95
|
-
* @property {string} rule
|
|
96
|
-
* @property {string} letter
|
|
97
|
-
* @property {string} bodyPreview request body preview, utf8, capped at ASK_BODY_LIMIT bytes
|
|
116
|
+
* @property {string} rule the gate's ask rule
|
|
117
|
+
* @property {string} letter the matched rwx letter, `'x'` when the ask names none
|
|
118
|
+
* @property {string} bodyPreview request body preview, utf8, capped at ASK_BODY_LIMIT bytes, card numbers masked
|
|
98
119
|
* @property {boolean} truncated true when the body exceeded ASK_BODY_LIMIT
|
|
99
120
|
* @property {number} waitingSec 0 at park; readers use the file mtime for a live value
|
|
100
121
|
* @property {string|null} expiresAt ISO-8601 UTC deadline, or null when `timeoutMs: 'never'`
|
|
@@ -106,13 +127,6 @@ const MAX_WAITING_PER_AGENT = 16;
|
|
|
106
127
|
* @typedef {(ask: AskPayload) => Promise<{ decision: string, reason?: string }>} OnAsk
|
|
107
128
|
*/
|
|
108
129
|
|
|
109
|
-
/**
|
|
110
|
-
* Decide whether a request parks. Return a human-readable reason, or null
|
|
111
|
-
* to forward. M3 plugs the rwxmap + bareguard classifier into this one seam.
|
|
112
|
-
*
|
|
113
|
-
* @typedef {(req: { agent: string, method: string, url: string, headers: Record<string, string | string[] | undefined> }) => string | null} ShouldHold
|
|
114
|
-
*/
|
|
115
|
-
|
|
116
130
|
/**
|
|
117
131
|
* Atomic write: tmp file + rename, so readers never see a partial payload.
|
|
118
132
|
*
|
|
@@ -213,23 +227,19 @@ export function normalizeDecision(input, { approveAlias = false } = {}) {
|
|
|
213
227
|
*
|
|
214
228
|
* @param {object} opts
|
|
215
229
|
* @param {(o: Record<string, unknown>) => void} opts.log audit-log writer
|
|
216
|
-
* @param {ShouldHold} [opts.shouldHold] decision function (default: path-substring `match`)
|
|
217
|
-
* @param {string} [opts.match] path substring that parks a request (default impl when `shouldHold` is absent)
|
|
218
230
|
* @param {number|string} [opts.timeoutMs] hold deadline in ms, or `'never'` (default 120000)
|
|
219
|
-
* @param {number} [opts.maxBody] bodies over this are denied at the door, never queued (default
|
|
231
|
+
* @param {number} [opts.maxBody] bodies over this are denied at the door, never queued (default 52428800)
|
|
220
232
|
* @param {string|null} [opts.runtime] runtime dir; required for the default file checkpoint (writes `asks/`, polls `answers/`)
|
|
221
233
|
* @param {OnAsk|null} [opts.onAsk] ask seam (bareguard `humanChannel` shape); when present no files are involved
|
|
222
234
|
* @param {number} [opts.pollMs] answer poll interval in ms for the default file checkpoint (default 250, PRD Q9)
|
|
223
235
|
* @param {OnEvent|null} [opts.onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon
|
|
224
236
|
* @param {(entry: object) => void} opts.onApprove forward the parked request upstream
|
|
225
237
|
* @param {(entry: object, reason: string) => void} opts.onDeny refuse the parked request
|
|
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 },
|
|
238
|
+
* @returns {{ add: (entry: object) => string|null, dropBody: (id: string) => void, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string) => void }) => { state: 'now'|'queued'|'full', id: string, arrivedAt: number, cancel: () => void }, abandon: (id: string) => void, abandonSocket: (sock: object) => void, pending: () => HeldRequest[], close: () => void }} queue handle
|
|
227
239
|
*/
|
|
228
|
-
export function createHolds({ log,
|
|
229
|
-
maxBody =
|
|
240
|
+
export function createHolds({ log, timeoutMs = 120000,
|
|
241
|
+
maxBody = DEFAULT_HOLD_MAX_BODY, runtime = null, onAsk = null, pollMs = DEFAULT_POLL_MS,
|
|
230
242
|
onEvent = null, onApprove, onDeny }) {
|
|
231
|
-
// The default IS matchPath: one definition of the path-substring rule (see below).
|
|
232
|
-
const decide = shouldHold ?? (match ? matchPath(match) : () => null);
|
|
233
243
|
/** @returns {number|null} */
|
|
234
244
|
const deadlineMs = () => {
|
|
235
245
|
if (timeoutMs === 'never') return null;
|
|
@@ -255,6 +265,13 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
255
265
|
if (paths) {
|
|
256
266
|
ensurePrivateDir(paths.asksDir);
|
|
257
267
|
ensurePrivateDir(paths.answersDir);
|
|
268
|
+
ensurePrivateDir(paths.heldDir);
|
|
269
|
+
// Held bodies of a dead queue are orphans (ids restart at h1).
|
|
270
|
+
try {
|
|
271
|
+
for (const name of fs.readdirSync(paths.heldDir)) {
|
|
272
|
+
try { fs.unlinkSync(path.join(paths.heldDir, name)); } catch {}
|
|
273
|
+
}
|
|
274
|
+
} catch {}
|
|
258
275
|
}
|
|
259
276
|
// A dead queue's leftovers must never decide the next queue's holds
|
|
260
277
|
// (ids restart at h1): clear both folders at start, logging one audit
|
|
@@ -290,7 +307,7 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
290
307
|
* @type {Map<string, { holder: object|null, line: Array<object> }>}
|
|
291
308
|
*/
|
|
292
309
|
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 }>} */
|
|
310
|
+
/** 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, id: string }>} */
|
|
294
311
|
const handleState = new WeakMap();
|
|
295
312
|
|
|
296
313
|
/**
|
|
@@ -357,17 +374,15 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
357
374
|
* @returns {AskPayload}
|
|
358
375
|
*/
|
|
359
376
|
function askPayload(entry, ms, rule) {
|
|
360
|
-
const body = Buffer.isBuffer(entry.body) ? entry.body : Buffer.from(String(entry.body ?? ''));
|
|
361
377
|
return {
|
|
362
378
|
id: entry.id,
|
|
363
379
|
agent: entry.agent,
|
|
364
380
|
method: entry.method,
|
|
365
381
|
url: entry.url,
|
|
366
382
|
rule,
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
truncated: body.length > ASK_BODY_LIMIT,
|
|
383
|
+
letter: entry.letter ?? 'x',
|
|
384
|
+
bodyPreview: entry.preview,
|
|
385
|
+
truncated: entry.bodyBytes > ASK_BODY_LIMIT,
|
|
371
386
|
waitingSec: 0,
|
|
372
387
|
// ISO-8601 UTC (not epoch ms): readable in `sbx pending` and logs.
|
|
373
388
|
expiresAt: ms === null ? null : new Date(entry.t0 + ms).toISOString(),
|
|
@@ -381,6 +396,18 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
381
396
|
} catch {}
|
|
382
397
|
}
|
|
383
398
|
|
|
399
|
+
/**
|
|
400
|
+
* The one deleter of a held body file (the proxy calls it too, after an
|
|
401
|
+
* approved upstream has read it, or when a reservation never parks).
|
|
402
|
+
*
|
|
403
|
+
* @param {string} id hold id
|
|
404
|
+
* @returns {void}
|
|
405
|
+
*/
|
|
406
|
+
function dropBody(id) {
|
|
407
|
+
if (!paths) return;
|
|
408
|
+
try { fs.unlinkSync(paths.heldFile(id)); } catch {}
|
|
409
|
+
}
|
|
410
|
+
|
|
384
411
|
function settle(id, approved, reason) {
|
|
385
412
|
const h = queue.get(id);
|
|
386
413
|
if (!h) return `unknown ${id}`;
|
|
@@ -393,6 +420,7 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
393
420
|
log({ ev: 'decide', id, agent: h.agent, decision, reason: reason || undefined });
|
|
394
421
|
onApprove(h);
|
|
395
422
|
} else {
|
|
423
|
+
dropBody(id);
|
|
396
424
|
log({ ev: 'decide', id, agent: h.agent, decision, reason });
|
|
397
425
|
onDeny(h, reason);
|
|
398
426
|
}
|
|
@@ -488,18 +516,23 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
488
516
|
* parks nothing and returns `null`. Without `slot`, parks exactly as
|
|
489
517
|
* before, without limit.
|
|
490
518
|
*
|
|
519
|
+
* The entry carries the masked `preview` and the full `bodyBytes`, never
|
|
520
|
+
* the body itself (the proxy spooled it to `heldFile(id)`). `finish` is
|
|
521
|
+
* the proxy's resolver for the request's pending ask: the queue never
|
|
522
|
+
* calls it directly, `onApprove` / `onDeny` do.
|
|
523
|
+
*
|
|
491
524
|
* @param {object} entry queue entry
|
|
492
525
|
* @returns {string|null} hold id, or null for a finished slot
|
|
493
526
|
*/
|
|
494
|
-
add({ agent, method, url,
|
|
527
|
+
add({ agent, method, url, preview = '', bodyBytes = 0, sock, note, letter, finish, slot, arrivedAt }) {
|
|
495
528
|
const hst = typeof slot === 'object' && slot !== null ? handleState.get(slot) : undefined;
|
|
496
529
|
const s = slots.get(agent);
|
|
497
530
|
if (slot && (!hst || hst.done || !s || s.holder !== slot)) return null;
|
|
498
|
-
const id = `h${++n}`;
|
|
531
|
+
const id = hst?.id ?? `h${++n}`;
|
|
499
532
|
const ms = deadlineMs();
|
|
500
533
|
const t0 = typeof arrivedAt === 'number' ? arrivedAt : Date.now();
|
|
501
534
|
const entry = {
|
|
502
|
-
id, agent, method, url,
|
|
535
|
+
id, agent, method, url, preview, bodyBytes, sock, note, letter, finish, t0,
|
|
503
536
|
slot: null,
|
|
504
537
|
timer: ms === null ? null
|
|
505
538
|
: setTimeout(() => settle(id, false, 'hold timeout'), Math.max(0, ms - (Date.now() - t0))),
|
|
@@ -524,7 +557,9 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
524
557
|
* Ask for this agent's hold slot before reading a held request's body.
|
|
525
558
|
* @param {string} agent
|
|
526
559
|
* @param {{ onReady: () => void, onExpire: (reason: string) => void }} cbs
|
|
527
|
-
*
|
|
560
|
+
* The handle's `id` is the id its hold will have (empty when `full`), so
|
|
561
|
+
* the body file can be named before the hold parks.
|
|
562
|
+
* @returns {{ state: 'now'|'queued'|'full', id: string, arrivedAt: number, cancel: () => void }}
|
|
528
563
|
*/
|
|
529
564
|
reserve(agent, { onReady, onExpire }) {
|
|
530
565
|
const arrivedAt = Date.now();
|
|
@@ -532,13 +567,15 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
532
567
|
// receives that same object as `slot`, so holder comparisons use it.
|
|
533
568
|
// The one deadline timer lives here, armed below for 'now' and
|
|
534
569
|
// '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 };
|
|
570
|
+
/** @type {{ agent: string, onReady: () => void, onExpire: (reason: string) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean, id: string }} */
|
|
571
|
+
const st = { agent, onReady, onExpire, timer: null, consumed: false, done: false, id: '' };
|
|
537
572
|
const s0 = slots.get(agent);
|
|
538
573
|
/** @type {'now'|'queued'|'full'} */
|
|
539
574
|
const state = !s0 ? 'now' : (s0.line.length >= MAX_WAITING_PER_AGENT ? 'full' : 'queued');
|
|
575
|
+
if (state !== 'full') st.id = `h${++n}`;
|
|
540
576
|
const handle = {
|
|
541
577
|
state,
|
|
578
|
+
id: st.id,
|
|
542
579
|
arrivedAt,
|
|
543
580
|
cancel() {
|
|
544
581
|
if (st.done) return;
|
|
@@ -586,6 +623,7 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
586
623
|
if (h.timer) clearTimeout(h.timer);
|
|
587
624
|
if (h.slot) releaseSlot(h.agent);
|
|
588
625
|
removeAskFile(id);
|
|
626
|
+
dropBody(id);
|
|
589
627
|
log({ ev: 'hold-abandoned', id, agent: h.agent, method: h.method, url: h.url });
|
|
590
628
|
onDeny(h, 'client gone');
|
|
591
629
|
onEvent?.({ type: 'decided', id, decision: 'deny', reason: 'client gone' });
|
|
@@ -597,7 +635,7 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
597
635
|
}
|
|
598
636
|
},
|
|
599
637
|
|
|
600
|
-
|
|
638
|
+
dropBody,
|
|
601
639
|
|
|
602
640
|
pending() { return [...queue.values()].map(pub); },
|
|
603
641
|
|
|
@@ -623,13 +661,3 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
623
661
|
|
|
624
662
|
return holds;
|
|
625
663
|
}
|
|
626
|
-
|
|
627
|
-
/**
|
|
628
|
-
* Default decision: park requests whose path contains `match`.
|
|
629
|
-
*
|
|
630
|
-
* @param {string} match path substring
|
|
631
|
-
* @returns {ShouldHold} decision function
|
|
632
|
-
*/
|
|
633
|
-
export function matchPath(match) {
|
|
634
|
-
return (req) => (new URL(req.url).pathname.includes(match) ? `path matches ${match}` : null);
|
|
635
|
-
}
|
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/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
|
+
}
|