barebox 0.3.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 +80 -0
- package/README.md +21 -22
- package/barebox.context.md +136 -16
- package/package.json +6 -1
- package/primitives.json +1 -1
- package/src/cardscan.js +96 -0
- package/src/certs.js +22 -2
- package/src/cli.js +31 -6
- package/src/config.js +96 -0
- package/src/holds.js +237 -50
- package/src/labels.js +88 -0
- package/src/launcher.js +11 -2
- package/src/overlay.js +54 -2
- package/src/policy.js +138 -0
- package/src/proxy.js +596 -132
- package/src/run.js +40 -73
- package/src/runtime.js +40 -3
- package/src/wall.js +104 -37
- 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 +37 -48
- package/types/labels.d.ts +21 -0
- package/types/launcher.d.ts +3 -1
- package/types/overlay.d.ts +8 -0
- package/types/policy.d.ts +64 -0
- package/types/proxy.d.ts +83 -34
- package/types/run.d.ts +32 -10
- package/types/runtime.d.ts +22 -1
- package/types/wall.d.ts +4 -2
package/src/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
1
|
+
#!/usr/bin/env -S node --max-semi-space-size=1
|
|
2
2
|
// sbx — second-terminal CLI for the hold queue (M2.5 file channel):
|
|
3
3
|
// sbx pending | approve <id> | deny <id> [reason]
|
|
4
4
|
// Reads `<runtime>/asks/<id>.json`, answers by atomically writing
|
|
@@ -6,6 +6,9 @@
|
|
|
6
6
|
// a partial). The runtime comes from SBX_RUNTIME only; there is no
|
|
7
7
|
// cwd-relative default.
|
|
8
8
|
//
|
|
9
|
+
// Settings (mode, holdTimeoutSec, heldBodyMaxMB, localLlm) come from the one config file, see config.js;
|
|
10
|
+
// a flag beats the file. A bad file is a usage-class error (exit 2).
|
|
11
|
+
//
|
|
9
12
|
// sbx run [--mode ask|auto|trust] [--json] [--overlay] -- <cmd> [...]
|
|
10
13
|
// Runs one sandboxed agent start-to-finish in this process (project = cwd).
|
|
11
14
|
// The runtime is SBX_RUNTIME when set, else a short temp dir (printed to
|
|
@@ -27,10 +30,13 @@
|
|
|
27
30
|
import fs from 'node:fs';
|
|
28
31
|
import path from 'node:path';
|
|
29
32
|
import { parseArgs } from 'node:util';
|
|
33
|
+
import { resolveConfig } from './config.js';
|
|
34
|
+
import { loadLabels } from './labels.js';
|
|
35
|
+
import { MODES } from './policy.js';
|
|
30
36
|
import { writeFileAtomic } from './holds.js';
|
|
31
37
|
import { run as sandboxRun } from './run.js';
|
|
32
38
|
import { diffOverlay, commitOverlay, rollbackOverlay } from './overlay.js';
|
|
33
|
-
import { assertAgentName, createRuntime, runtimePaths, runtimeLive, safe } from './runtime.js';
|
|
39
|
+
import { assertAgentName, createRuntime, runtimePaths, runtimeLive, safe, shellQuote } from './runtime.js';
|
|
34
40
|
|
|
35
41
|
const USAGE = 'usage: sbx [--help] | pending | approve <id> | deny <id> [reason] | diff [--agent <name>] | commit [--agent <name>] [--skip-conflicts] | rollback [--agent <name>] | run [--mode ask|auto|trust] [--json] [--overlay] -- <cmd> [...]';
|
|
36
42
|
|
|
@@ -157,8 +163,25 @@ async function run(args) {
|
|
|
157
163
|
} catch {
|
|
158
164
|
usage();
|
|
159
165
|
}
|
|
160
|
-
|
|
161
|
-
|
|
166
|
+
if (values.mode !== undefined && !MODES.includes(values.mode)) usage();
|
|
167
|
+
/** @type {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number }} */
|
|
168
|
+
let cfg;
|
|
169
|
+
try {
|
|
170
|
+
cfg = resolveConfig({ mode: values.mode });
|
|
171
|
+
} catch (e) {
|
|
172
|
+
err(e instanceof Error ? e.message : String(e));
|
|
173
|
+
process.exit(2);
|
|
174
|
+
}
|
|
175
|
+
const { mode } = cfg;
|
|
176
|
+
/** @type {ReturnType<typeof loadLabels>} */
|
|
177
|
+
let labels;
|
|
178
|
+
try {
|
|
179
|
+
labels = loadLabels(cfg);
|
|
180
|
+
} catch (e) {
|
|
181
|
+
err(e instanceof Error ? e.message : String(e));
|
|
182
|
+
process.exit(2);
|
|
183
|
+
}
|
|
184
|
+
const timeoutMs = cfg.holdTimeoutSec === 'never' ? 'never' : Number(cfg.holdTimeoutSec) * 1000;
|
|
162
185
|
if (!command.length) usage();
|
|
163
186
|
const json = values.json ?? false;
|
|
164
187
|
const overlay = values.overlay ?? false;
|
|
@@ -179,7 +202,7 @@ async function run(args) {
|
|
|
179
202
|
if (json) out(JSON.stringify({ ev: 'decided', id: c.id, decision: c.decision, reason: c.reason }));
|
|
180
203
|
else out(`decided ${c.id} ${c.decision}${c.reason ? ` (${c.reason})` : ''}`);
|
|
181
204
|
};
|
|
182
|
-
err(`runtime ${runtime} (answer with: SBX_RUNTIME=${runtime} sbx approve <id>)`);
|
|
205
|
+
err(`runtime ${runtime} (answer with: SBX_RUNTIME=${shellQuote(runtime)} sbx approve <id>)`);
|
|
183
206
|
/** @type {{ exit: number, diff: { path: string }[] } | null} */
|
|
184
207
|
let result = null;
|
|
185
208
|
try {
|
|
@@ -187,7 +210,9 @@ async function run(args) {
|
|
|
187
210
|
const extraIgnore = (process.env.SBX_OVERLAY_IGNORE ?? '').split(',')
|
|
188
211
|
.map((s) => s.trim()).filter(Boolean);
|
|
189
212
|
result = await sandboxRun({
|
|
190
|
-
runtime, proj: process.cwd(), command, mode,
|
|
213
|
+
runtime, proj: process.cwd(), command, mode, timeoutMs,
|
|
214
|
+
allowLocal: cfg.localLlm, labels,
|
|
215
|
+
...(cfg.heldBodyMaxMB ? { heldBodyMaxBytes: cfg.heldBodyMaxMB * 1048576 } : {}),
|
|
191
216
|
unsafeTestOnly: { allowLoopback: process.env.SBX_UNSAFE_TEST_ALLOW_LOOPBACK === '1' },
|
|
192
217
|
overlay,
|
|
193
218
|
...(extraIgnore.length ? { overlayIgnore: ['node_modules', ...extraIgnore] } : {}),
|
package/src/config.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// barebox's one config file: `${XDG_CONFIG_HOME:-$HOME/.config}/barebox/config.json`.
|
|
2
|
+
// Only the CLI reads it; library callers (`run`, `createProxy`) pass options.
|
|
3
|
+
// Later modules add keys here, not a second file. The sandbox never sees it
|
|
4
|
+
// (the launcher masks the directory this file lives in).
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { MODES } from './policy.js';
|
|
9
|
+
|
|
10
|
+
const DEFAULTS = { mode: 'auto', holdTimeoutSec: 120, localLlm: [], labels: [], tenants: {} };
|
|
11
|
+
|
|
12
|
+
/** One `host:port` (host without a colon, port 1-65535). @param {unknown} v @returns {boolean} */
|
|
13
|
+
const isHostPort = (v) => {
|
|
14
|
+
if (typeof v !== 'string') return false;
|
|
15
|
+
const m = /^([^\s:/@]+):(\d{1,5})$/.exec(v);
|
|
16
|
+
return m !== null && Number(m[2]) >= 1 && Number(m[2]) <= 65535;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/** An absolute http(s) URL. @param {unknown} v @returns {boolean} */
|
|
20
|
+
const isHttpUrl = (v) => {
|
|
21
|
+
if (typeof v !== 'string') return false;
|
|
22
|
+
try { return ['http:', 'https:'].includes(new URL(v).protocol); } catch { return false; }
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** Validators by key; each returns an error string or null. */
|
|
26
|
+
const KEYS = {
|
|
27
|
+
mode: (v) => (MODES.includes(v) ? null : `must be one of ${MODES.join(', ')}`),
|
|
28
|
+
holdTimeoutSec: (v) => (v === 'never' || (Number.isInteger(v) && v > 0)
|
|
29
|
+
? null : 'must be a positive integer or "never"'),
|
|
30
|
+
heldBodyMaxMB: (v) => (Number.isInteger(v) && v > 0 ? null : 'must be a positive integer'),
|
|
31
|
+
localLlm: (v) => (Array.isArray(v) && v.every(isHostPort)
|
|
32
|
+
? null : 'must be an array of "host:port" strings (port 1-65535)'),
|
|
33
|
+
labels: (v) => (Array.isArray(v) && v.every((x) => typeof x === 'string' && x !== '')
|
|
34
|
+
? null : 'must be an array of folder paths (strings)'),
|
|
35
|
+
tenants: (v) => (v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
36
|
+
&& Object.values(v).every((a) => Array.isArray(a) && a.length > 0 && a.every(isHttpUrl))
|
|
37
|
+
? null : 'must be an object of vendor -> non-empty array of http(s) URLs'),
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Where the config file lives.
|
|
42
|
+
*
|
|
43
|
+
* @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
|
|
44
|
+
* @returns {string} absolute path of `config.json`
|
|
45
|
+
*/
|
|
46
|
+
export function configPath(env = process.env) {
|
|
47
|
+
const base = env.XDG_CONFIG_HOME || path.join(env.HOME || os.homedir(), '.config');
|
|
48
|
+
return path.join(base, 'barebox', 'config.json');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Read the config file over the defaults. No file means defaults.
|
|
53
|
+
*
|
|
54
|
+
* @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
|
|
55
|
+
* @returns {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number }} effective settings (`heldBodyMaxMB` absent means the library default)
|
|
56
|
+
* @throws {Error} naming the file (and the key) on invalid JSON, an unknown key or a bad value
|
|
57
|
+
*/
|
|
58
|
+
export function loadConfig(env = process.env) {
|
|
59
|
+
const file = configPath(env);
|
|
60
|
+
let text;
|
|
61
|
+
try {
|
|
62
|
+
text = fs.readFileSync(file, 'utf8');
|
|
63
|
+
} catch (e) {
|
|
64
|
+
if (/** @type {NodeJS.ErrnoException} */ (e).code === 'ENOENT') return { ...DEFAULTS };
|
|
65
|
+
throw new Error(`${file}: ${e instanceof Error ? e.message : String(e)}`);
|
|
66
|
+
}
|
|
67
|
+
let data;
|
|
68
|
+
try {
|
|
69
|
+
data = JSON.parse(text);
|
|
70
|
+
} catch (e) {
|
|
71
|
+
throw new Error(`${file}: invalid JSON (${e instanceof Error ? e.message : String(e)})`);
|
|
72
|
+
}
|
|
73
|
+
if (data === null || typeof data !== 'object' || Array.isArray(data)) {
|
|
74
|
+
throw new Error(`${file}: must be a JSON object`);
|
|
75
|
+
}
|
|
76
|
+
for (const [k, v] of Object.entries(data)) {
|
|
77
|
+
if (!Object.hasOwn(KEYS, k)) throw new Error(`${file}: unknown key "${k}"`);
|
|
78
|
+
const bad = KEYS[/** @type {keyof typeof KEYS} */ (k)](v);
|
|
79
|
+
if (bad) throw new Error(`${file}: key "${k}" ${bad}`);
|
|
80
|
+
}
|
|
81
|
+
return { ...DEFAULTS, ...data };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Settings for one `sbx run`: a CLI flag beats the file, the file beats the default.
|
|
86
|
+
*
|
|
87
|
+
* @param {object} [flags] values given on the command line
|
|
88
|
+
* @param {string} [flags.mode] `--mode`
|
|
89
|
+
* @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
|
|
90
|
+
* @returns {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number }} effective settings (`heldBodyMaxMB` absent means the library default)
|
|
91
|
+
* @throws {Error} as {@link loadConfig}
|
|
92
|
+
*/
|
|
93
|
+
export function resolveConfig(flags = {}, env = process.env) {
|
|
94
|
+
const cfg = loadConfig(env);
|
|
95
|
+
return { ...cfg, ...(flags.mode !== undefined ? { mode: flags.mode } : {}) };
|
|
96
|
+
}
|
package/src/holds.js
CHANGED
|
@@ -32,29 +32,53 @@
|
|
|
32
32
|
// (the hold-reason string), `letter`, `bodyPreview` + `truncated`,
|
|
33
33
|
// `waitingSec` (0 at park; readers use the file mtime for a live value),
|
|
34
34
|
// `expiresAt` (ISO-8601 UTC string, or null when `timeoutMs: 'never'`).
|
|
35
|
-
// `
|
|
36
|
-
//
|
|
37
|
-
//
|
|
35
|
+
// `rule` and `letter` come from the gate's ask (`rwx.ask`, `flags.cardLike`,
|
|
36
|
+
// ...; the matched rwx letter, `'x'` when the ask names none): the queue only
|
|
37
|
+
// parks what bareguard's `humanChannel` hands it. Headers are excluded from the
|
|
38
38
|
// payload (they carry Authorization secrets); the body preview is capped at
|
|
39
|
-
// ASK_BODY_LIMIT bytes
|
|
40
|
-
// redaction takes over
|
|
39
|
+
// ASK_BODY_LIMIT bytes with card numbers masked (`bodyPreview`) — M3's
|
|
40
|
+
// bareguard `secrets` redaction takes over the rest.
|
|
41
|
+
//
|
|
42
|
+
// A held request's body lives on disk, never whole in memory: the proxy
|
|
43
|
+
// spools it to `<runtime>/held/<id>` and this queue only keeps the preview
|
|
44
|
+
// and byte count. The file ends with the hold: deny, timeout, abandon and
|
|
45
|
+
// close delete it here (`dropBody`); an approve hands it to the proxy, which
|
|
46
|
+
// deletes it once the upstream has read it.
|
|
41
47
|
//
|
|
42
48
|
// Answer payload (`answers/<id>.json`): `{ decision: 'allow' | 'deny',
|
|
43
49
|
// reason? }`. `'approve'` is accepted as an alias of `'allow'`. Writers
|
|
44
50
|
// must write atomically (tmp file + rename); readers never see partials.
|
|
45
51
|
import fs from 'node:fs';
|
|
46
52
|
import path from 'node:path';
|
|
47
|
-
import { runtimePaths } from './runtime.js';
|
|
53
|
+
import { ensurePrivateDir, runtimePaths } from './runtime.js';
|
|
54
|
+
import { maskCards } from './cardscan.js';
|
|
48
55
|
|
|
49
56
|
/** Body preview cap for `asks/<id>.json` (bytes). */
|
|
50
57
|
export const ASK_BODY_LIMIT = 4096;
|
|
51
58
|
|
|
59
|
+
/** Default cap on a held body (bytes): over it the request is denied at the door. */
|
|
60
|
+
export const DEFAULT_HOLD_MAX_BODY = 52428800;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The one body preview, for the ask file: the first
|
|
64
|
+
* ASK_BODY_LIMIT bytes as utf8, with card numbers masked.
|
|
65
|
+
*
|
|
66
|
+
* @param {Buffer} head the body's first bytes (anything past ASK_BODY_LIMIT is ignored)
|
|
67
|
+
* @returns {string} masked preview
|
|
68
|
+
*/
|
|
69
|
+
export function bodyPreview(head) {
|
|
70
|
+
return maskCards(head.subarray(0, ASK_BODY_LIMIT).toString('utf8'));
|
|
71
|
+
}
|
|
72
|
+
|
|
52
73
|
/** Default answer poll interval in ms (PRD Q9). */
|
|
53
74
|
export const DEFAULT_POLL_MS = 250;
|
|
54
75
|
|
|
76
|
+
/** At most this many held requests wait in line per agent; the next is refused. */
|
|
77
|
+
const MAX_WAITING_PER_AGENT = 16;
|
|
78
|
+
|
|
55
79
|
/**
|
|
56
80
|
* A parked request, as returned by {@link pending}. Plain objects only —
|
|
57
|
-
* the queue itself never leaves this module. No body: returning whole
|
|
81
|
+
* the queue itself never leaves this module. No body: returning whole
|
|
58
82
|
* bodies from a status call is never needed, and the ask payload in
|
|
59
83
|
* `asks/<id>.json` carries the preview.
|
|
60
84
|
*
|
|
@@ -63,7 +87,7 @@ export const DEFAULT_POLL_MS = 250;
|
|
|
63
87
|
* @property {string} agent agent name (its socket), never `c<n>`
|
|
64
88
|
* @property {string} method HTTP method
|
|
65
89
|
* @property {string} url full URL
|
|
66
|
-
* @property {string} rule
|
|
90
|
+
* @property {string} rule the gate's ask rule (hold reason)
|
|
67
91
|
* @property {number} waitingSec seconds since the hold parked
|
|
68
92
|
*/
|
|
69
93
|
|
|
@@ -89,9 +113,9 @@ export const DEFAULT_POLL_MS = 250;
|
|
|
89
113
|
* @property {string} agent agent name (its socket)
|
|
90
114
|
* @property {string} method HTTP method
|
|
91
115
|
* @property {string} url full URL
|
|
92
|
-
* @property {string} rule
|
|
93
|
-
* @property {string} letter
|
|
94
|
-
* @property {string} bodyPreview request body preview, utf8, capped at ASK_BODY_LIMIT bytes
|
|
116
|
+
* @property {string} rule the gate's ask rule
|
|
117
|
+
* @property {string} letter the matched rwx letter, `'x'` when the ask names none
|
|
118
|
+
* @property {string} bodyPreview request body preview, utf8, capped at ASK_BODY_LIMIT bytes, card numbers masked
|
|
95
119
|
* @property {boolean} truncated true when the body exceeded ASK_BODY_LIMIT
|
|
96
120
|
* @property {number} waitingSec 0 at park; readers use the file mtime for a live value
|
|
97
121
|
* @property {string|null} expiresAt ISO-8601 UTC deadline, or null when `timeoutMs: 'never'`
|
|
@@ -103,13 +127,6 @@ export const DEFAULT_POLL_MS = 250;
|
|
|
103
127
|
* @typedef {(ask: AskPayload) => Promise<{ decision: string, reason?: string }>} OnAsk
|
|
104
128
|
*/
|
|
105
129
|
|
|
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
130
|
/**
|
|
114
131
|
* Atomic write: tmp file + rename, so readers never see a partial payload.
|
|
115
132
|
*
|
|
@@ -204,27 +221,25 @@ export function normalizeDecision(input, { approveAlias = false } = {}) {
|
|
|
204
221
|
* in `createProxy` (a second live proxy on the same runtime never starts):
|
|
205
222
|
* on the file channel the queue owns `asks/` and `answers/` for its
|
|
206
223
|
* runtime, clearing both at start and removing its asks on close, so no
|
|
207
|
-
* answer outlives its queue.
|
|
224
|
+
* answer outlives its queue. One parked request per agent: `reserve` hands
|
|
225
|
+
* out the agent's hold slot before a held body is read, and the slot passes
|
|
226
|
+
* to the next waiter when the parked entry leaves by any path.
|
|
208
227
|
*
|
|
209
228
|
* @param {object} opts
|
|
210
229
|
* @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
230
|
* @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
|
|
231
|
+
* @param {number} [opts.maxBody] bodies over this are denied at the door, never queued (default 52428800)
|
|
215
232
|
* @param {string|null} [opts.runtime] runtime dir; required for the default file checkpoint (writes `asks/`, polls `answers/`)
|
|
216
233
|
* @param {OnAsk|null} [opts.onAsk] ask seam (bareguard `humanChannel` shape); when present no files are involved
|
|
217
234
|
* @param {number} [opts.pollMs] answer poll interval in ms for the default file checkpoint (default 250, PRD Q9)
|
|
218
235
|
* @param {OnEvent|null} [opts.onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon
|
|
219
236
|
* @param {(entry: object) => void} opts.onApprove forward the parked request upstream
|
|
220
237
|
* @param {(entry: object, reason: string) => void} opts.onDeny refuse the parked request
|
|
221
|
-
* @returns {{ add: (entry: object) => string,
|
|
238
|
+
* @returns {{ add: (entry: object) => string|null, dropBody: (id: string) => void, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string) => void }) => { state: 'now'|'queued'|'full', id: string, arrivedAt: number, cancel: () => void }, abandon: (id: string) => void, abandonSocket: (sock: object) => void, pending: () => HeldRequest[], close: () => void }} queue handle
|
|
222
239
|
*/
|
|
223
|
-
export function createHolds({ log,
|
|
224
|
-
maxBody =
|
|
240
|
+
export function createHolds({ log, timeoutMs = 120000,
|
|
241
|
+
maxBody = DEFAULT_HOLD_MAX_BODY, runtime = null, onAsk = null, pollMs = DEFAULT_POLL_MS,
|
|
225
242
|
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
243
|
/** @returns {number|null} */
|
|
229
244
|
const deadlineMs = () => {
|
|
230
245
|
if (timeoutMs === 'never') return null;
|
|
@@ -248,8 +263,15 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
248
263
|
}
|
|
249
264
|
const paths = runtime ? runtimePaths(runtime) : null;
|
|
250
265
|
if (paths) {
|
|
251
|
-
|
|
252
|
-
|
|
266
|
+
ensurePrivateDir(paths.asksDir);
|
|
267
|
+
ensurePrivateDir(paths.answersDir);
|
|
268
|
+
ensurePrivateDir(paths.heldDir);
|
|
269
|
+
// Held bodies of a dead queue are orphans (ids restart at h1).
|
|
270
|
+
try {
|
|
271
|
+
for (const name of fs.readdirSync(paths.heldDir)) {
|
|
272
|
+
try { fs.unlinkSync(path.join(paths.heldDir, name)); } catch {}
|
|
273
|
+
}
|
|
274
|
+
} catch {}
|
|
253
275
|
}
|
|
254
276
|
// A dead queue's leftovers must never decide the next queue's holds
|
|
255
277
|
// (ids restart at h1): clear both folders at start, logging one audit
|
|
@@ -278,6 +300,65 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
278
300
|
let n = 0;
|
|
279
301
|
/** @type {Map<string, object>} */
|
|
280
302
|
const queue = new Map();
|
|
303
|
+
/**
|
|
304
|
+
* One hold slot per agent: `holder` is the reservation holding it (or the
|
|
305
|
+
* parked entry's marker), `line` the FIFO of waiting reservation handles.
|
|
306
|
+
*
|
|
307
|
+
* @type {Map<string, { holder: object|null, line: Array<object> }>}
|
|
308
|
+
*/
|
|
309
|
+
const slots = new Map();
|
|
310
|
+
/** Internal reserve state by returned handle identity. @type {WeakMap<object, { agent: string, onReady: () => void, onExpire: (reason: string) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean, id: string }>} */
|
|
311
|
+
const handleState = new WeakMap();
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* The one expiry path for every reservation timer: mark it done, take it
|
|
315
|
+
* out of the line or hand its slot to the next waiter (whose own timer
|
|
316
|
+
* keeps running from its arrival), then expire it. Once.
|
|
317
|
+
*
|
|
318
|
+
* @param {string} agent agent name
|
|
319
|
+
* @param {object} handle the reservation's handle
|
|
320
|
+
* @param {string} reason expiry reason
|
|
321
|
+
* @returns {void}
|
|
322
|
+
*/
|
|
323
|
+
function expireReservation(agent, handle, reason) {
|
|
324
|
+
const st = handleState.get(handle);
|
|
325
|
+
if (!st || st.done) return;
|
|
326
|
+
st.done = true;
|
|
327
|
+
st.timer = null;
|
|
328
|
+
const s = slots.get(agent);
|
|
329
|
+
if (s) {
|
|
330
|
+
if (s.holder === handle) {
|
|
331
|
+
releaseSlot(agent);
|
|
332
|
+
} else {
|
|
333
|
+
const i = s.line.indexOf(handle);
|
|
334
|
+
if (i >= 0) s.line.splice(i, 1);
|
|
335
|
+
if (!s.holder && s.line.length === 0) slots.delete(agent);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
st.onExpire(reason);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Drop the current holder and hand the slot to the next waiter in line,
|
|
343
|
+
* or forget the agent when nobody waits. A promoted waiter keeps its own
|
|
344
|
+
* arrival timer: nothing here arms, clears or resets one.
|
|
345
|
+
*
|
|
346
|
+
* @param {string} agent agent name
|
|
347
|
+
* @returns {void}
|
|
348
|
+
*/
|
|
349
|
+
function releaseSlot(agent) {
|
|
350
|
+
const s = slots.get(agent);
|
|
351
|
+
if (!s) return;
|
|
352
|
+
s.holder = null;
|
|
353
|
+
const next = s.line.shift();
|
|
354
|
+
if (!next) {
|
|
355
|
+
slots.delete(agent);
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
s.holder = next;
|
|
359
|
+
const hst = handleState.get(next);
|
|
360
|
+
if (hst) hst.onReady();
|
|
361
|
+
}
|
|
281
362
|
|
|
282
363
|
const pub = (h) => ({
|
|
283
364
|
id: h.id, agent: h.agent, method: h.method, url: h.url, rule: h.note,
|
|
@@ -293,17 +374,15 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
293
374
|
* @returns {AskPayload}
|
|
294
375
|
*/
|
|
295
376
|
function askPayload(entry, ms, rule) {
|
|
296
|
-
const body = Buffer.isBuffer(entry.body) ? entry.body : Buffer.from(String(entry.body ?? ''));
|
|
297
377
|
return {
|
|
298
378
|
id: entry.id,
|
|
299
379
|
agent: entry.agent,
|
|
300
380
|
method: entry.method,
|
|
301
381
|
url: entry.url,
|
|
302
382
|
rule,
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
truncated: body.length > ASK_BODY_LIMIT,
|
|
383
|
+
letter: entry.letter ?? 'x',
|
|
384
|
+
bodyPreview: entry.preview,
|
|
385
|
+
truncated: entry.bodyBytes > ASK_BODY_LIMIT,
|
|
307
386
|
waitingSec: 0,
|
|
308
387
|
// ISO-8601 UTC (not epoch ms): readable in `sbx pending` and logs.
|
|
309
388
|
expiresAt: ms === null ? null : new Date(entry.t0 + ms).toISOString(),
|
|
@@ -317,17 +396,31 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
317
396
|
} catch {}
|
|
318
397
|
}
|
|
319
398
|
|
|
399
|
+
/**
|
|
400
|
+
* The one deleter of a held body file (the proxy calls it too, after an
|
|
401
|
+
* approved upstream has read it, or when a reservation never parks).
|
|
402
|
+
*
|
|
403
|
+
* @param {string} id hold id
|
|
404
|
+
* @returns {void}
|
|
405
|
+
*/
|
|
406
|
+
function dropBody(id) {
|
|
407
|
+
if (!paths) return;
|
|
408
|
+
try { fs.unlinkSync(paths.heldFile(id)); } catch {}
|
|
409
|
+
}
|
|
410
|
+
|
|
320
411
|
function settle(id, approved, reason) {
|
|
321
412
|
const h = queue.get(id);
|
|
322
413
|
if (!h) return `unknown ${id}`;
|
|
323
414
|
queue.delete(id);
|
|
324
415
|
if (h.timer) clearTimeout(h.timer);
|
|
416
|
+
if (h.slot) releaseSlot(h.agent);
|
|
325
417
|
removeAskFile(id);
|
|
326
418
|
const decision = approved ? 'allow' : 'deny';
|
|
327
419
|
if (approved) {
|
|
328
420
|
log({ ev: 'decide', id, agent: h.agent, decision, reason: reason || undefined });
|
|
329
421
|
onApprove(h);
|
|
330
422
|
} else {
|
|
423
|
+
dropBody(id);
|
|
331
424
|
log({ ev: 'decide', id, agent: h.agent, decision, reason });
|
|
332
425
|
onDeny(h, reason);
|
|
333
426
|
}
|
|
@@ -415,23 +508,112 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
415
508
|
if (pollTimer && typeof pollTimer.unref === 'function') pollTimer.unref();
|
|
416
509
|
|
|
417
510
|
const holds = {
|
|
418
|
-
|
|
419
|
-
|
|
511
|
+
/**
|
|
512
|
+
* Park a held request. With `slot` (from `reserve`) the parked entry
|
|
513
|
+
* takes over that slot, clearing the reservation's timer; with
|
|
514
|
+
* `arrivedAt` the deadline counts from arrival, not from now. A
|
|
515
|
+
* finished slot (expired, cancelled, closed, or no longer the holder)
|
|
516
|
+
* parks nothing and returns `null`. Without `slot`, parks exactly as
|
|
517
|
+
* before, without limit.
|
|
518
|
+
*
|
|
519
|
+
* The entry carries the masked `preview` and the full `bodyBytes`, never
|
|
520
|
+
* the body itself (the proxy spooled it to `heldFile(id)`). `finish` is
|
|
521
|
+
* the proxy's resolver for the request's pending ask: the queue never
|
|
522
|
+
* calls it directly, `onApprove` / `onDeny` do.
|
|
523
|
+
*
|
|
524
|
+
* @param {object} entry queue entry
|
|
525
|
+
* @returns {string|null} hold id, or null for a finished slot
|
|
526
|
+
*/
|
|
527
|
+
add({ agent, method, url, preview = '', bodyBytes = 0, sock, note, letter, finish, slot, arrivedAt }) {
|
|
528
|
+
const hst = typeof slot === 'object' && slot !== null ? handleState.get(slot) : undefined;
|
|
529
|
+
const s = slots.get(agent);
|
|
530
|
+
if (slot && (!hst || hst.done || !s || s.holder !== slot)) return null;
|
|
531
|
+
const id = hst?.id ?? `h${++n}`;
|
|
420
532
|
const ms = deadlineMs();
|
|
533
|
+
const t0 = typeof arrivedAt === 'number' ? arrivedAt : Date.now();
|
|
421
534
|
const entry = {
|
|
422
|
-
id, agent, method, url,
|
|
535
|
+
id, agent, method, url, preview, bodyBytes, sock, note, letter, finish, t0,
|
|
536
|
+
slot: null,
|
|
423
537
|
timer: ms === null ? null
|
|
424
|
-
: setTimeout(() => settle(id, false, 'hold timeout'), ms),
|
|
538
|
+
: setTimeout(() => settle(id, false, 'hold timeout'), Math.max(0, ms - (Date.now() - t0))),
|
|
425
539
|
};
|
|
426
540
|
// Unref: a parked `never` hold must not keep the process alive by itself.
|
|
427
541
|
if (entry.timer?.unref) entry.timer.unref();
|
|
542
|
+
if (slot && hst && s && s.holder === slot) {
|
|
543
|
+
if (hst.timer) clearTimeout(hst.timer);
|
|
544
|
+
hst.timer = null;
|
|
545
|
+
hst.consumed = true;
|
|
546
|
+
s.holder = { parked: id };
|
|
547
|
+
entry.slot = slot;
|
|
548
|
+
}
|
|
428
549
|
queue.set(id, entry);
|
|
429
550
|
log({ ev: 'hold', id, agent, method, url, reason: note ?? undefined,
|
|
430
|
-
timeoutMs: ms, waiting: queue.size });
|
|
551
|
+
timeoutMs: ms, waiting: queue.size, queued: s ? s.line.length : 0 });
|
|
431
552
|
void park(entry, ms, note ?? '');
|
|
432
553
|
return id;
|
|
433
554
|
},
|
|
434
555
|
|
|
556
|
+
/**
|
|
557
|
+
* Ask for this agent's hold slot before reading a held request's body.
|
|
558
|
+
* @param {string} agent
|
|
559
|
+
* @param {{ onReady: () => void, onExpire: (reason: string) => void }} cbs
|
|
560
|
+
* The handle's `id` is the id its hold will have (empty when `full`), so
|
|
561
|
+
* the body file can be named before the hold parks.
|
|
562
|
+
* @returns {{ state: 'now'|'queued'|'full', id: string, arrivedAt: number, cancel: () => void }}
|
|
563
|
+
*/
|
|
564
|
+
reserve(agent, { onReady, onExpire }) {
|
|
565
|
+
const arrivedAt = Date.now();
|
|
566
|
+
// Internal slot state, keyed by the returned handle's identity: `add`
|
|
567
|
+
// receives that same object as `slot`, so holder comparisons use it.
|
|
568
|
+
// The one deadline timer lives here, armed below for 'now' and
|
|
569
|
+
// 'queued' alike; expiry runs through `expireReservation` only.
|
|
570
|
+
/** @type {{ agent: string, onReady: () => void, onExpire: (reason: string) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean, id: string }} */
|
|
571
|
+
const st = { agent, onReady, onExpire, timer: null, consumed: false, done: false, id: '' };
|
|
572
|
+
const s0 = slots.get(agent);
|
|
573
|
+
/** @type {'now'|'queued'|'full'} */
|
|
574
|
+
const state = !s0 ? 'now' : (s0.line.length >= MAX_WAITING_PER_AGENT ? 'full' : 'queued');
|
|
575
|
+
if (state !== 'full') st.id = `h${++n}`;
|
|
576
|
+
const handle = {
|
|
577
|
+
state,
|
|
578
|
+
id: st.id,
|
|
579
|
+
arrivedAt,
|
|
580
|
+
cancel() {
|
|
581
|
+
if (st.done) return;
|
|
582
|
+
st.done = true;
|
|
583
|
+
if (st.timer) clearTimeout(st.timer);
|
|
584
|
+
st.timer = null;
|
|
585
|
+
if (st.consumed) return;
|
|
586
|
+
const s = slots.get(agent);
|
|
587
|
+
if (!s) return;
|
|
588
|
+
if (s.holder === handle) {
|
|
589
|
+
releaseSlot(agent);
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
const i = s.line.indexOf(handle);
|
|
593
|
+
if (i >= 0) {
|
|
594
|
+
s.line.splice(i, 1);
|
|
595
|
+
if (!s.holder && s.line.length === 0) slots.delete(agent);
|
|
596
|
+
}
|
|
597
|
+
},
|
|
598
|
+
};
|
|
599
|
+
handleState.set(handle, st);
|
|
600
|
+
if (state === 'now') {
|
|
601
|
+
slots.set(agent, { holder: handle, line: [] });
|
|
602
|
+
} else if (state === 'full') {
|
|
603
|
+
log({ ev: 'hold-queue-full', agent });
|
|
604
|
+
return handle;
|
|
605
|
+
} else {
|
|
606
|
+
if (!s0) throw new Error(`reserve: no slot record for ${agent}`);
|
|
607
|
+
s0.line.push(handle);
|
|
608
|
+
}
|
|
609
|
+
const ms = deadlineMs();
|
|
610
|
+
if (ms !== null) {
|
|
611
|
+
st.timer = setTimeout(() => expireReservation(agent, handle, 'hold timeout'), ms);
|
|
612
|
+
if (st.timer.unref) st.timer.unref();
|
|
613
|
+
}
|
|
614
|
+
return handle;
|
|
615
|
+
},
|
|
616
|
+
|
|
435
617
|
// The client went away: drop its holds so no later answer can forward
|
|
436
618
|
// a request nobody is listening for.
|
|
437
619
|
abandon(id) {
|
|
@@ -439,7 +621,9 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
439
621
|
if (!h) return;
|
|
440
622
|
queue.delete(id);
|
|
441
623
|
if (h.timer) clearTimeout(h.timer);
|
|
624
|
+
if (h.slot) releaseSlot(h.agent);
|
|
442
625
|
removeAskFile(id);
|
|
626
|
+
dropBody(id);
|
|
443
627
|
log({ ev: 'hold-abandoned', id, agent: h.agent, method: h.method, url: h.url });
|
|
444
628
|
onDeny(h, 'client gone');
|
|
445
629
|
onEvent?.({ type: 'decided', id, decision: 'deny', reason: 'client gone' });
|
|
@@ -451,12 +635,25 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
451
635
|
}
|
|
452
636
|
},
|
|
453
637
|
|
|
454
|
-
|
|
638
|
+
dropBody,
|
|
455
639
|
|
|
456
640
|
pending() { return [...queue.values()].map(pub); },
|
|
457
641
|
|
|
458
642
|
close() {
|
|
459
643
|
if (pollTimer) clearInterval(pollTimer);
|
|
644
|
+
for (const s of [...slots.values()]) {
|
|
645
|
+
const handles = [...s.line];
|
|
646
|
+
if (s.holder && !('parked' in s.holder)) handles.push(s.holder);
|
|
647
|
+
for (const handle of handles) {
|
|
648
|
+
const hst = handleState.get(handle);
|
|
649
|
+
if (!hst) continue;
|
|
650
|
+
if (hst.timer) clearTimeout(hst.timer);
|
|
651
|
+
hst.timer = null;
|
|
652
|
+
hst.done = true;
|
|
653
|
+
hst.onExpire('proxy closing');
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
slots.clear();
|
|
460
657
|
// settle() removes each ask file: `sbx pending` never lists a dead queue's holds.
|
|
461
658
|
for (const [id] of [...queue]) settle(id, false, 'proxy closing');
|
|
462
659
|
},
|
|
@@ -464,13 +661,3 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
464
661
|
|
|
465
662
|
return holds;
|
|
466
663
|
}
|
|
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
|
-
}
|