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/run.js
CHANGED
|
@@ -4,19 +4,18 @@
|
|
|
4
4
|
// which stay public): one agent, one sandbox, one audit log, exit code out.
|
|
5
5
|
// The caller never touches sockets, ask files, or the hold queue.
|
|
6
6
|
//
|
|
7
|
-
// What `mode` does
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
// - `trust` forwards everything else, logged.
|
|
7
|
+
// What `mode` does: it picks the agent's bareguard letters (see policy.js).
|
|
8
|
+
// Every request is one `gate.check()`; the hold queue is the gate's human
|
|
9
|
+
// channel. Until rwxmap lands, each HTTP method is one tool: GET/HEAD are `r`,
|
|
10
|
+
// POST/PUT/PATCH/DELETE are `x`, any other method is denied in every mode.
|
|
11
|
+
// - `ask` holds r only; w and x ask.
|
|
12
|
+
// - `auto` holds r and w; x asks.
|
|
13
|
+
// - `trust` holds r, w and x; nothing asks.
|
|
14
|
+
// - the card/payment FLOOR asks in every mode, trust included: a body of
|
|
15
|
+
// <= 64 KB holding a card number (`flags.cardLike`), or a path naming a
|
|
16
|
+
// payment destination (`flags.paymentPath`: /checkout, /payment,
|
|
17
|
+
// /orders, /purchase). Bodies over 64 KB stream through unchecked for
|
|
18
|
+
// cards (known gap). Known payment DOMAINS are B2 (they need rwxmap).
|
|
20
19
|
//
|
|
21
20
|
// A passed `onAsk` answers parked requests with no files involved; when it is
|
|
22
21
|
// absent the file checkpoint runs (`<runtime>/asks` + `<runtime>/answers`,
|
|
@@ -31,55 +30,7 @@ import { createProxy } from './proxy.js';
|
|
|
31
30
|
import { createRuntime, runtimePaths } from './runtime.js';
|
|
32
31
|
import { launch } from './launcher.js';
|
|
33
32
|
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
|
-
}
|
|
33
|
+
import { MODES, gateFor } from './policy.js';
|
|
83
34
|
|
|
84
35
|
/**
|
|
85
36
|
* A collected ask record: the parked ask plus how it was decided.
|
|
@@ -90,7 +41,7 @@ export function shouldHoldForMode(mode) {
|
|
|
90
41
|
* @property {string} method HTTP method
|
|
91
42
|
* @property {string} url full URL
|
|
92
43
|
* @property {string} rule hold-reason string
|
|
93
|
-
* @property {string} letter
|
|
44
|
+
* @property {string} letter the matched rwx letter, `'x'` when the ask names none
|
|
94
45
|
* @property {string} [bodyPreview] request body preview
|
|
95
46
|
* @property {boolean} [truncated] body preview truncation flag
|
|
96
47
|
* @property {string|null} [expiresAt] ISO-8601 UTC deadline, or null
|
|
@@ -110,6 +61,9 @@ export function shouldHoldForMode(mode) {
|
|
|
110
61
|
* @property {string} [runtime] runtime dir (created when absent: a short `sbx-*` temp dir, keeping unix socket paths under the ~108-char limit)
|
|
111
62
|
* @property {string} [agent] agent name (default `'agent'`)
|
|
112
63
|
* @property {number|string} [timeoutMs] hold deadline in ms, or `'never'` (default 120000)
|
|
64
|
+
* @property {number} [heldBodyMaxBytes] cap on a held request's body, in bytes (default 52428800); over it the request is denied
|
|
65
|
+
* @property {{ matcher: any, tools: Record<string, any>, dirs?: string[] }} [labels] the loaded label files (`loadLabels`); their folders are masked from the sandbox
|
|
66
|
+
* @property {string[]} [allowLocal] exact `host:port` pairs (for example a local model server) that may pass the wall's private/loopback check (the `localLlm` setting)
|
|
113
67
|
* @property {object} [unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`): everything under it weakens the sandbox wall
|
|
114
68
|
* @property {NodeJS.WritableStream} [stdout] where the agent's stdout goes (default process.stdout)
|
|
115
69
|
* @property {NodeJS.WritableStream} [stderr] where the agent's stderr goes (default process.stderr)
|
|
@@ -129,6 +83,9 @@ export function shouldHoldForMode(mode) {
|
|
|
129
83
|
* @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
84
|
* @param {string} [opts.agent] agent name (default `'agent'`)
|
|
131
85
|
* @param {number|string} [opts.timeoutMs] hold deadline in ms, or `'never'` (default 120000)
|
|
86
|
+
* @param {number} [opts.heldBodyMaxBytes] cap on a held request's body, in bytes (default 52428800); over it the request is denied
|
|
87
|
+
* @param {{ matcher: any, tools: Record<string, any>, dirs?: string[] }|null} [opts.labels] the loaded label files (`loadLabels`); their folders are masked from the sandbox
|
|
88
|
+
* @param {string[]} [opts.allowLocal] exact `host:port` pairs (for example a local model server) that may pass the wall's private/loopback check (the `localLlm` setting)
|
|
132
89
|
* @param {object|null} [opts.unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`)
|
|
133
90
|
* @param {NodeJS.WritableStream|null} [opts.stdout] where the agent's stdout goes (default process.stdout)
|
|
134
91
|
* @param {NodeJS.WritableStream|null} [opts.stderr] where the agent's stderr goes (default process.stderr)
|
|
@@ -142,8 +99,8 @@ export function shouldHoldForMode(mode) {
|
|
|
142
99
|
* const { exit, asks, audit } = await run({ proj: "/tmp/proj", command: ["bash", "-c", "echo hi"] });
|
|
143
100
|
*/
|
|
144
101
|
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,
|
|
102
|
+
onEvent = null, runtime = null, agent = 'agent', timeoutMs, heldBodyMaxBytes,
|
|
103
|
+
allowLocal = [], labels = null, unsafeTestOnly = null, stdout = null, stderr = null,
|
|
147
104
|
overlay = false, overlayIgnore }) {
|
|
148
105
|
if (typeof proj !== 'string' || !proj) throw new Error('run: proj must be a non-empty string');
|
|
149
106
|
if (!fs.existsSync(proj)) throw new Error(`run: proj does not exist: ${proj}`);
|
|
@@ -154,7 +111,9 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
|
154
111
|
throw new Error('run: onAsk must be a function');
|
|
155
112
|
}
|
|
156
113
|
// Mode first: bad input throws before any runtime dir is created.
|
|
157
|
-
|
|
114
|
+
if (!MODES.includes(mode)) {
|
|
115
|
+
throw new Error(`run: mode must be ${MODES.join('|')}, got ${JSON.stringify(mode)}`);
|
|
116
|
+
}
|
|
158
117
|
// Short temp dir: agent socket paths inherit it and cap at ~108 chars.
|
|
159
118
|
const rt = runtime ?? createRuntime();
|
|
160
119
|
const audit = runtimePaths(rt).audit;
|
|
@@ -177,8 +136,10 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
|
177
136
|
: recordEvent;
|
|
178
137
|
|
|
179
138
|
const proxy = createProxy({
|
|
180
|
-
runtime: rt, logFile: audit, unsafeTestOnly,
|
|
181
|
-
|
|
139
|
+
runtime: rt, logFile: audit, allowLocal, unsafeTestOnly,
|
|
140
|
+
...(labels ? { labels } : {}),
|
|
141
|
+
gateFor: (name, { humanChannel, tools }) => gateFor({ agent: name, mode, auditPath: audit, humanChannel, tools }),
|
|
142
|
+
hold: { onAsk, timeoutMs, maxBody: heldBodyMaxBytes, onEvent: holdOnEvent },
|
|
182
143
|
});
|
|
183
144
|
try {
|
|
184
145
|
await proxy.ready;
|
|
@@ -199,7 +160,7 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
|
199
160
|
const child = launch({
|
|
200
161
|
runtime: rt, agent, proj, command,
|
|
201
162
|
socket: sock, caFile: proxy.caFile,
|
|
202
|
-
overlay, overlayIgnore,
|
|
163
|
+
overlay, overlayIgnore, maskDirs: labels?.dirs ?? [],
|
|
203
164
|
});
|
|
204
165
|
const out = stdout ?? process.stdout;
|
|
205
166
|
const err = stderr ?? process.stderr;
|
package/src/runtime.js
CHANGED
|
@@ -256,17 +256,21 @@ export function shellQuote(s) {
|
|
|
256
256
|
* Every path in a runtime dir. The one place that names them.
|
|
257
257
|
*
|
|
258
258
|
* @param {string} runtime runtime dir
|
|
259
|
-
* @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
|
|
259
|
+
* @returns {{ socket: (agent: string) => string, asksDir: string, answersDir: string, askFile: (id: string) => string, answerFile: (id: string) => string, heldDir: string, heldFile: (id: string) => string, certsDir: string, caBundle: string, audit: string, owner: string, overlay: (agent: string) => { base: string, upper: string, work: string, manifest: string } }} layout
|
|
260
260
|
*/
|
|
261
261
|
export function runtimePaths(runtime) {
|
|
262
262
|
const asksDir = path.join(runtime, 'asks');
|
|
263
263
|
const answersDir = path.join(runtime, 'answers');
|
|
264
|
+
const heldDir = path.join(runtime, 'held');
|
|
264
265
|
return {
|
|
265
266
|
owner: path.join(runtime, 'owner'),
|
|
266
267
|
asksDir,
|
|
267
268
|
answersDir,
|
|
268
269
|
askFile: (id) => path.join(asksDir, `${id}.json`),
|
|
269
270
|
answerFile: (id) => path.join(answersDir, `${id}.json`),
|
|
271
|
+
heldDir,
|
|
272
|
+
// A held request's body, spooled to disk while it waits for a decision.
|
|
273
|
+
heldFile: (id) => path.join(heldDir, id),
|
|
270
274
|
/**
|
|
271
275
|
* The one path both sides agree on: the proxy listens here, the
|
|
272
276
|
* launcher binds it into the sandbox.
|
|
@@ -281,7 +285,8 @@ export function runtimePaths(runtime) {
|
|
|
281
285
|
},
|
|
282
286
|
certsDir: path.join(runtime, 'certs'),
|
|
283
287
|
caBundle: path.join(runtime, 'ca-bundle.pem'),
|
|
284
|
-
audit
|
|
288
|
+
// The one audit file, in bareguard's shape: every agent's gate and the runtime's own `sbx` gate append here (one atomic line per write).
|
|
289
|
+
audit: path.join(runtime, 'gate.jsonl'),
|
|
285
290
|
overlay: (agent) => {
|
|
286
291
|
const base = path.join(runtime, 'overlay', agent);
|
|
287
292
|
return {
|
package/src/wall.js
CHANGED
|
@@ -8,9 +8,12 @@
|
|
|
8
8
|
// and 6to4 (RFC 3056). The check runs AFTER DNS resolution, so a
|
|
9
9
|
// hostname that resolves to 127.0.0.1 is denied exactly like the literal.
|
|
10
10
|
// Unresolvable names are denied too (fail closed, never 502-then-dial).
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
11
|
+
// Two things let a denied destination through. The TEST-ONLY
|
|
12
|
+
// `unsafeTestOnly.allowLoopback` (loopback + unspecified) is for fixtures.
|
|
13
|
+
// `allowLocal` (the `localLlm` setting) names exact `host:port` pairs, such as
|
|
14
|
+
// a local model server: only those pass the private/loopback check, never
|
|
15
|
+
// link-local (cloud metadata), and any other port on the same host is denied
|
|
16
|
+
// as before. There is no allowPrivate flag: the wall is default-deny.
|
|
14
17
|
import net from 'node:net';
|
|
15
18
|
import os from 'node:os';
|
|
16
19
|
import { lookup as dnsLookup } from 'node:dns/promises';
|
|
@@ -198,17 +201,20 @@ function interleaveIps(ips) {
|
|
|
198
201
|
* rebinding, with fallback when the first address refuses).
|
|
199
202
|
*
|
|
200
203
|
* @param {string} host CONNECT/request hostname
|
|
201
|
-
* @param {{ allowLoopback: boolean, resolveUpstream?: (host: string) => Promise<string[] | string | null> }} gate
|
|
204
|
+
* @param {{ allowLoopback: boolean, allowLocal?: ReadonlySet<string>, resolveUpstream?: (host: string) => Promise<string[] | string | null> }} gate
|
|
205
|
+
* @param {number} port destination port (matched against `gate.allowLocal`)
|
|
202
206
|
* @returns {Promise<{ ok: true, ips: string[] } | { ok: false, ip: string, reason: string }>}
|
|
203
207
|
*/
|
|
204
|
-
export async function checkUpstream(host, gate) {
|
|
208
|
+
export async function checkUpstream(host, gate, port) {
|
|
205
209
|
const ips = await resolveAllUpstream(host, gate.resolveUpstream);
|
|
206
210
|
if (!ips || !ips.length) {
|
|
207
211
|
return { ok: false, ip: host, reason: `unresolvable upstream denied: ${host}` };
|
|
208
212
|
}
|
|
213
|
+
const listed = gate.allowLocal?.has(`${host.toLowerCase()}:${port}`) === true;
|
|
209
214
|
for (const ip of ips) {
|
|
210
215
|
const kind = denyReasonForIp(ip, gate.allowLoopback);
|
|
211
|
-
|
|
216
|
+
// A listed host:port waives everything but link-local (cloud metadata).
|
|
217
|
+
if (kind && !(listed && kind !== 'link-local')) {
|
|
212
218
|
const where = ip === host ? host : `${host} (${ip})`;
|
|
213
219
|
return { ok: false, ip, reason: `${kind} upstream denied: ${where}` };
|
|
214
220
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Create a streaming card-number scanner.
|
|
3
|
+
* @returns {{ push(chunk: Buffer): boolean, readonly found: boolean, readonly tailLength: number }}
|
|
4
|
+
* `push` returns `found`; `tailLength` is the retained byte count (<= 40).
|
|
5
|
+
*/
|
|
6
|
+
export function createCardScanner(): {
|
|
7
|
+
push(chunk: Buffer): boolean;
|
|
8
|
+
readonly found: boolean;
|
|
9
|
+
readonly tailLength: number;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Replace every card candidate's digits with `*` except the last 4,
|
|
13
|
+
* keeping the separators.
|
|
14
|
+
* @param {string} text
|
|
15
|
+
* @returns {string}
|
|
16
|
+
*/
|
|
17
|
+
export function maskCards(text: string): string;
|
package/types/cli.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
1
|
+
#!/usr/bin/env -S node --max-semi-space-size=1
|
|
2
2
|
export {};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the config file lives.
|
|
3
|
+
*
|
|
4
|
+
* @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
|
|
5
|
+
* @returns {string} absolute path of `config.json`
|
|
6
|
+
*/
|
|
7
|
+
export function configPath(env?: NodeJS.ProcessEnv): string;
|
|
8
|
+
/**
|
|
9
|
+
* Read the config file over the defaults. No file means defaults.
|
|
10
|
+
*
|
|
11
|
+
* @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
|
|
12
|
+
* @returns {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number }} effective settings (`heldBodyMaxMB` absent means the library default)
|
|
13
|
+
* @throws {Error} naming the file (and the key) on invalid JSON, an unknown key or a bad value
|
|
14
|
+
*/
|
|
15
|
+
export function loadConfig(env?: NodeJS.ProcessEnv): {
|
|
16
|
+
mode: string;
|
|
17
|
+
holdTimeoutSec: number | string;
|
|
18
|
+
localLlm: string[];
|
|
19
|
+
labels: string[];
|
|
20
|
+
tenants: Record<string, string[]>;
|
|
21
|
+
heldBodyMaxMB?: number;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Settings for one `sbx run`: a CLI flag beats the file, the file beats the default.
|
|
25
|
+
*
|
|
26
|
+
* @param {object} [flags] values given on the command line
|
|
27
|
+
* @param {string} [flags.mode] `--mode`
|
|
28
|
+
* @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
|
|
29
|
+
* @returns {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number }} effective settings (`heldBodyMaxMB` absent means the library default)
|
|
30
|
+
* @throws {Error} as {@link loadConfig}
|
|
31
|
+
*/
|
|
32
|
+
export function resolveConfig(flags?: {
|
|
33
|
+
mode?: string | undefined;
|
|
34
|
+
}, env?: NodeJS.ProcessEnv): {
|
|
35
|
+
mode: string;
|
|
36
|
+
holdTimeoutSec: number | string;
|
|
37
|
+
localLlm: string[];
|
|
38
|
+
labels: string[];
|
|
39
|
+
tenants: Record<string, string[]>;
|
|
40
|
+
heldBodyMaxMB?: number;
|
|
41
|
+
};
|
package/types/holds.d.ts
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one body preview, for the ask file: the first
|
|
3
|
+
* ASK_BODY_LIMIT bytes as utf8, with card numbers masked.
|
|
4
|
+
*
|
|
5
|
+
* @param {Buffer} head the body's first bytes (anything past ASK_BODY_LIMIT is ignored)
|
|
6
|
+
* @returns {string} masked preview
|
|
7
|
+
*/
|
|
8
|
+
export function bodyPreview(head: Buffer): string;
|
|
1
9
|
/**
|
|
2
10
|
* A parked request, as returned by {@link pending}. Plain objects only —
|
|
3
|
-
* the queue itself never leaves this module. No body: returning whole
|
|
11
|
+
* the queue itself never leaves this module. No body: returning whole
|
|
4
12
|
* bodies from a status call is never needed, and the ask payload in
|
|
5
13
|
* `asks/<id>.json` carries the preview.
|
|
6
14
|
*
|
|
@@ -9,7 +17,7 @@
|
|
|
9
17
|
* @property {string} agent agent name (its socket), never `c<n>`
|
|
10
18
|
* @property {string} method HTTP method
|
|
11
19
|
* @property {string} url full URL
|
|
12
|
-
* @property {string} rule
|
|
20
|
+
* @property {string} rule the gate's ask rule (hold reason)
|
|
13
21
|
* @property {number} waitingSec seconds since the hold parked
|
|
14
22
|
*/
|
|
15
23
|
/**
|
|
@@ -32,9 +40,9 @@
|
|
|
32
40
|
* @property {string} agent agent name (its socket)
|
|
33
41
|
* @property {string} method HTTP method
|
|
34
42
|
* @property {string} url full URL
|
|
35
|
-
* @property {string} rule
|
|
36
|
-
* @property {string} letter
|
|
37
|
-
* @property {string} bodyPreview request body preview, utf8, capped at ASK_BODY_LIMIT bytes
|
|
43
|
+
* @property {string} rule the gate's ask rule
|
|
44
|
+
* @property {string} letter the matched rwx letter, `'x'` when the ask names none
|
|
45
|
+
* @property {string} bodyPreview request body preview, utf8, capped at ASK_BODY_LIMIT bytes, card numbers masked
|
|
38
46
|
* @property {boolean} truncated true when the body exceeded ASK_BODY_LIMIT
|
|
39
47
|
* @property {number} waitingSec 0 at park; readers use the file mtime for a live value
|
|
40
48
|
* @property {string|null} expiresAt ISO-8601 UTC deadline, or null when `timeoutMs: 'never'`
|
|
@@ -44,12 +52,6 @@
|
|
|
44
52
|
*
|
|
45
53
|
* @typedef {(ask: AskPayload) => Promise<{ decision: string, reason?: string }>} OnAsk
|
|
46
54
|
*/
|
|
47
|
-
/**
|
|
48
|
-
* Decide whether a request parks. Return a human-readable reason, or null
|
|
49
|
-
* to forward. M3 plugs the rwxmap + bareguard classifier into this one seam.
|
|
50
|
-
*
|
|
51
|
-
* @typedef {(req: { agent: string, method: string, url: string, headers: Record<string, string | string[] | undefined> }) => string | null} ShouldHold
|
|
52
|
-
*/
|
|
53
55
|
/**
|
|
54
56
|
* Atomic write: tmp file + rename, so readers never see a partial payload.
|
|
55
57
|
*
|
|
@@ -88,22 +90,18 @@ export function normalizeDecision(input: {
|
|
|
88
90
|
*
|
|
89
91
|
* @param {object} opts
|
|
90
92
|
* @param {(o: Record<string, unknown>) => void} opts.log audit-log writer
|
|
91
|
-
* @param {ShouldHold} [opts.shouldHold] decision function (default: path-substring `match`)
|
|
92
|
-
* @param {string} [opts.match] path substring that parks a request (default impl when `shouldHold` is absent)
|
|
93
93
|
* @param {number|string} [opts.timeoutMs] hold deadline in ms, or `'never'` (default 120000)
|
|
94
|
-
* @param {number} [opts.maxBody] bodies over this are denied at the door, never queued (default
|
|
94
|
+
* @param {number} [opts.maxBody] bodies over this are denied at the door, never queued (default 52428800)
|
|
95
95
|
* @param {string|null} [opts.runtime] runtime dir; required for the default file checkpoint (writes `asks/`, polls `answers/`)
|
|
96
96
|
* @param {OnAsk|null} [opts.onAsk] ask seam (bareguard `humanChannel` shape); when present no files are involved
|
|
97
97
|
* @param {number} [opts.pollMs] answer poll interval in ms for the default file checkpoint (default 250, PRD Q9)
|
|
98
98
|
* @param {OnEvent|null} [opts.onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon
|
|
99
99
|
* @param {(entry: object) => void} opts.onApprove forward the parked request upstream
|
|
100
100
|
* @param {(entry: object, reason: string) => void} opts.onDeny refuse the parked request
|
|
101
|
-
* @returns {{ add: (entry: object) => string|null, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string) => void }) => { state: 'now'|'queued'|'full', arrivedAt: number, cancel: () => void },
|
|
101
|
+
* @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
|
|
102
102
|
*/
|
|
103
|
-
export function createHolds({ log,
|
|
103
|
+
export function createHolds({ log, timeoutMs, maxBody, runtime, onAsk, pollMs, onEvent, onApprove, onDeny }: {
|
|
104
104
|
log: (o: Record<string, unknown>) => void;
|
|
105
|
-
shouldHold?: ShouldHold | undefined;
|
|
106
|
-
match?: string | undefined;
|
|
107
105
|
timeoutMs?: string | number | undefined;
|
|
108
106
|
maxBody?: number | undefined;
|
|
109
107
|
runtime?: string | null | undefined;
|
|
@@ -114,39 +112,30 @@ export function createHolds({ log, shouldHold, match, timeoutMs, maxBody, runtim
|
|
|
114
112
|
onDeny: (entry: object, reason: string) => void;
|
|
115
113
|
}): {
|
|
116
114
|
add: (entry: object) => string | null;
|
|
115
|
+
dropBody: (id: string) => void;
|
|
117
116
|
reserve: (agent: string, cbs: {
|
|
118
117
|
onReady: () => void;
|
|
119
118
|
onExpire: (reason: string) => void;
|
|
120
119
|
}) => {
|
|
121
120
|
state: "now" | "queued" | "full";
|
|
121
|
+
id: string;
|
|
122
122
|
arrivedAt: number;
|
|
123
123
|
cancel: () => void;
|
|
124
124
|
};
|
|
125
|
-
decide: (req: {
|
|
126
|
-
agent: string;
|
|
127
|
-
method: string;
|
|
128
|
-
url: string;
|
|
129
|
-
headers: Record<string, string | string[] | undefined>;
|
|
130
|
-
}) => string | null;
|
|
131
125
|
abandon: (id: string) => void;
|
|
132
126
|
abandonSocket: (sock: object) => void;
|
|
133
127
|
pending: () => HeldRequest[];
|
|
134
128
|
close: () => void;
|
|
135
129
|
};
|
|
136
|
-
/**
|
|
137
|
-
* Default decision: park requests whose path contains `match`.
|
|
138
|
-
*
|
|
139
|
-
* @param {string} match path substring
|
|
140
|
-
* @returns {ShouldHold} decision function
|
|
141
|
-
*/
|
|
142
|
-
export function matchPath(match: string): ShouldHold;
|
|
143
130
|
/** Body preview cap for `asks/<id>.json` (bytes). */
|
|
144
131
|
export const ASK_BODY_LIMIT: 4096;
|
|
132
|
+
/** Default cap on a held body (bytes): over it the request is denied at the door. */
|
|
133
|
+
export const DEFAULT_HOLD_MAX_BODY: 52428800;
|
|
145
134
|
/** Default answer poll interval in ms (PRD Q9). */
|
|
146
135
|
export const DEFAULT_POLL_MS: 250;
|
|
147
136
|
/**
|
|
148
137
|
* A parked request, as returned by {@link pending}. Plain objects only —
|
|
149
|
-
* the queue itself never leaves this module. No body: returning whole
|
|
138
|
+
* the queue itself never leaves this module. No body: returning whole
|
|
150
139
|
* bodies from a status call is never needed, and the ask payload in
|
|
151
140
|
* `asks/<id>.json` carries the preview.
|
|
152
141
|
*/
|
|
@@ -168,7 +157,7 @@ export type HeldRequest = {
|
|
|
168
157
|
*/
|
|
169
158
|
url: string;
|
|
170
159
|
/**
|
|
171
|
-
*
|
|
160
|
+
* the gate's ask rule (hold reason)
|
|
172
161
|
*/
|
|
173
162
|
rule: string;
|
|
174
163
|
/**
|
|
@@ -215,15 +204,15 @@ export type AskPayload = {
|
|
|
215
204
|
*/
|
|
216
205
|
url: string;
|
|
217
206
|
/**
|
|
218
|
-
*
|
|
207
|
+
* the gate's ask rule
|
|
219
208
|
*/
|
|
220
209
|
rule: string;
|
|
221
210
|
/**
|
|
222
|
-
*
|
|
211
|
+
* the matched rwx letter, `'x'` when the ask names none
|
|
223
212
|
*/
|
|
224
213
|
letter: string;
|
|
225
214
|
/**
|
|
226
|
-
* request body preview, utf8, capped at ASK_BODY_LIMIT bytes
|
|
215
|
+
* request body preview, utf8, capped at ASK_BODY_LIMIT bytes, card numbers masked
|
|
227
216
|
*/
|
|
228
217
|
bodyPreview: string;
|
|
229
218
|
/**
|
|
@@ -246,13 +235,3 @@ export type OnAsk = (ask: AskPayload) => Promise<{
|
|
|
246
235
|
decision: string;
|
|
247
236
|
reason?: string;
|
|
248
237
|
}>;
|
|
249
|
-
/**
|
|
250
|
-
* Decide whether a request parks. Return a human-readable reason, or null
|
|
251
|
-
* to forward. M3 plugs the rwxmap + bareguard classifier into this one seam.
|
|
252
|
-
*/
|
|
253
|
-
export type ShouldHold = (req: {
|
|
254
|
-
agent: string;
|
|
255
|
-
method: string;
|
|
256
|
-
url: string;
|
|
257
|
-
headers: Record<string, string | string[] | undefined>;
|
|
258
|
-
}) => string | null;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Load every label folder: the matcher for request keys and the tools table
|
|
3
|
+
* (key to `{ letter, marker }`) from the gate files. Call once at startup so a
|
|
4
|
+
* bad file fails the run before any agent starts.
|
|
5
|
+
*
|
|
6
|
+
* @param {object} cfg
|
|
7
|
+
* @param {string[]} [cfg.labels] folders the rwxmap CLI wrote (`~/` means `$HOME`)
|
|
8
|
+
* @param {Record<string, string[]>} [cfg.tenants] vendor to tenant base URLs, replacing the sidecar's `servers`
|
|
9
|
+
* @param {NodeJS.ProcessEnv} [env] environment for `$HOME`
|
|
10
|
+
* @returns {{ matcher: ReturnType<typeof matcherFrom>, tools: Record<string, any>, dirs: string[] }} `dirs` are the absolute folders (the launcher masks them)
|
|
11
|
+
* @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
|
|
12
|
+
*/
|
|
13
|
+
export function loadLabels({ labels, tenants }: {
|
|
14
|
+
labels?: string[] | undefined;
|
|
15
|
+
tenants?: Record<string, string[]> | undefined;
|
|
16
|
+
}, env?: NodeJS.ProcessEnv): {
|
|
17
|
+
matcher: ReturnType<typeof matcherFrom>;
|
|
18
|
+
tools: Record<string, any>;
|
|
19
|
+
dirs: string[];
|
|
20
|
+
};
|
|
21
|
+
import { matcherFrom } from 'rwxmap/match';
|
package/types/launcher.d.ts
CHANGED
|
@@ -29,6 +29,7 @@ export function buildCaBundle(runtime: string, caFile: string): string;
|
|
|
29
29
|
* @param {object} [opts.extraEnv] extra environment entries for the inside
|
|
30
30
|
* @param {string|null} [opts.socket] agent socket path, as returned by `proxy.addAgent` (default `<runtime>/socks/<agent>.sock`; the two must agree)
|
|
31
31
|
* @param {string|null} [opts.caFile] barebox CA cert path (from `proxy.caFile`); when set, the sandbox trusts it for HTTPS alongside the system roots
|
|
32
|
+
* @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)
|
|
32
33
|
* @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)`
|
|
33
34
|
* @param {string[]} [opts.overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
|
|
34
35
|
* @returns {import('node:child_process').ChildProcess} the bwrap child (stdio piped); `close` gives its exit code
|
|
@@ -39,7 +40,7 @@ export function buildCaBundle(runtime: string, caFile: string): string;
|
|
|
39
40
|
* const child = launch({ runtime: "/tmp/sbx", agent: "fx", proj: "/tmp/proj", command: ["bash", "-c", "echo hi"] });
|
|
40
41
|
* await new Promise((r) => child.on("close", r)); // child.exitCode === 0
|
|
41
42
|
*/
|
|
42
|
-
export function launch({ runtime, agent, proj, command, proxyPort, extraEnv, socket, caFile, overlay, overlayIgnore }: {
|
|
43
|
+
export function launch({ runtime, agent, proj, command, proxyPort, extraEnv, socket, caFile, overlay, overlayIgnore, maskDirs }: {
|
|
43
44
|
runtime: string;
|
|
44
45
|
agent: string;
|
|
45
46
|
proj: string;
|
|
@@ -48,6 +49,7 @@ export function launch({ runtime, agent, proj, command, proxyPort, extraEnv, soc
|
|
|
48
49
|
extraEnv?: object;
|
|
49
50
|
socket?: string | null | undefined;
|
|
50
51
|
caFile?: string | null | undefined;
|
|
52
|
+
maskDirs?: string[] | undefined;
|
|
51
53
|
overlay?: boolean | undefined;
|
|
52
54
|
overlayIgnore?: string[] | undefined;
|
|
53
55
|
}): import("node:child_process").ChildProcess;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one tools table of a runtime: the `http.*` tools, the model endpoints
|
|
3
|
+
* (`r`) and the label tools. Model keys come from `matcher.match()` itself so
|
|
4
|
+
* there is no second key builder.
|
|
5
|
+
*
|
|
6
|
+
* @param {Record<string, any>} [labelTools] the label files' gate-file tools (`{ key: { letter, marker } }`)
|
|
7
|
+
* @param {string[]} [localLlm] `host:port` pairs of local model servers
|
|
8
|
+
* @returns {Record<string, any>} tool name to letter
|
|
9
|
+
*/
|
|
10
|
+
export function buildTools(labelTools?: Record<string, any>, localLlm?: string[]): Record<string, any>;
|
|
11
|
+
/**
|
|
12
|
+
* The tool name for one request. A spec key (a label file documents it) is
|
|
13
|
+
* used as is, even if the gate file lacks it (then the gate denies it:
|
|
14
|
+
* fail closed). A request-only key is used only when it is a known model
|
|
15
|
+
* endpoint; everything else is `http.<METHOD>`. Never the matcher's letter.
|
|
16
|
+
*
|
|
17
|
+
* @param {{ match: (method: string, url: string) => { key: string, source: string } }} matcher
|
|
18
|
+
* @param {Record<string, any>} tools the runtime's tools table
|
|
19
|
+
* @param {string} method HTTP method
|
|
20
|
+
* @param {string} url full request URL
|
|
21
|
+
* @returns {string} the tool name
|
|
22
|
+
*/
|
|
23
|
+
export function toolFor(matcher: {
|
|
24
|
+
match: (method: string, url: string) => {
|
|
25
|
+
key: string;
|
|
26
|
+
source: string;
|
|
27
|
+
};
|
|
28
|
+
}, tools: Record<string, any>, method: string, url: string): string;
|
|
29
|
+
/**
|
|
30
|
+
* True when the URL's path names a payment destination (the floor's
|
|
31
|
+
* URL-visible half). An unparsable URL is not one.
|
|
32
|
+
*
|
|
33
|
+
* @param {string} url full request URL
|
|
34
|
+
* @returns {boolean} whether the path contains a payment fragment
|
|
35
|
+
*/
|
|
36
|
+
export function paymentPath(url: string): boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Build and initialise one agent's gate.
|
|
39
|
+
*
|
|
40
|
+
* @param {object} opts
|
|
41
|
+
* @param {string} opts.agent agent name (the gate's rwx agent)
|
|
42
|
+
* @param {string} opts.mode `ask` | `auto` | `trust`
|
|
43
|
+
* @param {string} opts.auditPath bareguard audit file (shared by every gate of a runtime)
|
|
44
|
+
* @param {Record<string, any>} [opts.tools] the runtime's tools table (default: the `http.*` tools)
|
|
45
|
+
* @param {(event: any) => Promise<{ decision: 'allow' | 'deny', reason?: string }>} opts.humanChannel resolves every ask
|
|
46
|
+
* @returns {Promise<Gate>} an initialised gate
|
|
47
|
+
*/
|
|
48
|
+
export function gateFor({ agent, mode, auditPath, humanChannel, tools }: {
|
|
49
|
+
agent: string;
|
|
50
|
+
mode: string;
|
|
51
|
+
auditPath: string;
|
|
52
|
+
tools?: Record<string, any> | undefined;
|
|
53
|
+
humanChannel: (event: any) => Promise<{
|
|
54
|
+
decision: "allow" | "deny";
|
|
55
|
+
reason?: string;
|
|
56
|
+
}>;
|
|
57
|
+
}): Promise<Gate>;
|
|
58
|
+
/** The mode names, in the order the CLI and config list them. */
|
|
59
|
+
export const MODES: string[];
|
|
60
|
+
/** The matcher used when no label files are loaded: every request is request-only. */
|
|
61
|
+
export const emptyMatcher: {
|
|
62
|
+
match: (method: string, url: string) => import("rwxmap/match").MatchResult;
|
|
63
|
+
};
|
|
64
|
+
import { Gate } from 'bareguard';
|