barebox 0.1.0 → 0.3.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/holds.js ADDED
@@ -0,0 +1,476 @@
1
+ // holds.js — the ONLY writer of the hold queue.
2
+ //
3
+ // A held request parks with its client socket open until the ask channel
4
+ // answers. Two channels, one queue:
5
+ // - `onAsk(ask) -> Promise<{ decision, reason? }>` (bareguard's
6
+ // `humanChannel` shape): one promise per hold, no files involved.
7
+ // - the default file checkpoint: `<runtime>/asks/<id>.json` is written on
8
+ // park, and ONE interval per queue reads `<runtime>/answers/` once per
9
+ // tick (default 250 ms, PRD Q9), consuming each answer file (renamed away
10
+ // before reading). An answer for a held id settles it; anything else is
11
+ // stale: ignored, logged (`stale-answer`), removed.
12
+ // The deadline timer in `add()` is the only deadline: nothing else looks
13
+ // at the clock. Timeout — or any failure of the channel itself — is deny.
14
+ // A malformed answer (bad JSON, missing/unknown decision) is ignored,
15
+ // logged (`malformed-answer`), and removed; the hold keeps waiting until
16
+ // the deadline. The queue never throws on channel input: everything
17
+ // unexpected is loud in the log and eventually a deny.
18
+ //
19
+ // Decisions enter through one `normalizeDecision` (`allow`/`deny`, with
20
+ // `'approve'` accepted as an alias of `'allow'` in answer files only) and
21
+ // are reported through one optional `onEvent` callback: `{ type: 'ask' }`
22
+ // when a hold parks, `{ type: 'decided' }` when it settles or is abandoned
23
+ // (`deny` / `client gone`). Outcomes are
24
+ // reported, never reconstructed: `run()` and `sbx run` build their ask
25
+ // records from these events. The library never writes to stdout or stderr.
26
+ //
27
+ // Approving a hold whose client is gone must be impossible: `abandon()`
28
+ // removes the entry and its ask file, so a later answer is stale and
29
+ // nothing is forwarded.
30
+ //
31
+ // Ask payload (`asks/<id>.json`): `id`, `agent`, `method`, `url`, `rule`
32
+ // (the hold-reason string), `letter`, `bodyPreview` + `truncated`,
33
+ // `waitingSec` (0 at park; readers use the file mtime for a live value),
34
+ // `expiresAt` (ISO-8601 UTC string, or null when `timeoutMs: 'never'`).
35
+ // `letter` is `'x'` for every parked ask: letters are M3's job (rwxmap +
36
+ // bareguard) — the queue only parks what the decision function flags, and
37
+ // everything flagged today is irreversible. Headers are excluded from the
38
+ // payload (they carry Authorization secrets); the body preview is capped at
39
+ // ASK_BODY_LIMIT bytes but otherwise verbatim — M3's bareguard `secrets`
40
+ // redaction takes over redaction there.
41
+ //
42
+ // Answer payload (`answers/<id>.json`): `{ decision: 'allow' | 'deny',
43
+ // reason? }`. `'approve'` is accepted as an alias of `'allow'`. Writers
44
+ // must write atomically (tmp file + rename); readers never see partials.
45
+ import fs from 'node:fs';
46
+ import path from 'node:path';
47
+ import { runtimePaths } from './runtime.js';
48
+
49
+ /** Body preview cap for `asks/<id>.json` (bytes). */
50
+ export const ASK_BODY_LIMIT = 4096;
51
+
52
+ /** Default answer poll interval in ms (PRD Q9). */
53
+ export const DEFAULT_POLL_MS = 250;
54
+
55
+ /**
56
+ * A parked request, as returned by {@link pending}. Plain objects only —
57
+ * the queue itself never leaves this module. No body: returning whole 1 MB
58
+ * bodies from a status call is never needed, and the ask payload in
59
+ * `asks/<id>.json` carries the preview.
60
+ *
61
+ * @typedef {object} HeldRequest
62
+ * @property {string} id hold id (`h<n>`)
63
+ * @property {string} agent agent name (its socket), never `c<n>`
64
+ * @property {string} method HTTP method
65
+ * @property {string} url full URL
66
+ * @property {string} rule hold-reason string from the decision function
67
+ * @property {number} waitingSec seconds since the hold parked
68
+ */
69
+
70
+ /**
71
+ * A queue event, as delivered to the `onEvent` callback: `{ type: 'ask' }`
72
+ * when a hold parks, `{ type: 'decided' }` when it settles or its client
73
+ * goes away (`deny` / `client gone`): every ask ends in exactly one.
74
+ *
75
+ * @typedef {{ type: 'ask', ask: AskPayload } | { type: 'decided', id: string, decision: 'allow' | 'deny', reason?: string }} HoldEvent
76
+ */
77
+
78
+ /**
79
+ * Queue event callback.
80
+ *
81
+ * @typedef {(e: HoldEvent) => void} OnEvent
82
+ */
83
+
84
+ /**
85
+ * The decision-ready ask written to `asks/<id>.json`.
86
+ *
87
+ * @typedef {object} AskPayload
88
+ * @property {string} id hold id (`h<n>`)
89
+ * @property {string} agent agent name (its socket)
90
+ * @property {string} method HTTP method
91
+ * @property {string} url full URL
92
+ * @property {string} rule hold-reason string from the decision function
93
+ * @property {string} letter always `'x'` until M3 owns letters
94
+ * @property {string} bodyPreview request body preview, utf8, capped at ASK_BODY_LIMIT bytes
95
+ * @property {boolean} truncated true when the body exceeded ASK_BODY_LIMIT
96
+ * @property {number} waitingSec 0 at park; readers use the file mtime for a live value
97
+ * @property {string|null} expiresAt ISO-8601 UTC deadline, or null when `timeoutMs: 'never'`
98
+ */
99
+
100
+ /**
101
+ * Decide a parked ask. Resolves `{ decision: 'allow' | 'deny', reason? }`.
102
+ *
103
+ * @typedef {(ask: AskPayload) => Promise<{ decision: string, reason?: string }>} OnAsk
104
+ */
105
+
106
+ /**
107
+ * Decide whether a request parks. Return a human-readable reason, or null
108
+ * to forward. M3 plugs the rwxmap + bareguard classifier into this one seam.
109
+ *
110
+ * @typedef {(req: { agent: string, method: string, url: string, headers: Record<string, string | string[] | undefined> }) => string | null} ShouldHold
111
+ */
112
+
113
+ /**
114
+ * Atomic write: tmp file + rename, so readers never see a partial payload.
115
+ *
116
+ * @param {string} file destination path
117
+ * @param {string} text content
118
+ * @returns {void}
119
+ */
120
+ export function writeFileAtomic(file, text) {
121
+ fs.mkdirSync(path.dirname(file), { recursive: true });
122
+ const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
123
+ // 0600, not the 0644 default: asks carry the audit trail and unredacted
124
+ // body previews, and answers carry the decision. (Umask can only remove
125
+ // bits from 0600, never add group/other access.)
126
+ fs.writeFileSync(tmp, text, { mode: 0o600 });
127
+ fs.renameSync(tmp, file);
128
+ }
129
+
130
+ let consumeN = 0;
131
+
132
+ /**
133
+ * Consume a file exactly once: rename it away, then read and unlink the
134
+ * renamed copy. Returns null when there is nothing to consume.
135
+ *
136
+ * @param {string} file path to consume
137
+ * @returns {string|null} content, `''` when the renamed copy is unreadable, null when absent
138
+ */
139
+ function consumeFile(file) {
140
+ const tmp = `${file}.consumed-${process.pid}-${++consumeN}`;
141
+ try {
142
+ fs.renameSync(file, tmp);
143
+ } catch {
144
+ return null;
145
+ }
146
+ let text = '';
147
+ try {
148
+ text = fs.readFileSync(tmp, 'utf8');
149
+ } catch {}
150
+ try {
151
+ fs.unlinkSync(tmp);
152
+ } catch {}
153
+ return text;
154
+ }
155
+
156
+ /**
157
+ * Validate an answer payload's shape. Returns the raw decision pair;
158
+ * normalization (including the `'approve'` alias) is `normalizeDecision`'s
159
+ * job. Anything unparsable, or with a missing decision, is malformed.
160
+ *
161
+ * @param {string} text raw answer file content
162
+ * @returns {{ decision: unknown, reason?: unknown } | null} raw pair, or null when malformed
163
+ */
164
+ function parseAnswer(text) {
165
+ let obj;
166
+ try {
167
+ obj = JSON.parse(text);
168
+ } catch {
169
+ return null;
170
+ }
171
+ if (!obj || typeof obj !== 'object') return null;
172
+ const { decision, reason } = /** @type {{ decision?: unknown, reason?: unknown }} */ (obj);
173
+ if (typeof decision !== 'string' || !decision) return null;
174
+ return { decision, reason };
175
+ }
176
+
177
+ /**
178
+ * The one normalization of decisions, applied once wherever a decision
179
+ * enters (an answer file, or an `onAsk` result). The audit log speaks
180
+ * `allow`/`deny`, which is bareguard's vocabulary.
181
+ *
182
+ * @param {{ decision?: unknown, reason?: unknown } | null} input raw decision pair
183
+ * @param {object} [opts]
184
+ * @param {boolean} [opts.approveAlias] accept `'approve'` as an alias of `'allow'` (answer files only)
185
+ * @returns {{ decision: 'allow' | 'deny', reason?: string } | null} normalized, or null when not a decision at all
186
+ */
187
+ export function normalizeDecision(input, { approveAlias = false } = {}) {
188
+ const decision = input?.decision;
189
+ if (decision === 'allow' || (approveAlias && decision === 'approve')) {
190
+ return { decision: 'allow' };
191
+ }
192
+ if (decision === 'deny') {
193
+ const reason = input?.reason;
194
+ return {
195
+ decision: 'deny',
196
+ reason: typeof reason === 'string' && reason ? reason : 'denied',
197
+ };
198
+ }
199
+ return null;
200
+ }
201
+
202
+ /**
203
+ * Create the hold queue. One queue per runtime, enforced by `claimRuntime`
204
+ * in `createProxy` (a second live proxy on the same runtime never starts):
205
+ * on the file channel the queue owns `asks/` and `answers/` for its
206
+ * runtime, clearing both at start and removing its asks on close, so no
207
+ * answer outlives its queue.
208
+ *
209
+ * @param {object} opts
210
+ * @param {(o: Record<string, unknown>) => void} opts.log audit-log writer
211
+ * @param {ShouldHold} [opts.shouldHold] decision function (default: path-substring `match`)
212
+ * @param {string} [opts.match] path substring that parks a request (default impl when `shouldHold` is absent)
213
+ * @param {number|string} [opts.timeoutMs] hold deadline in ms, or `'never'` (default 120000)
214
+ * @param {number} [opts.maxBody] bodies over this are denied at the door, never queued (default 1048576)
215
+ * @param {string|null} [opts.runtime] runtime dir; required for the default file checkpoint (writes `asks/`, polls `answers/`)
216
+ * @param {OnAsk|null} [opts.onAsk] ask seam (bareguard `humanChannel` shape); when present no files are involved
217
+ * @param {number} [opts.pollMs] answer poll interval in ms for the default file checkpoint (default 250, PRD Q9)
218
+ * @param {OnEvent|null} [opts.onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon
219
+ * @param {(entry: object) => void} opts.onApprove forward the parked request upstream
220
+ * @param {(entry: object, reason: string) => void} opts.onDeny refuse the parked request
221
+ * @returns {{ add: (entry: object) => string, 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
222
+ */
223
+ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
224
+ maxBody = 1048576, runtime = null, onAsk = null, pollMs = DEFAULT_POLL_MS,
225
+ onEvent = null, onApprove, onDeny }) {
226
+ // The default IS matchPath: one definition of the path-substring rule (see below).
227
+ const decide = shouldHold ?? (match ? matchPath(match) : () => null);
228
+ /** @returns {number|null} */
229
+ const deadlineMs = () => {
230
+ if (timeoutMs === 'never') return null;
231
+ const ms = timeoutMs ?? 120000;
232
+ return typeof ms === 'number' && Number.isFinite(ms) && ms >= 0 ? ms : 120000;
233
+ };
234
+ if (onAsk != null && typeof onAsk !== 'function') {
235
+ throw new Error('createHolds: onAsk must be a function');
236
+ }
237
+ if (onEvent != null && typeof onEvent !== 'function') {
238
+ throw new Error('createHolds: onEvent must be a function');
239
+ }
240
+ const poll = typeof pollMs === 'number' && Number.isFinite(pollMs) && pollMs > 0
241
+ ? pollMs
242
+ : DEFAULT_POLL_MS;
243
+ // Custom onAsk owns decisions with no files involved; the default IS the
244
+ // file checkpoint and needs a runtime dir for asks/ + answers/.
245
+ const useFiles = onAsk == null;
246
+ if (useFiles && !runtime) {
247
+ throw new Error('createHolds: runtime is required for the default file checkpoint (or pass onAsk)');
248
+ }
249
+ const paths = runtime ? runtimePaths(runtime) : null;
250
+ if (paths) {
251
+ fs.mkdirSync(paths.asksDir, { recursive: true });
252
+ fs.mkdirSync(paths.answersDir, { recursive: true });
253
+ }
254
+ // A dead queue's leftovers must never decide the next queue's holds
255
+ // (ids restart at h1): clear both folders at start, logging one audit
256
+ // line per removed answer.
257
+ if (useFiles && paths) {
258
+ for (const [dir, isAnswers] of /** @type {[string, boolean][]} */ ([[paths.asksDir, false], [paths.answersDir, true]])) {
259
+ let names;
260
+ try {
261
+ names = fs.readdirSync(dir);
262
+ } catch {
263
+ continue;
264
+ }
265
+ for (const name of names) {
266
+ try {
267
+ fs.unlinkSync(path.join(dir, name));
268
+ } catch {
269
+ continue;
270
+ }
271
+ if (isAnswers) {
272
+ log({ ev: 'stale-answer', id: name.endsWith('.json') ? name.slice(0, -'.json'.length) : name, note: 'leftover from a dead queue; removed at start' });
273
+ }
274
+ }
275
+ }
276
+ }
277
+
278
+ let n = 0;
279
+ /** @type {Map<string, object>} */
280
+ const queue = new Map();
281
+
282
+ const pub = (h) => ({
283
+ id: h.id, agent: h.agent, method: h.method, url: h.url, rule: h.note,
284
+ waitingSec: Math.round((Date.now() - h.t0) / 1000),
285
+ });
286
+
287
+ /**
288
+ * Build the decision-ready ask payload for a parked entry.
289
+ *
290
+ * @param {object} entry queue entry
291
+ * @param {number|null} ms hold deadline in ms, or null for never
292
+ * @param {string} rule hold-reason string
293
+ * @returns {AskPayload}
294
+ */
295
+ function askPayload(entry, ms, rule) {
296
+ const body = Buffer.isBuffer(entry.body) ? entry.body : Buffer.from(String(entry.body ?? ''));
297
+ return {
298
+ id: entry.id,
299
+ agent: entry.agent,
300
+ method: entry.method,
301
+ url: entry.url,
302
+ rule,
303
+ // M3 owns letters; everything the queue parks today is irreversible.
304
+ letter: 'x',
305
+ bodyPreview: body.subarray(0, ASK_BODY_LIMIT).toString('utf8'),
306
+ truncated: body.length > ASK_BODY_LIMIT,
307
+ waitingSec: 0,
308
+ // ISO-8601 UTC (not epoch ms): readable in `sbx pending` and logs.
309
+ expiresAt: ms === null ? null : new Date(entry.t0 + ms).toISOString(),
310
+ };
311
+ }
312
+
313
+ function removeAskFile(id) {
314
+ if (!paths) return;
315
+ try {
316
+ fs.unlinkSync(paths.askFile(id));
317
+ } catch {}
318
+ }
319
+
320
+ function settle(id, approved, reason) {
321
+ const h = queue.get(id);
322
+ if (!h) return `unknown ${id}`;
323
+ queue.delete(id);
324
+ if (h.timer) clearTimeout(h.timer);
325
+ removeAskFile(id);
326
+ const decision = approved ? 'allow' : 'deny';
327
+ if (approved) {
328
+ log({ ev: 'decide', id, agent: h.agent, decision, reason: reason || undefined });
329
+ onApprove(h);
330
+ } else {
331
+ log({ ev: 'decide', id, agent: h.agent, decision, reason });
332
+ onDeny(h, reason);
333
+ }
334
+ onEvent?.({ type: 'decided', id, decision, reason: reason || undefined });
335
+ return approved ? `approved ${id}` : `denied ${id}`;
336
+ }
337
+
338
+ /**
339
+ * Park an entry: write the ask file (file channel only) and report the
340
+ * ask. Double-settle is safe: the deadline timer and the answer race,
341
+ * and the loser finds no entry. The file channel never waits here: the
342
+ * single interval settles on answer, the timer denies on deadline.
343
+ * The `onAsk` channel stays a promise per hold.
344
+ *
345
+ * @param {object} entry queue entry
346
+ * @param {number|null} ms hold deadline in ms, or null for never
347
+ * @param {string} rule hold-reason string
348
+ * @returns {Promise<void>}
349
+ */
350
+ async function park(entry, ms, rule) {
351
+ const ask = askPayload(entry, ms, rule);
352
+ if (useFiles && paths) {
353
+ try {
354
+ writeFileAtomic(paths.askFile(entry.id), JSON.stringify(ask));
355
+ } catch (e) {
356
+ const msg = e instanceof Error ? e.message : String(e);
357
+ log({ ev: 'deny', agent: entry.agent, code: 500, note: `ask channel failed: ${msg}` });
358
+ settle(entry.id, false, 'ask channel failed');
359
+ return;
360
+ }
361
+ }
362
+ onEvent?.({ type: 'ask', ask });
363
+ if (!useFiles) {
364
+ /** @type {{ decision?: unknown, reason?: unknown } | null} */
365
+ let raw = null;
366
+ try {
367
+ raw = await onAsk(ask);
368
+ } catch (e) {
369
+ const msg = e instanceof Error ? e.message : String(e);
370
+ raw = { decision: 'deny', reason: `onAsk failed: ${msg}` };
371
+ }
372
+ const norm = normalizeDecision(raw);
373
+ if (norm && norm.decision === 'allow') settle(entry.id, true, '');
374
+ else settle(entry.id, false, norm?.reason ?? 'denied');
375
+ }
376
+ }
377
+
378
+ /**
379
+ * The one answer reader (file channel only): each tick reads `answers/`
380
+ * once, consuming every answer file. A held id settles; anything else is
381
+ * stale (ignored, logged, removed). Malformed answers are ignored and
382
+ * logged; the hold keeps waiting until its deadline.
383
+ *
384
+ * @returns {void}
385
+ */
386
+ function pollAnswers() {
387
+ if (!paths) return;
388
+ let names;
389
+ try {
390
+ names = fs.readdirSync(paths.answersDir);
391
+ } catch {
392
+ return;
393
+ }
394
+ for (const name of names) {
395
+ if (!name.endsWith('.json')) continue;
396
+ const id = name.slice(0, -'.json'.length);
397
+ const text = consumeFile(paths.answerFile(id));
398
+ if (text === null) continue;
399
+ const norm = normalizeDecision(parseAnswer(text), { approveAlias: true });
400
+ if (!norm) {
401
+ log({ ev: 'malformed-answer', id, note: 'ignored; still waiting' });
402
+ continue;
403
+ }
404
+ if (!queue.has(id)) {
405
+ log({ ev: 'stale-answer', id, note: 'unknown or already-settled id; ignored' });
406
+ continue;
407
+ }
408
+ settle(id, norm.decision === 'allow', norm.reason ?? '');
409
+ }
410
+ }
411
+
412
+ const pollTimer = useFiles && paths
413
+ ? setInterval(pollAnswers, poll)
414
+ : null;
415
+ if (pollTimer && typeof pollTimer.unref === 'function') pollTimer.unref();
416
+
417
+ const holds = {
418
+ add({ agent, method, url, headers, body, sock, cres, note }) {
419
+ const id = `h${++n}`;
420
+ const ms = deadlineMs();
421
+ const entry = {
422
+ id, agent, method, url, headers, body, sock, cres, note, t0: Date.now(),
423
+ timer: ms === null ? null
424
+ : setTimeout(() => settle(id, false, 'hold timeout'), ms),
425
+ };
426
+ // Unref: a parked `never` hold must not keep the process alive by itself.
427
+ if (entry.timer?.unref) entry.timer.unref();
428
+ queue.set(id, entry);
429
+ log({ ev: 'hold', id, agent, method, url, reason: note ?? undefined,
430
+ timeoutMs: ms, waiting: queue.size });
431
+ void park(entry, ms, note ?? '');
432
+ return id;
433
+ },
434
+
435
+ // The client went away: drop its holds so no later answer can forward
436
+ // a request nobody is listening for.
437
+ abandon(id) {
438
+ const h = queue.get(id);
439
+ if (!h) return;
440
+ queue.delete(id);
441
+ if (h.timer) clearTimeout(h.timer);
442
+ removeAskFile(id);
443
+ log({ ev: 'hold-abandoned', id, agent: h.agent, method: h.method, url: h.url });
444
+ onDeny(h, 'client gone');
445
+ onEvent?.({ type: 'decided', id, decision: 'deny', reason: 'client gone' });
446
+ },
447
+
448
+ abandonSocket(sock) {
449
+ for (const [id, h] of queue) {
450
+ if (h.sock === sock) holds.abandon(id);
451
+ }
452
+ },
453
+
454
+ decide(req) { return decide(req); },
455
+
456
+ pending() { return [...queue.values()].map(pub); },
457
+
458
+ close() {
459
+ if (pollTimer) clearInterval(pollTimer);
460
+ // settle() removes each ask file: `sbx pending` never lists a dead queue's holds.
461
+ for (const [id] of [...queue]) settle(id, false, 'proxy closing');
462
+ },
463
+ };
464
+
465
+ return holds;
466
+ }
467
+
468
+ /**
469
+ * Default decision: park requests whose path contains `match`.
470
+ *
471
+ * @param {string} match path substring
472
+ * @returns {ShouldHold} decision function
473
+ */
474
+ export function matchPath(match) {
475
+ return (req) => (new URL(req.url).pathname.includes(match) ? `path matches ${match}` : null);
476
+ }
package/src/index.js ADDED
@@ -0,0 +1,5 @@
1
+ // barebox public barrel. Every export with @when appears in primitives.json.
2
+ export { launch } from './launcher.js';
3
+ export { createProxy } from './proxy.js';
4
+ export { run } from './run.js';
5
+ export { diffOverlay, commitOverlay, rollbackOverlay } from './overlay.js';