barebox 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/run.js 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 TODAY (letters are M3's job): the proxy sees requests,
8
- // not intent, so until the rwxmap + bareguard letter pipeline lands there is
9
- // no per-letter policy — only this interim hold rule:
10
- // - the card/payment FLOOR holds in every mode, including `trust`: a
11
- // request whose path names a payment destination (`/checkout`,
12
- // `/payment`, `/orders`, `/purchase`). The card-in-body half of the
13
- // floor is NOT enforced here: the decide seam sees method/URL/headers
14
- // but never the body, so body inspection waits for M3's in-proxy rules.
15
- // Known payment DOMAINS are likewise M3 (they need rwxmap).
16
- // - `ask`/`auto` additionally park every non-GET/HEAD request (the PRD's
17
- // "unsure? tag it x" default: GET/HEAD = r, anything else = x). The two
18
- // modes behave identically until M3's `askOn` letters separate them.
19
- // - `trust` forwards everything else, logged.
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,8 @@ 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';
34
+ import { loadSecrets } from './secrets.js';
83
35
 
84
36
  /**
85
37
  * A collected ask record: the parked ask plus how it was decided.
@@ -90,7 +42,7 @@ export function shouldHoldForMode(mode) {
90
42
  * @property {string} method HTTP method
91
43
  * @property {string} url full URL
92
44
  * @property {string} rule hold-reason string
93
- * @property {string} letter always `'x'` until M3 owns letters
45
+ * @property {string} letter the matched rwx letter, `'x'` when the ask names none
94
46
  * @property {string} [bodyPreview] request body preview
95
47
  * @property {boolean} [truncated] body preview truncation flag
96
48
  * @property {string|null} [expiresAt] ISO-8601 UTC deadline, or null
@@ -110,9 +62,14 @@ export function shouldHoldForMode(mode) {
110
62
  * @property {string} [runtime] runtime dir (created when absent: a short `sbx-*` temp dir, keeping unix socket paths under the ~108-char limit)
111
63
  * @property {string} [agent] agent name (default `'agent'`)
112
64
  * @property {number|string} [timeoutMs] hold deadline in ms, or `'never'` (default 120000)
65
+ * @property {number} [heldBodyMaxBytes] cap on a held request's body, in bytes (default 52428800); over it the request is denied
66
+ * @property {{ matcher: any, tools: Record<string, any>, dirs?: string[] }} [labels] the loaded label files (`loadLabels`); their folders are masked from the sandbox
67
+ * @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
68
  * @property {object} [unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`): everything under it weakens the sandbox wall
114
69
  * @property {NodeJS.WritableStream} [stdout] where the agent's stdout goes (default process.stdout)
115
70
  * @property {NodeJS.WritableStream} [stderr] where the agent's stderr goes (default process.stderr)
71
+ * @property {Record<string, { fromEnv?: string, value?: string, hosts: string[] }>} [secrets] keys the agent never holds (M5), the config `secrets` shape: the sandbox gets a random placeholder under each NAME; the proxy swaps in the real value on an allowed request to one of its `hosts` (see `createProxy`). A `fromEnv` variable missing from this process's environment rejects the run, naming the secret
72
+ * @property {{ pass?: string[], set?: Record<string, string> }} [env] the sandbox's environment (M5), the config `env` shape: the host environment never reaches it except a short default list (`TERM`, `LANG`, `LC_*`, `TZ`, ...), the host variables named in `pass` and the values in `set` (see `launch`)
116
73
  * @property {boolean} [overlay] when true, mount a per-run overlay upper over the project (M4 tracing paper) instead of binding it read-only; the result's `diff` lists the run's changes for commit/rollback
117
74
  * @property {string[]} [overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
118
75
  */
@@ -129,22 +86,27 @@ export function shouldHoldForMode(mode) {
129
86
  * @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
87
  * @param {string} [opts.agent] agent name (default `'agent'`)
131
88
  * @param {number|string} [opts.timeoutMs] hold deadline in ms, or `'never'` (default 120000)
89
+ * @param {number} [opts.heldBodyMaxBytes] cap on a held request's body, in bytes (default 52428800); over it the request is denied
90
+ * @param {{ matcher: any, tools: Record<string, any>, dirs?: string[] }|null} [opts.labels] the loaded label files (`loadLabels`); their folders are masked from the sandbox
91
+ * @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
92
  * @param {object|null} [opts.unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`)
133
93
  * @param {NodeJS.WritableStream|null} [opts.stdout] where the agent's stdout goes (default process.stdout)
134
94
  * @param {NodeJS.WritableStream|null} [opts.stderr] where the agent's stderr goes (default process.stderr)
95
+ * @param {Record<string, { fromEnv?: string, value?: string, hosts: string[] }>|null} [opts.secrets] keys the agent never holds (M5), the config `secrets` shape; see {@link RunOptions}
96
+ * @param {{ pass?: string[], set?: Record<string, string> }|null} [opts.env] the sandbox's environment (M5), the config `env` shape; see {@link RunOptions}
135
97
  * @param {boolean} [opts.overlay] when true, mount a per-run overlay upper over the project instead of binding it read-only; the result's `diff` lists the run's changes for commit/rollback
136
98
  * @param {string[]} [opts.overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
137
99
  * @returns {Promise<{ exit: number, asks: AskRecord[], audit: string, diff: import('./overlay.js').OverlayChange[], runtime: string }>} the agent process exit code, the collected ask records, the JSONL audit log path, the run's overlay diff (M4), and the runtime dir addressing it
138
100
  * @when Reach for this to HARNESS-ONLY run one sandboxed agent start-to-finish in a single call: it starts the proxy, sandboxes the command, answers holds, and returns the exit code with the ask and audit trail (plus the overlay diff once M4 exists).
139
- * @fails Rejects on a missing/unreadable `proj`, an empty `command`, a bad `mode`, a misshapen `onAsk`, a proxy that never becomes ready, a `launch` that throws (uncommitted overlay changes, a runtime inside the project — the proxy is closed first), or an overlay diff that cannot be read. The agent's own nonzero exit is returned as `exit`, never thrown.
101
+ * @fails Rejects on a missing/unreadable `proj`, an empty `command`, a bad `mode`, a misshapen `onAsk`, a `secrets` entry with no value (a `fromEnv` variable missing from this process's environment; the message names the secret, never a value), a proxy that never becomes ready, a `launch` that throws (uncommitted overlay changes, a runtime inside the project — the proxy is closed first), or an overlay diff that cannot be read. The agent's own nonzero exit is returned as `exit`, never thrown.
140
102
  * @example
141
103
  * import { run } from "barebox";
142
104
  * const { exit, asks, audit } = await run({ proj: "/tmp/proj", command: ["bash", "-c", "echo hi"] });
143
105
  */
144
106
  export async function run({ proj, command, mode = 'auto', onAsk = null,
145
- onEvent = null, runtime = null, agent = 'agent', timeoutMs,
146
- unsafeTestOnly = null, stdout = null, stderr = null,
147
- overlay = false, overlayIgnore }) {
107
+ onEvent = null, runtime = null, agent = 'agent', timeoutMs, heldBodyMaxBytes,
108
+ allowLocal = [], labels = null, unsafeTestOnly = null, stdout = null, stderr = null,
109
+ overlay = false, overlayIgnore, secrets = null, env = null }) {
148
110
  if (typeof proj !== 'string' || !proj) throw new Error('run: proj must be a non-empty string');
149
111
  if (!fs.existsSync(proj)) throw new Error(`run: proj does not exist: ${proj}`);
150
112
  if (!Array.isArray(command) || !command.length) {
@@ -154,7 +116,11 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
154
116
  throw new Error('run: onAsk must be a function');
155
117
  }
156
118
  // Mode first: bad input throws before any runtime dir is created.
157
- const decide = shouldHoldForMode(mode);
119
+ if (!MODES.includes(mode)) {
120
+ throw new Error(`run: mode must be ${MODES.join('|')}, got ${JSON.stringify(mode)}`);
121
+ }
122
+ // Once per run: the placeholders are fresh per run. A secret without a value throws here, before any runtime dir.
123
+ const loaded = loadSecrets(secrets ?? {});
158
124
  // Short temp dir: agent socket paths inherit it and cap at ~108 chars.
159
125
  const rt = runtime ?? createRuntime();
160
126
  const audit = runtimePaths(rt).audit;
@@ -177,8 +143,10 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
177
143
  : recordEvent;
178
144
 
179
145
  const proxy = createProxy({
180
- runtime: rt, logFile: audit, unsafeTestOnly,
181
- hold: { shouldHold: decide, onAsk, timeoutMs, onEvent: holdOnEvent },
146
+ runtime: rt, logFile: audit, allowLocal, unsafeTestOnly, secrets: loaded,
147
+ ...(labels ? { labels } : {}),
148
+ gateFor: (name, { humanChannel, tools }) => gateFor({ agent: name, mode, auditPath: audit, humanChannel, tools }),
149
+ hold: { onAsk, timeoutMs, maxBody: heldBodyMaxBytes, onEvent: holdOnEvent },
182
150
  });
183
151
  try {
184
152
  await proxy.ready;
@@ -199,7 +167,8 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
199
167
  const child = launch({
200
168
  runtime: rt, agent, proj, command,
201
169
  socket: sock, caFile: proxy.caFile,
202
- overlay, overlayIgnore,
170
+ overlay, overlayIgnore, maskDirs: labels?.dirs ?? [],
171
+ env: { ...env, placeholders: Object.fromEntries(loaded.map((s) => [s.name, s.placeholder])) },
203
172
  });
204
173
  const out = stdout ?? process.stdout;
205
174
  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: path.join(runtime, 'audit.jsonl'),
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/secrets.js ADDED
@@ -0,0 +1,113 @@
1
+ // Secrets (M5): keys the agent never holds. The sandbox gets one random
2
+ // placeholder per secret; the proxy, outside it, swaps the real value into a
3
+ // request's headers only after the gate allowed it and only for a bound host.
4
+ // Pure: no I/O, no proxy state. Detect and apply are separate on purpose, so
5
+ // the real value is never in a request's headers while it waits for a decision.
6
+ import crypto from 'node:crypto';
7
+
8
+ /**
9
+ * One loaded secret.
10
+ *
11
+ * @typedef {object} Secret
12
+ * @property {string} name the variable name the sandbox sees the placeholder under
13
+ * @property {string} value the real value; never leaves the proxy except in an allowed request's header
14
+ * @property {string[]} hosts hostnames (no port) the real value may be sent to
15
+ * @property {string} placeholder `sbx-ph-<16 hex>`, fresh per call
16
+ */
17
+
18
+ /** Request headers as node reads them: lowercase names, string or string[] values. @typedef {Record<string, string | string[] | undefined>} Headers */
19
+
20
+ const BASIC = /^(Basic\s+)([A-Za-z0-9+/=_-]+)$/i;
21
+
22
+ /** @param {string} h @returns {string} */
23
+ const bare = (h) => h.toLowerCase();
24
+
25
+ /**
26
+ * Read the secrets from the config shape and give each a fresh placeholder.
27
+ *
28
+ * @param {Record<string, { fromEnv?: string, value?: string, hosts: string[] }>} [config] the config `secrets` object
29
+ * @param {NodeJS.ProcessEnv} [env] where `fromEnv` is read (default `process.env`)
30
+ * @returns {Secret[]} one entry per secret, new placeholders on every call (so per run)
31
+ * @throws {Error} naming the secret (never a value) when it has no value or no hosts
32
+ */
33
+ export function loadSecrets(config = {}, env = process.env) {
34
+ return Object.entries(config).map(([name, c]) => {
35
+ const value = c.fromEnv !== undefined ? env[c.fromEnv] : c.value;
36
+ if (typeof value !== 'string' || !value) throw new Error(`secret ${name}: no value`);
37
+ if (!Array.isArray(c.hosts) || !c.hosts.length) throw new Error(`secret ${name}: hosts required`);
38
+ return { name, value, hosts: c.hosts.map(bare), placeholder: `sbx-ph-${crypto.randomBytes(8).toString('hex')}` };
39
+ });
40
+ }
41
+
42
+ /**
43
+ * Does `v` hold the secret's placeholder, plainly or inside `Basic <base64>`?
44
+ * @param {string} v @param {Secret} s @returns {'plain'|'basic'|null}
45
+ */
46
+ function kindIn(v, s) {
47
+ if (v.includes(s.placeholder)) return 'plain';
48
+ const m = BASIC.exec(v);
49
+ if (m && Buffer.from(m[2], 'base64').toString('latin1').includes(s.placeholder)) return 'basic';
50
+ return null;
51
+ }
52
+
53
+ /**
54
+ * @param {string} v one header value @param {Secret} s @returns {string} `v` with the real value in place
55
+ */
56
+ function swapIn(v, s) {
57
+ const kind = kindIn(v, s);
58
+ if (kind === 'plain') return v.split(s.placeholder).join(s.value);
59
+ if (kind === 'basic') {
60
+ const m = /** @type {RegExpExecArray} */ (BASIC.exec(v));
61
+ const dec = Buffer.from(m[2], 'base64').toString('latin1');
62
+ // latin1 keeps every byte; the value goes in as its UTF-8 bytes.
63
+ const real = Buffer.from(s.value, 'utf8').toString('latin1');
64
+ return m[1] + Buffer.from(dec.split(s.placeholder).join(real), 'latin1').toString('base64');
65
+ }
66
+ return v;
67
+ }
68
+
69
+ /**
70
+ * Which placeholders a request carries, and whether each is headed for a host its secret is bound to.
71
+ * Each header value is searched as a substring and, for `Basic <base64>`, decoded.
72
+ *
73
+ * @param {Headers} headers the request headers
74
+ * @param {string} host the request's hostname (no port)
75
+ * @param {Secret[]} secrets from {@link loadSecrets}
76
+ * @returns {{ name: string, header: string, bound: boolean }[]} one entry per (secret, header)
77
+ */
78
+ export function findPlaceholders(headers, host, secrets) {
79
+ const h = bare(host);
80
+ const found = [];
81
+ for (const [header, v] of Object.entries(headers)) {
82
+ const vals = Array.isArray(v) ? v : [v];
83
+ for (const s of secrets) {
84
+ if (vals.some((x) => typeof x === 'string' && kindIn(x, s))) {
85
+ found.push({ name: s.name, header, bound: s.hosts.includes(h) });
86
+ }
87
+ }
88
+ }
89
+ return found;
90
+ }
91
+
92
+ /**
93
+ * The headers with every bound placeholder replaced by its real value. A new
94
+ * object; the input (which the agent's request owns) is never changed.
95
+ * Placeholders of a secret not bound to `host` stay as they are.
96
+ *
97
+ * @param {Headers} headers the request headers
98
+ * @param {string} host the request's hostname (no port)
99
+ * @param {Secret[]} secrets from {@link loadSecrets}
100
+ * @returns {Headers} new headers
101
+ */
102
+ export function applySecrets(headers, host, secrets) {
103
+ const h = bare(host);
104
+ const bound = secrets.filter((s) => s.hosts.includes(h));
105
+ /** @type {Headers} */
106
+ const out = {};
107
+ for (const [k, v] of Object.entries(headers)) {
108
+ /** @param {string} x @returns {string} */
109
+ const one = (x) => bound.reduce((acc, s) => swapIn(acc, s), x);
110
+ out[k] = Array.isArray(v) ? v.map(one) : (typeof v === 'string' ? one(v) : v);
111
+ }
112
+ return out;
113
+ }
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
- // Only the TEST-ONLY `unsafeTestOnly.allowLoopback` (loopback + unspecified)
12
- // lets a denied destination through; only tests pass it. There is no
13
- // allowPrivate flag and no per-host escape hatch: the wall is default-deny.
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
- if (kind) {
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,59 @@
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, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} 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
+ env?: {
23
+ pass?: string[];
24
+ set?: Record<string, string>;
25
+ };
26
+ secrets?: Record<string, {
27
+ fromEnv?: string;
28
+ value?: string;
29
+ hosts: string[];
30
+ }>;
31
+ };
32
+ /**
33
+ * Settings for one `sbx run`: a CLI flag beats the file, the file beats the default.
34
+ *
35
+ * @param {object} [flags] values given on the command line
36
+ * @param {string} [flags.mode] `--mode`
37
+ * @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
38
+ * @returns {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
39
+ * @throws {Error} as {@link loadConfig}
40
+ */
41
+ export function resolveConfig(flags?: {
42
+ mode?: string | undefined;
43
+ }, env?: NodeJS.ProcessEnv): {
44
+ mode: string;
45
+ holdTimeoutSec: number | string;
46
+ localLlm: string[];
47
+ labels: string[];
48
+ tenants: Record<string, string[]>;
49
+ heldBodyMaxMB?: number;
50
+ env?: {
51
+ pass?: string[];
52
+ set?: Record<string, string>;
53
+ };
54
+ secrets?: Record<string, {
55
+ fromEnv?: string;
56
+ value?: string;
57
+ hosts: string[];
58
+ }>;
59
+ };
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 1 MB
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 hold-reason string from the decision function
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 hold-reason string from the decision function
36
- * @property {string} letter always `'x'` until M3 owns letters
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 1048576)
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 }, decide: (req: { agent: string, method: string, url: string, headers: Record<string, string | string[] | undefined> }) => string | null, abandon: (id: string) => void, abandonSocket: (sock: object) => void, pending: () => HeldRequest[], close: () => void }} queue handle
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, shouldHold, match, timeoutMs, maxBody, runtime, onAsk, pollMs, onEvent, onApprove, onDeny }: {
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 1 MB
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
- * hold-reason string from the decision function
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
- * hold-reason string from the decision function
207
+ * the gate's ask rule
219
208
  */
220
209
  rule: string;
221
210
  /**
222
- * always `'x'` until M3 owns letters
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;
package/types/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { launch } from "./launcher.js";
2
2
  export { createProxy } from "./proxy.js";
3
3
  export { run } from "./run.js";
4
+ export { loadLabels } from "./labels.js";
4
5
  export { diffOverlay, commitOverlay, rollbackOverlay } from "./overlay.js";