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/CHANGELOG.md +79 -0
- package/README.md +37 -23
- package/barebox.context.md +196 -13
- package/package.json +7 -2
- package/primitives.json +10 -1
- package/src/cardscan.js +96 -0
- package/src/cli.js +29 -4
- package/src/config.js +147 -0
- package/src/holds.js +76 -48
- package/src/index.js +1 -0
- package/src/labels.js +94 -0
- package/src/launcher.js +52 -7
- package/src/policy.js +141 -0
- package/src/proxy.js +599 -161
- package/src/run.js +40 -71
- package/src/runtime.js +7 -2
- package/src/secrets.js +113 -0
- package/src/wall.js +12 -6
- package/types/cardscan.d.ts +17 -0
- package/types/cli.d.ts +1 -1
- package/types/config.d.ts +59 -0
- package/types/holds.d.ts +25 -46
- package/types/index.d.ts +1 -0
- package/types/labels.d.ts +27 -0
- package/types/launcher.d.ts +10 -2
- package/types/policy.d.ts +64 -0
- package/types/proxy.d.ts +87 -33
- package/types/run.d.ts +61 -11
- package/types/runtime.d.ts +3 -1
- package/types/secrets.d.ts +63 -0
- 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,6 +30,9 @@
|
|
|
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';
|
|
@@ -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, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} */
|
|
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;
|
|
@@ -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, secrets: cfg.secrets, env: cfg.env,
|
|
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,147 @@
|
|
|
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
|
+
const NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
26
|
+
const SECRET_LIKE = /KEY|TOKEN|SECRET|PASSWORD/i;
|
|
27
|
+
/** A plain object. @param {unknown} v @returns {boolean} */
|
|
28
|
+
const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
29
|
+
|
|
30
|
+
/** `env`: `{ pass?: names, set?: name -> string }`. @param {unknown} v @returns {string|null} */
|
|
31
|
+
const checkEnv = (v) => {
|
|
32
|
+
if (!isObj(v)) return 'must be an object of { pass?, set? }';
|
|
33
|
+
const o = /** @type {Record<string, any>} */ (v);
|
|
34
|
+
for (const k of Object.keys(o)) if (k !== 'pass' && k !== 'set') return `has unknown field "${k}"`;
|
|
35
|
+
if (o.pass !== undefined) {
|
|
36
|
+
if (!Array.isArray(o.pass) || !o.pass.every((n) => typeof n === 'string' && NAME_RE.test(n))) {
|
|
37
|
+
return 'env.pass must be an array of variable names';
|
|
38
|
+
}
|
|
39
|
+
const bad = o.pass.find((n) => SECRET_LIKE.test(n));
|
|
40
|
+
if (bad !== undefined) return `env.pass: "${bad}" looks like a secret; use "secrets" for it`;
|
|
41
|
+
}
|
|
42
|
+
if (o.set !== undefined) {
|
|
43
|
+
if (!isObj(o.set) || !Object.entries(o.set).every(([n, x]) => NAME_RE.test(n) && typeof x === 'string')) {
|
|
44
|
+
return 'env.set must be an object of variable name -> string';
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return null;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/** `secrets`: NAME -> `{ fromEnv | value, hosts }`. @param {unknown} v @returns {string|null} */
|
|
51
|
+
const checkSecrets = (v) => {
|
|
52
|
+
if (!isObj(v)) return 'must be an object of NAME -> { fromEnv or value, hosts }';
|
|
53
|
+
for (const [name, s] of Object.entries(/** @type {Record<string, any>} */ (v))) {
|
|
54
|
+
if (!NAME_RE.test(name)) return `secret name "${name}" is not a variable name`;
|
|
55
|
+
if (!isObj(s)) return `secret ${name} must be an object`;
|
|
56
|
+
for (const k of Object.keys(s)) if (!['fromEnv', 'value', 'hosts'].includes(k)) return `secret ${name} has unknown field "${k}"`;
|
|
57
|
+
if ((s.fromEnv === undefined) === (s.value === undefined)) return `secret ${name} needs exactly one of fromEnv or value`;
|
|
58
|
+
if (s.fromEnv !== undefined && (typeof s.fromEnv !== 'string' || !NAME_RE.test(s.fromEnv))) return `secret ${name}: fromEnv must be a variable name`;
|
|
59
|
+
if (s.value !== undefined && (typeof s.value !== 'string' || s.value === '')) return `secret ${name}: value must be a non-empty string`;
|
|
60
|
+
if (!Array.isArray(s.hosts) || !s.hosts.length
|
|
61
|
+
|| !s.hosts.every((h) => typeof h === 'string' && /^[^\s:/@]+$/.test(h))) {
|
|
62
|
+
return `secret ${name}: hosts must be a non-empty array of hostnames (no scheme, no port)`;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return null;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/** Validators by key; each returns an error string or null. */
|
|
69
|
+
const KEYS = {
|
|
70
|
+
mode: (v) => (MODES.includes(v) ? null : `must be one of ${MODES.join(', ')}`),
|
|
71
|
+
holdTimeoutSec: (v) => (v === 'never' || (Number.isInteger(v) && v > 0)
|
|
72
|
+
? null : 'must be a positive integer or "never"'),
|
|
73
|
+
heldBodyMaxMB: (v) => (Number.isInteger(v) && v > 0 ? null : 'must be a positive integer'),
|
|
74
|
+
localLlm: (v) => (Array.isArray(v) && v.every(isHostPort)
|
|
75
|
+
? null : 'must be an array of "host:port" strings (port 1-65535)'),
|
|
76
|
+
labels: (v) => (Array.isArray(v) && v.every((x) => typeof x === 'string' && x !== '')
|
|
77
|
+
? null : 'must be an array of folder paths (strings)'),
|
|
78
|
+
tenants: (v) => (v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
79
|
+
&& Object.values(v).every((a) => Array.isArray(a) && a.length > 0 && a.every(isHttpUrl))
|
|
80
|
+
? null : 'must be an object of vendor -> non-empty array of http(s) URLs'),
|
|
81
|
+
env: checkEnv,
|
|
82
|
+
secrets: checkSecrets,
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Where the config file lives.
|
|
87
|
+
*
|
|
88
|
+
* @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
|
|
89
|
+
* @returns {string} absolute path of `config.json`
|
|
90
|
+
*/
|
|
91
|
+
export function configPath(env = process.env) {
|
|
92
|
+
const base = env.XDG_CONFIG_HOME || path.join(env.HOME || os.homedir(), '.config');
|
|
93
|
+
return path.join(base, 'barebox', 'config.json');
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Read the config file over the defaults. No file means defaults.
|
|
98
|
+
*
|
|
99
|
+
* @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
|
|
100
|
+
* @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)
|
|
101
|
+
* @throws {Error} naming the file (and the key) on invalid JSON, an unknown key or a bad value
|
|
102
|
+
*/
|
|
103
|
+
export function loadConfig(env = process.env) {
|
|
104
|
+
const file = configPath(env);
|
|
105
|
+
let text;
|
|
106
|
+
try {
|
|
107
|
+
text = fs.readFileSync(file, 'utf8');
|
|
108
|
+
} catch (e) {
|
|
109
|
+
if (/** @type {NodeJS.ErrnoException} */ (e).code === 'ENOENT') return { ...DEFAULTS };
|
|
110
|
+
throw new Error(`${file}: ${e instanceof Error ? e.message : String(e)}`);
|
|
111
|
+
}
|
|
112
|
+
let data;
|
|
113
|
+
try {
|
|
114
|
+
data = JSON.parse(text);
|
|
115
|
+
} catch (e) {
|
|
116
|
+
throw new Error(`${file}: invalid JSON (${e instanceof Error ? e.message : String(e)})`);
|
|
117
|
+
}
|
|
118
|
+
if (data === null || typeof data !== 'object' || Array.isArray(data)) {
|
|
119
|
+
throw new Error(`${file}: must be a JSON object`);
|
|
120
|
+
}
|
|
121
|
+
for (const [k, v] of Object.entries(data)) {
|
|
122
|
+
if (!Object.hasOwn(KEYS, k)) throw new Error(`${file}: unknown key "${k}"`);
|
|
123
|
+
const bad = KEYS[/** @type {keyof typeof KEYS} */ (k)](v);
|
|
124
|
+
if (bad) throw new Error(`${file}: key "${k}" ${bad}`);
|
|
125
|
+
}
|
|
126
|
+
// A secret read from the host environment must be there at startup (the name, never a value).
|
|
127
|
+
for (const [name, s] of Object.entries(data.secrets ?? {})) {
|
|
128
|
+
if (s.fromEnv !== undefined && !env[s.fromEnv]) {
|
|
129
|
+
throw new Error(`${file}: secret ${name}: host variable ${s.fromEnv} is not set`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return { ...DEFAULTS, ...data };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Settings for one `sbx run`: a CLI flag beats the file, the file beats the default.
|
|
137
|
+
*
|
|
138
|
+
* @param {object} [flags] values given on the command line
|
|
139
|
+
* @param {string} [flags.mode] `--mode`
|
|
140
|
+
* @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
|
|
141
|
+
* @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)
|
|
142
|
+
* @throws {Error} as {@link loadConfig}
|
|
143
|
+
*/
|
|
144
|
+
export function resolveConfig(flags = {}, env = process.env) {
|
|
145
|
+
const cfg = loadConfig(env);
|
|
146
|
+
return { ...cfg, ...(flags.mode !== undefined ? { mode: flags.mode } : {}) };
|
|
147
|
+
}
|
package/src/holds.js
CHANGED
|
@@ -32,12 +32,18 @@
|
|
|
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
|
|
@@ -45,10 +51,25 @@
|
|
|
45
51
|
import fs from 'node:fs';
|
|
46
52
|
import path from 'node:path';
|
|
47
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
|
|
|
@@ -57,7 +78,7 @@ const MAX_WAITING_PER_AGENT = 16;
|
|
|
57
78
|
|
|
58
79
|
/**
|
|
59
80
|
* A parked request, as returned by {@link pending}. Plain objects only —
|
|
60
|
-
* the queue itself never leaves this module. No body: returning whole
|
|
81
|
+
* the queue itself never leaves this module. No body: returning whole
|
|
61
82
|
* bodies from a status call is never needed, and the ask payload in
|
|
62
83
|
* `asks/<id>.json` carries the preview.
|
|
63
84
|
*
|
|
@@ -66,7 +87,7 @@ const MAX_WAITING_PER_AGENT = 16;
|
|
|
66
87
|
* @property {string} agent agent name (its socket), never `c<n>`
|
|
67
88
|
* @property {string} method HTTP method
|
|
68
89
|
* @property {string} url full URL
|
|
69
|
-
* @property {string} rule
|
|
90
|
+
* @property {string} rule the gate's ask rule (hold reason)
|
|
70
91
|
* @property {number} waitingSec seconds since the hold parked
|
|
71
92
|
*/
|
|
72
93
|
|
|
@@ -92,9 +113,9 @@ const MAX_WAITING_PER_AGENT = 16;
|
|
|
92
113
|
* @property {string} agent agent name (its socket)
|
|
93
114
|
* @property {string} method HTTP method
|
|
94
115
|
* @property {string} url full URL
|
|
95
|
-
* @property {string} rule
|
|
96
|
-
* @property {string} letter
|
|
97
|
-
* @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
|
|
98
119
|
* @property {boolean} truncated true when the body exceeded ASK_BODY_LIMIT
|
|
99
120
|
* @property {number} waitingSec 0 at park; readers use the file mtime for a live value
|
|
100
121
|
* @property {string|null} expiresAt ISO-8601 UTC deadline, or null when `timeoutMs: 'never'`
|
|
@@ -106,13 +127,6 @@ const MAX_WAITING_PER_AGENT = 16;
|
|
|
106
127
|
* @typedef {(ask: AskPayload) => Promise<{ decision: string, reason?: string }>} OnAsk
|
|
107
128
|
*/
|
|
108
129
|
|
|
109
|
-
/**
|
|
110
|
-
* Decide whether a request parks. Return a human-readable reason, or null
|
|
111
|
-
* to forward. M3 plugs the rwxmap + bareguard classifier into this one seam.
|
|
112
|
-
*
|
|
113
|
-
* @typedef {(req: { agent: string, method: string, url: string, headers: Record<string, string | string[] | undefined> }) => string | null} ShouldHold
|
|
114
|
-
*/
|
|
115
|
-
|
|
116
130
|
/**
|
|
117
131
|
* Atomic write: tmp file + rename, so readers never see a partial payload.
|
|
118
132
|
*
|
|
@@ -213,23 +227,19 @@ export function normalizeDecision(input, { approveAlias = false } = {}) {
|
|
|
213
227
|
*
|
|
214
228
|
* @param {object} opts
|
|
215
229
|
* @param {(o: Record<string, unknown>) => void} opts.log audit-log writer
|
|
216
|
-
* @param {ShouldHold} [opts.shouldHold] decision function (default: path-substring `match`)
|
|
217
|
-
* @param {string} [opts.match] path substring that parks a request (default impl when `shouldHold` is absent)
|
|
218
230
|
* @param {number|string} [opts.timeoutMs] hold deadline in ms, or `'never'` (default 120000)
|
|
219
|
-
* @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)
|
|
220
232
|
* @param {string|null} [opts.runtime] runtime dir; required for the default file checkpoint (writes `asks/`, polls `answers/`)
|
|
221
233
|
* @param {OnAsk|null} [opts.onAsk] ask seam (bareguard `humanChannel` shape); when present no files are involved
|
|
222
234
|
* @param {number} [opts.pollMs] answer poll interval in ms for the default file checkpoint (default 250, PRD Q9)
|
|
223
235
|
* @param {OnEvent|null} [opts.onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon
|
|
224
236
|
* @param {(entry: object) => void} opts.onApprove forward the parked request upstream
|
|
225
237
|
* @param {(entry: object, reason: string) => void} opts.onDeny refuse the parked request
|
|
226
|
-
* @returns {{ add: (entry: object) => string|null, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string) => void }) => { state: 'now'|'queued'|'full', arrivedAt: number, cancel: () => void },
|
|
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
|
|
227
239
|
*/
|
|
228
|
-
export function createHolds({ log,
|
|
229
|
-
maxBody =
|
|
240
|
+
export function createHolds({ log, timeoutMs = 120000,
|
|
241
|
+
maxBody = DEFAULT_HOLD_MAX_BODY, runtime = null, onAsk = null, pollMs = DEFAULT_POLL_MS,
|
|
230
242
|
onEvent = null, onApprove, onDeny }) {
|
|
231
|
-
// The default IS matchPath: one definition of the path-substring rule (see below).
|
|
232
|
-
const decide = shouldHold ?? (match ? matchPath(match) : () => null);
|
|
233
243
|
/** @returns {number|null} */
|
|
234
244
|
const deadlineMs = () => {
|
|
235
245
|
if (timeoutMs === 'never') return null;
|
|
@@ -255,6 +265,13 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
255
265
|
if (paths) {
|
|
256
266
|
ensurePrivateDir(paths.asksDir);
|
|
257
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 {}
|
|
258
275
|
}
|
|
259
276
|
// A dead queue's leftovers must never decide the next queue's holds
|
|
260
277
|
// (ids restart at h1): clear both folders at start, logging one audit
|
|
@@ -290,7 +307,7 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
290
307
|
* @type {Map<string, { holder: object|null, line: Array<object> }>}
|
|
291
308
|
*/
|
|
292
309
|
const slots = new Map();
|
|
293
|
-
/** 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 }>} */
|
|
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 }>} */
|
|
294
311
|
const handleState = new WeakMap();
|
|
295
312
|
|
|
296
313
|
/**
|
|
@@ -357,17 +374,15 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
357
374
|
* @returns {AskPayload}
|
|
358
375
|
*/
|
|
359
376
|
function askPayload(entry, ms, rule) {
|
|
360
|
-
const body = Buffer.isBuffer(entry.body) ? entry.body : Buffer.from(String(entry.body ?? ''));
|
|
361
377
|
return {
|
|
362
378
|
id: entry.id,
|
|
363
379
|
agent: entry.agent,
|
|
364
380
|
method: entry.method,
|
|
365
381
|
url: entry.url,
|
|
366
382
|
rule,
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
truncated: body.length > ASK_BODY_LIMIT,
|
|
383
|
+
letter: entry.letter ?? 'x',
|
|
384
|
+
bodyPreview: entry.preview,
|
|
385
|
+
truncated: entry.bodyBytes > ASK_BODY_LIMIT,
|
|
371
386
|
waitingSec: 0,
|
|
372
387
|
// ISO-8601 UTC (not epoch ms): readable in `sbx pending` and logs.
|
|
373
388
|
expiresAt: ms === null ? null : new Date(entry.t0 + ms).toISOString(),
|
|
@@ -381,6 +396,18 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
381
396
|
} catch {}
|
|
382
397
|
}
|
|
383
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
|
+
|
|
384
411
|
function settle(id, approved, reason) {
|
|
385
412
|
const h = queue.get(id);
|
|
386
413
|
if (!h) return `unknown ${id}`;
|
|
@@ -393,6 +420,7 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
393
420
|
log({ ev: 'decide', id, agent: h.agent, decision, reason: reason || undefined });
|
|
394
421
|
onApprove(h);
|
|
395
422
|
} else {
|
|
423
|
+
dropBody(id);
|
|
396
424
|
log({ ev: 'decide', id, agent: h.agent, decision, reason });
|
|
397
425
|
onDeny(h, reason);
|
|
398
426
|
}
|
|
@@ -488,18 +516,23 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
488
516
|
* parks nothing and returns `null`. Without `slot`, parks exactly as
|
|
489
517
|
* before, without limit.
|
|
490
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
|
+
*
|
|
491
524
|
* @param {object} entry queue entry
|
|
492
525
|
* @returns {string|null} hold id, or null for a finished slot
|
|
493
526
|
*/
|
|
494
|
-
add({ agent, method, url,
|
|
527
|
+
add({ agent, method, url, preview = '', bodyBytes = 0, sock, note, letter, finish, slot, arrivedAt }) {
|
|
495
528
|
const hst = typeof slot === 'object' && slot !== null ? handleState.get(slot) : undefined;
|
|
496
529
|
const s = slots.get(agent);
|
|
497
530
|
if (slot && (!hst || hst.done || !s || s.holder !== slot)) return null;
|
|
498
|
-
const id = `h${++n}`;
|
|
531
|
+
const id = hst?.id ?? `h${++n}`;
|
|
499
532
|
const ms = deadlineMs();
|
|
500
533
|
const t0 = typeof arrivedAt === 'number' ? arrivedAt : Date.now();
|
|
501
534
|
const entry = {
|
|
502
|
-
id, agent, method, url,
|
|
535
|
+
id, agent, method, url, preview, bodyBytes, sock, note, letter, finish, t0,
|
|
503
536
|
slot: null,
|
|
504
537
|
timer: ms === null ? null
|
|
505
538
|
: setTimeout(() => settle(id, false, 'hold timeout'), Math.max(0, ms - (Date.now() - t0))),
|
|
@@ -524,7 +557,9 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
524
557
|
* Ask for this agent's hold slot before reading a held request's body.
|
|
525
558
|
* @param {string} agent
|
|
526
559
|
* @param {{ onReady: () => void, onExpire: (reason: string) => void }} cbs
|
|
527
|
-
*
|
|
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 }}
|
|
528
563
|
*/
|
|
529
564
|
reserve(agent, { onReady, onExpire }) {
|
|
530
565
|
const arrivedAt = Date.now();
|
|
@@ -532,13 +567,15 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
532
567
|
// receives that same object as `slot`, so holder comparisons use it.
|
|
533
568
|
// The one deadline timer lives here, armed below for 'now' and
|
|
534
569
|
// 'queued' alike; expiry runs through `expireReservation` only.
|
|
535
|
-
/** @type {{ agent: string, onReady: () => void, onExpire: (reason: string) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean }} */
|
|
536
|
-
const st = { agent, onReady, onExpire, timer: null, consumed: false, done: false };
|
|
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: '' };
|
|
537
572
|
const s0 = slots.get(agent);
|
|
538
573
|
/** @type {'now'|'queued'|'full'} */
|
|
539
574
|
const state = !s0 ? 'now' : (s0.line.length >= MAX_WAITING_PER_AGENT ? 'full' : 'queued');
|
|
575
|
+
if (state !== 'full') st.id = `h${++n}`;
|
|
540
576
|
const handle = {
|
|
541
577
|
state,
|
|
578
|
+
id: st.id,
|
|
542
579
|
arrivedAt,
|
|
543
580
|
cancel() {
|
|
544
581
|
if (st.done) return;
|
|
@@ -586,6 +623,7 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
586
623
|
if (h.timer) clearTimeout(h.timer);
|
|
587
624
|
if (h.slot) releaseSlot(h.agent);
|
|
588
625
|
removeAskFile(id);
|
|
626
|
+
dropBody(id);
|
|
589
627
|
log({ ev: 'hold-abandoned', id, agent: h.agent, method: h.method, url: h.url });
|
|
590
628
|
onDeny(h, 'client gone');
|
|
591
629
|
onEvent?.({ type: 'decided', id, decision: 'deny', reason: 'client gone' });
|
|
@@ -597,7 +635,7 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
597
635
|
}
|
|
598
636
|
},
|
|
599
637
|
|
|
600
|
-
|
|
638
|
+
dropBody,
|
|
601
639
|
|
|
602
640
|
pending() { return [...queue.values()].map(pub); },
|
|
603
641
|
|
|
@@ -623,13 +661,3 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
|
623
661
|
|
|
624
662
|
return holds;
|
|
625
663
|
}
|
|
626
|
-
|
|
627
|
-
/**
|
|
628
|
-
* Default decision: park requests whose path contains `match`.
|
|
629
|
-
*
|
|
630
|
-
* @param {string} match path substring
|
|
631
|
-
* @returns {ShouldHold} decision function
|
|
632
|
-
*/
|
|
633
|
-
export function matchPath(match) {
|
|
634
|
-
return (req) => (new URL(req.url).pathname.includes(match) ? `path matches ${match}` : null);
|
|
635
|
-
}
|
package/src/index.js
CHANGED
package/src/labels.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// labels.js — the only reader of rwxmap label folders (`labels` in the config).
|
|
2
|
+
// Per vendor the rwxmap CLI writes `<v>.rwxmap.json` (the gate file: the
|
|
3
|
+
// letters barebox uses) and `<v>.rwxmap.review.json` (the sidecar the matcher
|
|
4
|
+
// reads). Letters come from the gate file only, never from the sidecar.
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { matcherFrom } from 'rwxmap/match';
|
|
9
|
+
|
|
10
|
+
const REVIEW = '.rwxmap.review.json';
|
|
11
|
+
const GATE = '.rwxmap.json';
|
|
12
|
+
|
|
13
|
+
/** @param {string} file @returns {any} parsed JSON, errors naming the file */
|
|
14
|
+
function readJson(file) {
|
|
15
|
+
try {
|
|
16
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
17
|
+
} catch (e) {
|
|
18
|
+
throw new Error(`${file}: ${e instanceof Error ? e.message : String(e)}`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Load every label folder: the matcher for request keys and the tools table
|
|
24
|
+
* (key to `{ letter, marker }`) from the gate files. Call once at startup so a
|
|
25
|
+
* bad file fails the run before any agent starts.
|
|
26
|
+
*
|
|
27
|
+
* @param {object} cfg
|
|
28
|
+
* @param {string[]} [cfg.labels] folders the rwxmap CLI wrote (`~/` means `$HOME`)
|
|
29
|
+
* @param {Record<string, string[]>} [cfg.tenants] vendor to tenant base URLs, replacing the sidecar's `servers`
|
|
30
|
+
* @param {NodeJS.ProcessEnv} [env] environment for `$HOME`
|
|
31
|
+
* @returns {{ matcher: ReturnType<typeof matcherFrom>, tools: Record<string, any>, dirs: string[] }} `dirs` are the absolute folders (the launcher masks them)
|
|
32
|
+
* @throws {Error} naming the file or folder on a missing gate or review file, a duplicate key, an unknown tenant vendor or a bad sidecar
|
|
33
|
+
* @when Reach for this to build the `labels` value `run()` and `createProxy()` take: it reads rwxmap label folders once at startup and returns the request matcher, the tools table (letters from each gate file) and the absolute folders.
|
|
34
|
+
* @fails Throws, naming the file or folder, on a folder with no review file, a review file without its gate file, a duplicate key across vendors, a tenants vendor no folder defines, an unreadable folder, or a label file written before rwxmap 0.8.0.
|
|
35
|
+
* @example
|
|
36
|
+
* import { loadLabels, run } from "barebox";
|
|
37
|
+
* const labels = loadLabels({ labels: ["/home/me/labels/jira"], tenants: { jira: ["https://acme.atlassian.net"] } });
|
|
38
|
+
* await run({ proj: "/tmp/proj", command: ["bash", "-c", "true"], labels });
|
|
39
|
+
*/
|
|
40
|
+
export function loadLabels({ labels = [], tenants = {} }, env = process.env) {
|
|
41
|
+
const home = env.HOME || os.homedir();
|
|
42
|
+
/** @type {Record<string, any>} */
|
|
43
|
+
const tools = {};
|
|
44
|
+
/** @type {Record<string, string>} key to the gate file that defined it */
|
|
45
|
+
const origin = {};
|
|
46
|
+
/** @type {any[]} */
|
|
47
|
+
const sidecars = [];
|
|
48
|
+
/** @type {Map<string, string>} sidecar vendor to review file path */
|
|
49
|
+
const vendors = new Map();
|
|
50
|
+
/** @type {string[]} */
|
|
51
|
+
const dirs = [];
|
|
52
|
+
for (const raw of labels) {
|
|
53
|
+
const dir = path.resolve(raw === '~' ? home : raw.startsWith('~/') ? path.join(home, raw.slice(2)) : raw);
|
|
54
|
+
dirs.push(dir);
|
|
55
|
+
let names;
|
|
56
|
+
try {
|
|
57
|
+
names = fs.readdirSync(dir).filter((n) => n.endsWith(REVIEW)).sort();
|
|
58
|
+
} catch (e) {
|
|
59
|
+
throw new Error(`labels folder ${dir}: ${e instanceof Error ? e.message : String(e)}`);
|
|
60
|
+
}
|
|
61
|
+
if (!names.length) throw new Error(`labels folder ${dir}: no *${REVIEW} file`);
|
|
62
|
+
for (const n of names) {
|
|
63
|
+
const review = path.join(dir, n);
|
|
64
|
+
const gateFile = path.join(dir, n.slice(0, -REVIEW.length) + GATE);
|
|
65
|
+
if (!fs.existsSync(gateFile)) throw new Error(`${review}: missing its gate file ${gateFile}`);
|
|
66
|
+
const side = readJson(review);
|
|
67
|
+
const gate = readJson(gateFile);
|
|
68
|
+
const t = gate?.bareguard?.tools;
|
|
69
|
+
if (t === null || typeof t !== 'object' || Array.isArray(t)) {
|
|
70
|
+
throw new Error(`${gateFile}: no bareguard.tools object`);
|
|
71
|
+
}
|
|
72
|
+
for (const [k, v] of Object.entries(t)) {
|
|
73
|
+
if (Object.hasOwn(tools, k)) throw new Error(`${gateFile}: key "${k}" is also defined in ${origin[k]}`);
|
|
74
|
+
tools[k] = v;
|
|
75
|
+
origin[k] = gateFile;
|
|
76
|
+
}
|
|
77
|
+
const tenant = side?.vendor !== undefined ? tenants[side.vendor] : undefined;
|
|
78
|
+
if (tenant) side.servers = tenant;
|
|
79
|
+
if (side?.vendor !== undefined) vendors.set(side.vendor, review);
|
|
80
|
+
sidecars.push({ side, review });
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
for (const v of Object.keys(tenants)) {
|
|
84
|
+
if (!vendors.has(v)) throw new Error(`tenants: vendor "${v}" is in no labels folder`);
|
|
85
|
+
}
|
|
86
|
+
let matcher;
|
|
87
|
+
try {
|
|
88
|
+
matcher = matcherFrom(sidecars.map((s) => s.side));
|
|
89
|
+
} catch (e) {
|
|
90
|
+
// matcherFrom does not say which file; name the files (pre-0.8.0 message passes through).
|
|
91
|
+
throw new Error(`${sidecars.map((s) => s.review).join(', ')}: ${e instanceof Error ? e.message : String(e)}`);
|
|
92
|
+
}
|
|
93
|
+
return { matcher, tools, dirs };
|
|
94
|
+
}
|