barebox 0.2.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/CHANGELOG.md +62 -2
- package/README.md +8 -8
- package/barebox.context.md +85 -17
- package/package.json +2 -2
- package/primitives.json +40 -4
- package/src/certs.js +2 -1
- package/src/cli.js +348 -35
- package/src/holds.js +368 -56
- package/src/index.js +2 -0
- package/src/launcher.js +149 -50
- package/src/overlay-walk.js +49 -0
- package/src/overlay.js +1012 -0
- package/src/proxy.js +101 -297
- package/src/run.js +226 -0
- package/src/runtime.js +263 -0
- package/src/wall.js +156 -0
- package/types/certs.d.ts +2 -0
- package/types/holds.d.ts +157 -13
- package/types/index.d.ts +2 -0
- package/types/launcher.d.ts +13 -4
- package/types/overlay-walk.d.ts +1 -0
- package/types/overlay.d.ts +220 -0
- package/types/proxy.d.ts +43 -83
- package/types/run.d.ts +192 -0
- package/types/runtime.d.ts +112 -0
- package/types/wall.d.ts +30 -0
package/src/holds.js
CHANGED
|
@@ -1,25 +1,108 @@
|
|
|
1
1
|
// holds.js — the ONLY writer of the hold queue.
|
|
2
2
|
//
|
|
3
|
-
// A held request parks with its client socket open until
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
|
|
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.
|
|
8
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;
|
|
9
54
|
|
|
10
55
|
/**
|
|
11
56
|
* A parked request, as returned by {@link pending}. Plain objects only —
|
|
12
|
-
* the queue itself never leaves this module.
|
|
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.
|
|
13
60
|
*
|
|
14
61
|
* @typedef {object} HeldRequest
|
|
15
62
|
* @property {string} id hold id (`h<n>`)
|
|
16
63
|
* @property {string} agent agent name (its socket), never `c<n>`
|
|
17
64
|
* @property {string} method HTTP method
|
|
18
65
|
* @property {string} url full URL
|
|
19
|
-
* @property {string}
|
|
66
|
+
* @property {string} rule hold-reason string from the decision function
|
|
20
67
|
* @property {number} waitingSec seconds since the hold parked
|
|
21
68
|
*/
|
|
22
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
|
+
|
|
23
106
|
/**
|
|
24
107
|
* Decide whether a request parks. Return a human-readable reason, or null
|
|
25
108
|
* to forward. M3 plugs the rwxmap + bareguard classifier into this one seam.
|
|
@@ -28,7 +111,100 @@ import fs from 'node:fs';
|
|
|
28
111
|
*/
|
|
29
112
|
|
|
30
113
|
/**
|
|
31
|
-
*
|
|
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.
|
|
32
208
|
*
|
|
33
209
|
* @param {object} opts
|
|
34
210
|
* @param {(o: Record<string, unknown>) => void} opts.log audit-log writer
|
|
@@ -36,52 +212,214 @@ import fs from 'node:fs';
|
|
|
36
212
|
* @param {string} [opts.match] path substring that parks a request (default impl when `shouldHold` is absent)
|
|
37
213
|
* @param {number|string} [opts.timeoutMs] hold deadline in ms, or `'never'` (default 120000)
|
|
38
214
|
* @param {number} [opts.maxBody] bodies over this are denied at the door, never queued (default 1048576)
|
|
39
|
-
* @param {string|null} [opts.
|
|
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
|
|
40
219
|
* @param {(entry: object) => void} opts.onApprove forward the parked request upstream
|
|
41
220
|
* @param {(entry: object, reason: string) => void} opts.onDeny refuse the parked request
|
|
42
|
-
* @returns {{ add: (entry: object) => string, decide: (req: { agent: string, method: string, url: string, headers: Record<string, string | string[] | undefined> }) => string | null,
|
|
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
|
|
43
222
|
*/
|
|
44
223
|
export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
45
|
-
maxBody = 1048576,
|
|
46
|
-
|
|
47
|
-
|
|
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);
|
|
48
228
|
/** @returns {number|null} */
|
|
49
229
|
const deadlineMs = () => {
|
|
50
230
|
if (timeoutMs === 'never') return null;
|
|
51
231
|
const ms = timeoutMs ?? 120000;
|
|
52
232
|
return typeof ms === 'number' && Number.isFinite(ms) && ms >= 0 ? ms : 120000;
|
|
53
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
|
+
}
|
|
54
277
|
|
|
55
278
|
let n = 0;
|
|
56
279
|
/** @type {Map<string, object>} */
|
|
57
280
|
const queue = new Map();
|
|
58
281
|
|
|
59
282
|
const pub = (h) => ({
|
|
60
|
-
id: h.id, agent: h.agent, method: h.method, url: h.url,
|
|
61
|
-
|
|
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),
|
|
62
285
|
});
|
|
63
286
|
|
|
64
|
-
|
|
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) {
|
|
65
321
|
const h = queue.get(id);
|
|
66
322
|
if (!h) return `unknown ${id}`;
|
|
67
323
|
queue.delete(id);
|
|
68
324
|
if (h.timer) clearTimeout(h.timer);
|
|
69
|
-
|
|
70
|
-
|
|
325
|
+
removeAskFile(id);
|
|
326
|
+
const decision = approved ? 'allow' : 'deny';
|
|
327
|
+
if (approved) {
|
|
328
|
+
log({ ev: 'decide', id, agent: h.agent, decision, reason: reason || undefined });
|
|
71
329
|
onApprove(h);
|
|
72
|
-
|
|
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');
|
|
73
375
|
}
|
|
74
|
-
log({ ev: 'decide', id, agent: h.agent, decision: 'deny', reason });
|
|
75
|
-
onDeny(h, reason);
|
|
76
|
-
return `denied ${id}`;
|
|
77
376
|
}
|
|
78
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
|
+
|
|
79
417
|
const holds = {
|
|
80
418
|
add({ agent, method, url, headers, body, sock, cres, note }) {
|
|
81
419
|
const id = `h${++n}`;
|
|
82
420
|
const ms = deadlineMs();
|
|
83
421
|
const entry = {
|
|
84
|
-
id, agent, method, url, headers, body, sock, cres, t0: Date.now(),
|
|
422
|
+
id, agent, method, url, headers, body, sock, cres, note, t0: Date.now(),
|
|
85
423
|
timer: ms === null ? null
|
|
86
424
|
: setTimeout(() => settle(id, false, 'hold timeout'), ms),
|
|
87
425
|
};
|
|
@@ -90,21 +428,21 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
90
428
|
queue.set(id, entry);
|
|
91
429
|
log({ ev: 'hold', id, agent, method, url, reason: note ?? undefined,
|
|
92
430
|
timeoutMs: ms, waiting: queue.size });
|
|
431
|
+
void park(entry, ms, note ?? '');
|
|
93
432
|
return id;
|
|
94
433
|
},
|
|
95
434
|
|
|
96
|
-
|
|
97
|
-
deny(id, reason) { return settle(id, false, reason || 'denied by user'); },
|
|
98
|
-
|
|
99
|
-
// The client went away: drop its holds so no later approve can forward
|
|
435
|
+
// The client went away: drop its holds so no later answer can forward
|
|
100
436
|
// a request nobody is listening for.
|
|
101
437
|
abandon(id) {
|
|
102
438
|
const h = queue.get(id);
|
|
103
439
|
if (!h) return;
|
|
104
440
|
queue.delete(id);
|
|
105
441
|
if (h.timer) clearTimeout(h.timer);
|
|
442
|
+
removeAskFile(id);
|
|
106
443
|
log({ ev: 'hold-abandoned', id, agent: h.agent, method: h.method, url: h.url });
|
|
107
444
|
onDeny(h, 'client gone');
|
|
445
|
+
onEvent?.({ type: 'decided', id, decision: 'deny', reason: 'client gone' });
|
|
108
446
|
},
|
|
109
447
|
|
|
110
448
|
abandonSocket(sock) {
|
|
@@ -116,40 +454,14 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
116
454
|
decide(req) { return decide(req); },
|
|
117
455
|
|
|
118
456
|
pending() { return [...queue.values()].map(pub); },
|
|
119
|
-
size() { return queue.size; },
|
|
120
457
|
|
|
121
458
|
close() {
|
|
122
|
-
|
|
123
|
-
|
|
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');
|
|
124
462
|
},
|
|
125
463
|
};
|
|
126
464
|
|
|
127
|
-
let ctl = null;
|
|
128
|
-
if (controlSocket) {
|
|
129
|
-
try { fs.unlinkSync(controlSocket); } catch {}
|
|
130
|
-
ctl = net.createServer((sock) => {
|
|
131
|
-
let line = '';
|
|
132
|
-
sock.on('data', (ch) => {
|
|
133
|
-
line += ch.toString('latin1');
|
|
134
|
-
const i = line.indexOf('\n');
|
|
135
|
-
if (i < 0) return;
|
|
136
|
-
const [cmd, arg, ...rest] = line.slice(0, i).trim().split(' ');
|
|
137
|
-
let out = '';
|
|
138
|
-
if (cmd === 'pending') out = JSON.stringify(holds.pending());
|
|
139
|
-
else if (cmd === 'approve' && arg) out = holds.approve(arg);
|
|
140
|
-
else if (cmd === 'deny' && arg) out = holds.deny(arg, rest.join(' '));
|
|
141
|
-
else out = 'usage: pending | approve <id> | deny <id> [reason]';
|
|
142
|
-
sock.end(out + '\n');
|
|
143
|
-
});
|
|
144
|
-
sock.on('error', () => {});
|
|
145
|
-
});
|
|
146
|
-
ctl.on('error', () => {});
|
|
147
|
-
ctl.listen(controlSocket, () => {
|
|
148
|
-
// Anyone who can connect can approve payments.
|
|
149
|
-
try { fs.chmodSync(controlSocket, 0o600); } catch {}
|
|
150
|
-
});
|
|
151
|
-
}
|
|
152
|
-
|
|
153
465
|
return holds;
|
|
154
466
|
}
|
|
155
467
|
|
package/src/index.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
// barebox public barrel. Every export with @when appears in primitives.json.
|
|
2
2
|
export { launch } from './launcher.js';
|
|
3
3
|
export { createProxy } from './proxy.js';
|
|
4
|
+
export { run } from './run.js';
|
|
5
|
+
export { diffOverlay, commitOverlay, rollbackOverlay } from './overlay.js';
|