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/run.js
CHANGED
|
@@ -4,19 +4,18 @@
|
|
|
4
4
|
// which stay public): one agent, one sandbox, one audit log, exit code out.
|
|
5
5
|
// The caller never touches sockets, ask files, or the hold queue.
|
|
6
6
|
//
|
|
7
|
-
// What `mode` does
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
// - `trust` forwards everything else, logged.
|
|
7
|
+
// What `mode` does: it picks the agent's bareguard letters (see policy.js).
|
|
8
|
+
// Every request is one `gate.check()`; the hold queue is the gate's human
|
|
9
|
+
// channel. Until rwxmap lands, each HTTP method is one tool: GET/HEAD are `r`,
|
|
10
|
+
// POST/PUT/PATCH/DELETE are `x`, any other method is denied in every mode.
|
|
11
|
+
// - `ask` holds r only; w and x ask.
|
|
12
|
+
// - `auto` holds r and w; x asks.
|
|
13
|
+
// - `trust` holds r, w and x; nothing asks.
|
|
14
|
+
// - the card/payment FLOOR asks in every mode, trust included: a body of
|
|
15
|
+
// <= 64 KB holding a card number (`flags.cardLike`), or a path naming a
|
|
16
|
+
// payment destination (`flags.paymentPath`: /checkout, /payment,
|
|
17
|
+
// /orders, /purchase). Bodies over 64 KB stream through unchecked for
|
|
18
|
+
// cards (known gap). Known payment DOMAINS are B2 (they need rwxmap).
|
|
20
19
|
//
|
|
21
20
|
// A passed `onAsk` answers parked requests with no files involved; when it is
|
|
22
21
|
// absent the file checkpoint runs (`<runtime>/asks` + `<runtime>/answers`,
|
|
@@ -31,55 +30,7 @@ import { createProxy } from './proxy.js';
|
|
|
31
30
|
import { createRuntime, runtimePaths } from './runtime.js';
|
|
32
31
|
import { launch } from './launcher.js';
|
|
33
32
|
import { diffOverlay } from './overlay.js';
|
|
34
|
-
|
|
35
|
-
/** Payment-destination path fragments: the URL-visible half of the floor (PRD section 2). */
|
|
36
|
-
const FLOOR_PATHS = ['/checkout', '/payment', '/orders', '/purchase'];
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* The card/payment floor, URL-visible half: park payment destinations in
|
|
40
|
-
* every mode. Returns the hold reason, or null to leave the mode rule alone.
|
|
41
|
-
*
|
|
42
|
-
* @param {{ url: string }} req request, as seen by the decide seam
|
|
43
|
-
* @returns {string|null} hold reason, or null
|
|
44
|
-
*/
|
|
45
|
-
function floorReason(req) {
|
|
46
|
-
let pathname;
|
|
47
|
-
try {
|
|
48
|
-
pathname = new URL(req.url).pathname.toLowerCase();
|
|
49
|
-
} catch {
|
|
50
|
-
return null;
|
|
51
|
-
}
|
|
52
|
-
for (const fp of FLOOR_PATHS) {
|
|
53
|
-
if (pathname.includes(fp)) return `payment destination (floor): ${fp}`;
|
|
54
|
-
}
|
|
55
|
-
return null;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* The interim x-rule (PRD "everything else"): GET/HEAD forward, any other
|
|
60
|
-
* method parks. Stands in for M3's letters.
|
|
61
|
-
*
|
|
62
|
-
* @param {{ method: string }} req request, as seen by the decide seam
|
|
63
|
-
* @returns {string|null} hold reason, or null
|
|
64
|
-
*/
|
|
65
|
-
function methodReason(req) {
|
|
66
|
-
const m = String(req.method || '').toUpperCase();
|
|
67
|
-
return (m === 'GET' || m === 'HEAD') ? null : `method ${m || '?'} is not GET/HEAD (interim x-rule)`;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/**
|
|
71
|
-
* Build the hold decision for a mode. Pure: unit-testable without a sandbox.
|
|
72
|
-
*
|
|
73
|
-
* @param {string} mode `ask` | `auto` | `trust`
|
|
74
|
-
* @returns {import('./holds.js').ShouldHold} decision function for the hold queue
|
|
75
|
-
*/
|
|
76
|
-
export function shouldHoldForMode(mode) {
|
|
77
|
-
if (mode !== 'ask' && mode !== 'auto' && mode !== 'trust') {
|
|
78
|
-
throw new Error(`run: mode must be ask|auto|trust, got ${JSON.stringify(mode)}`);
|
|
79
|
-
}
|
|
80
|
-
return (req) => floorReason(req)
|
|
81
|
-
?? (mode === 'trust' ? null : methodReason(req));
|
|
82
|
-
}
|
|
33
|
+
import { MODES, gateFor } from './policy.js';
|
|
83
34
|
|
|
84
35
|
/**
|
|
85
36
|
* A collected ask record: the parked ask plus how it was decided.
|
|
@@ -90,7 +41,7 @@ export function shouldHoldForMode(mode) {
|
|
|
90
41
|
* @property {string} method HTTP method
|
|
91
42
|
* @property {string} url full URL
|
|
92
43
|
* @property {string} rule hold-reason string
|
|
93
|
-
* @property {string} letter
|
|
44
|
+
* @property {string} letter the matched rwx letter, `'x'` when the ask names none
|
|
94
45
|
* @property {string} [bodyPreview] request body preview
|
|
95
46
|
* @property {boolean} [truncated] body preview truncation flag
|
|
96
47
|
* @property {string|null} [expiresAt] ISO-8601 UTC deadline, or null
|
|
@@ -110,6 +61,9 @@ export function shouldHoldForMode(mode) {
|
|
|
110
61
|
* @property {string} [runtime] runtime dir (created when absent: a short `sbx-*` temp dir, keeping unix socket paths under the ~108-char limit)
|
|
111
62
|
* @property {string} [agent] agent name (default `'agent'`)
|
|
112
63
|
* @property {number|string} [timeoutMs] hold deadline in ms, or `'never'` (default 120000)
|
|
64
|
+
* @property {number} [heldBodyMaxBytes] cap on a held request's body, in bytes (default 52428800); over it the request is denied
|
|
65
|
+
* @property {{ matcher: any, tools: Record<string, any>, dirs?: string[] }} [labels] the loaded label files (`loadLabels`); their folders are masked from the sandbox
|
|
66
|
+
* @property {string[]} [allowLocal] exact `host:port` pairs (for example a local model server) that may pass the wall's private/loopback check (the `localLlm` setting)
|
|
113
67
|
* @property {object} [unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`): everything under it weakens the sandbox wall
|
|
114
68
|
* @property {NodeJS.WritableStream} [stdout] where the agent's stdout goes (default process.stdout)
|
|
115
69
|
* @property {NodeJS.WritableStream} [stderr] where the agent's stderr goes (default process.stderr)
|
|
@@ -129,6 +83,9 @@ export function shouldHoldForMode(mode) {
|
|
|
129
83
|
* @param {string|null} [opts.runtime] runtime dir (created when absent: a short `sbx-*` temp dir, keeping unix socket paths under the ~108-char limit)
|
|
130
84
|
* @param {string} [opts.agent] agent name (default `'agent'`)
|
|
131
85
|
* @param {number|string} [opts.timeoutMs] hold deadline in ms, or `'never'` (default 120000)
|
|
86
|
+
* @param {number} [opts.heldBodyMaxBytes] cap on a held request's body, in bytes (default 52428800); over it the request is denied
|
|
87
|
+
* @param {{ matcher: any, tools: Record<string, any>, dirs?: string[] }|null} [opts.labels] the loaded label files (`loadLabels`); their folders are masked from the sandbox
|
|
88
|
+
* @param {string[]} [opts.allowLocal] exact `host:port` pairs (for example a local model server) that may pass the wall's private/loopback check (the `localLlm` setting)
|
|
132
89
|
* @param {object|null} [opts.unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`)
|
|
133
90
|
* @param {NodeJS.WritableStream|null} [opts.stdout] where the agent's stdout goes (default process.stdout)
|
|
134
91
|
* @param {NodeJS.WritableStream|null} [opts.stderr] where the agent's stderr goes (default process.stderr)
|
|
@@ -142,8 +99,8 @@ export function shouldHoldForMode(mode) {
|
|
|
142
99
|
* const { exit, asks, audit } = await run({ proj: "/tmp/proj", command: ["bash", "-c", "echo hi"] });
|
|
143
100
|
*/
|
|
144
101
|
export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
145
|
-
onEvent = null, runtime = null, agent = 'agent', timeoutMs,
|
|
146
|
-
unsafeTestOnly = null, stdout = null, stderr = null,
|
|
102
|
+
onEvent = null, runtime = null, agent = 'agent', timeoutMs, heldBodyMaxBytes,
|
|
103
|
+
allowLocal = [], labels = null, unsafeTestOnly = null, stdout = null, stderr = null,
|
|
147
104
|
overlay = false, overlayIgnore }) {
|
|
148
105
|
if (typeof proj !== 'string' || !proj) throw new Error('run: proj must be a non-empty string');
|
|
149
106
|
if (!fs.existsSync(proj)) throw new Error(`run: proj does not exist: ${proj}`);
|
|
@@ -154,7 +111,9 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
|
154
111
|
throw new Error('run: onAsk must be a function');
|
|
155
112
|
}
|
|
156
113
|
// Mode first: bad input throws before any runtime dir is created.
|
|
157
|
-
|
|
114
|
+
if (!MODES.includes(mode)) {
|
|
115
|
+
throw new Error(`run: mode must be ${MODES.join('|')}, got ${JSON.stringify(mode)}`);
|
|
116
|
+
}
|
|
158
117
|
// Short temp dir: agent socket paths inherit it and cap at ~108 chars.
|
|
159
118
|
const rt = runtime ?? createRuntime();
|
|
160
119
|
const audit = runtimePaths(rt).audit;
|
|
@@ -177,8 +136,10 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
|
177
136
|
: recordEvent;
|
|
178
137
|
|
|
179
138
|
const proxy = createProxy({
|
|
180
|
-
runtime: rt, logFile: audit, unsafeTestOnly,
|
|
181
|
-
|
|
139
|
+
runtime: rt, logFile: audit, allowLocal, unsafeTestOnly,
|
|
140
|
+
...(labels ? { labels } : {}),
|
|
141
|
+
gateFor: (name, { humanChannel, tools }) => gateFor({ agent: name, mode, auditPath: audit, humanChannel, tools }),
|
|
142
|
+
hold: { onAsk, timeoutMs, maxBody: heldBodyMaxBytes, onEvent: holdOnEvent },
|
|
182
143
|
});
|
|
183
144
|
try {
|
|
184
145
|
await proxy.ready;
|
|
@@ -186,17 +147,20 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
|
186
147
|
await proxy.close().catch(() => {});
|
|
187
148
|
throw e;
|
|
188
149
|
}
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
//
|
|
192
|
-
//
|
|
150
|
+
/** @type {string|undefined} */
|
|
151
|
+
let sock;
|
|
152
|
+
// `addAgent` and `launch` run INSIDE the try: a synchronous throw there
|
|
153
|
+
// (a broken socket folder, uncommitted overlay changes, a runtime inside
|
|
154
|
+
// the project) must still close the proxy — otherwise its listening
|
|
155
|
+
// sockets keep this process alive forever.
|
|
193
156
|
/** @type {number} */
|
|
194
157
|
let exit;
|
|
195
158
|
try {
|
|
159
|
+
sock = proxy.addAgent(agent);
|
|
196
160
|
const child = launch({
|
|
197
161
|
runtime: rt, agent, proj, command,
|
|
198
162
|
socket: sock, caFile: proxy.caFile,
|
|
199
|
-
overlay, overlayIgnore,
|
|
163
|
+
overlay, overlayIgnore, maskDirs: labels?.dirs ?? [],
|
|
200
164
|
});
|
|
201
165
|
const out = stdout ?? process.stdout;
|
|
202
166
|
const err = stderr ?? process.stderr;
|
|
@@ -207,6 +171,9 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
|
207
171
|
child.on('close', (code) => resolve(code ?? 1));
|
|
208
172
|
});
|
|
209
173
|
} finally {
|
|
174
|
+
// The sandbox is gone: end the agent's holds as client gone now, not
|
|
175
|
+
// as 'proxy closing' if close() beats the sockets' async 'close'.
|
|
176
|
+
if (sock) proxy.removeAgent(agent);
|
|
210
177
|
await proxy.close();
|
|
211
178
|
}
|
|
212
179
|
// M2.5 item 4: the result carries the M4 diff. Without overlay there is no
|
package/src/runtime.js
CHANGED
|
@@ -90,6 +90,26 @@ export function runtimeTempDir(scratch, prefix) {
|
|
|
90
90
|
return fs.mkdtempSync(path.join(scratch, `${prefix}-`));
|
|
91
91
|
}
|
|
92
92
|
|
|
93
|
+
/**
|
|
94
|
+
* Make a runtime dir owner-only whatever the umask: `mode` is masked by
|
|
95
|
+
* the umask and doesn't apply to an existing dir, hence the `chmod`. An
|
|
96
|
+
* existing dir you own is tightened to 0700; one you don't own (`/tmp`,
|
|
97
|
+
* root-owned, shared) is refused, since it can't be made private.
|
|
98
|
+
*
|
|
99
|
+
* @param {string} dir dir to create or fix up
|
|
100
|
+
* @returns {void}
|
|
101
|
+
* @throws {Error} when the dir exists and is owned by another uid
|
|
102
|
+
*/
|
|
103
|
+
export function ensurePrivateDir(dir) {
|
|
104
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
105
|
+
const owner = fs.statSync(dir).uid;
|
|
106
|
+
const me = /** @type {number} */ (process.getuid?.());
|
|
107
|
+
if (owner !== me) {
|
|
108
|
+
throw new Error(`runtime dir ${dir} is owned by uid ${owner}, not you (uid ${me}): use a dir of your own, e.g. ${path.join(dir, 'sbx')}`);
|
|
109
|
+
}
|
|
110
|
+
fs.chmodSync(dir, 0o700);
|
|
111
|
+
}
|
|
112
|
+
|
|
93
113
|
/** @param {string} owner owner file path @returns {unknown} the pid it names, or 'unknown' when missing, empty or garbage */
|
|
94
114
|
function pidOf(owner) {
|
|
95
115
|
try {
|
|
@@ -170,7 +190,7 @@ export function runtimeLive(runtime) {
|
|
|
170
190
|
* @returns {() => void} `release()`: unlinks the owner file only when it holds our pid, then closes the lock; idempotent per claim
|
|
171
191
|
*/
|
|
172
192
|
export function claimRuntime(runtime) {
|
|
173
|
-
|
|
193
|
+
ensurePrivateDir(runtime);
|
|
174
194
|
const real = fs.realpathSync(runtime);
|
|
175
195
|
const owner = runtimePaths(real).owner;
|
|
176
196
|
const name = lockName(runtime);
|
|
@@ -220,21 +240,37 @@ export function safe(s) {
|
|
|
220
240
|
.replace(/[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '');
|
|
221
241
|
}
|
|
222
242
|
|
|
243
|
+
/**
|
|
244
|
+
* Quote a path for pasting into a shell: safe spellings come back
|
|
245
|
+
* unchanged, anything else is single-quoted with `'` escaped.
|
|
246
|
+
*
|
|
247
|
+
* @param {string} s path to quote
|
|
248
|
+
* @returns {string} shell-safe spelling
|
|
249
|
+
*/
|
|
250
|
+
export function shellQuote(s) {
|
|
251
|
+
if (/^[A-Za-z0-9_\/.,:@%+=-]+$/.test(s)) return s;
|
|
252
|
+
return `'` + s.replace(/'/g, `'\\''`) + `'`;
|
|
253
|
+
}
|
|
254
|
+
|
|
223
255
|
/**
|
|
224
256
|
* Every path in a runtime dir. The one place that names them.
|
|
225
257
|
*
|
|
226
258
|
* @param {string} runtime runtime dir
|
|
227
|
-
* @returns {{ socket: (agent: string) => string, asksDir: string, answersDir: string, askFile: (id: string) => string, answerFile: (id: string) => string, certsDir: string, caBundle: string, audit: string, owner: string, overlay: (agent: string) => { base: string, upper: string, work: string, manifest: string } }} layout
|
|
259
|
+
* @returns {{ socket: (agent: string) => string, asksDir: string, answersDir: string, askFile: (id: string) => string, answerFile: (id: string) => string, heldDir: string, heldFile: (id: string) => string, certsDir: string, caBundle: string, audit: string, owner: string, overlay: (agent: string) => { base: string, upper: string, work: string, manifest: string } }} layout
|
|
228
260
|
*/
|
|
229
261
|
export function runtimePaths(runtime) {
|
|
230
262
|
const asksDir = path.join(runtime, 'asks');
|
|
231
263
|
const answersDir = path.join(runtime, 'answers');
|
|
264
|
+
const heldDir = path.join(runtime, 'held');
|
|
232
265
|
return {
|
|
233
266
|
owner: path.join(runtime, 'owner'),
|
|
234
267
|
asksDir,
|
|
235
268
|
answersDir,
|
|
236
269
|
askFile: (id) => path.join(asksDir, `${id}.json`),
|
|
237
270
|
answerFile: (id) => path.join(answersDir, `${id}.json`),
|
|
271
|
+
heldDir,
|
|
272
|
+
// A held request's body, spooled to disk while it waits for a decision.
|
|
273
|
+
heldFile: (id) => path.join(heldDir, id),
|
|
238
274
|
/**
|
|
239
275
|
* The one path both sides agree on: the proxy listens here, the
|
|
240
276
|
* launcher binds it into the sandbox.
|
|
@@ -249,7 +285,8 @@ export function runtimePaths(runtime) {
|
|
|
249
285
|
},
|
|
250
286
|
certsDir: path.join(runtime, 'certs'),
|
|
251
287
|
caBundle: path.join(runtime, 'ca-bundle.pem'),
|
|
252
|
-
audit
|
|
288
|
+
// The one audit file, in bareguard's shape: every agent's gate and the runtime's own `sbx` gate append here (one atomic line per write).
|
|
289
|
+
audit: path.join(runtime, 'gate.jsonl'),
|
|
253
290
|
overlay: (agent) => {
|
|
254
291
|
const base = path.join(runtime, 'overlay', agent);
|
|
255
292
|
return {
|
package/src/wall.js
CHANGED
|
@@ -3,12 +3,17 @@
|
|
|
3
3
|
//
|
|
4
4
|
// Default-deny for loopback, link-local (incl. cloud metadata 169.254/16),
|
|
5
5
|
// the host's own addresses, and private LAN ranges (RFC 1918, CGNAT
|
|
6
|
-
// 100.64/10, IPv6 ULA fc00::/7).
|
|
6
|
+
// 100.64/10, IPv6 ULA fc00::/7). An IPv4 embedded in IPv6 is checked too, in
|
|
7
|
+
// every spelling: mapped, compat, uncompressed, NAT64 (RFC 6052, RFC 8215)
|
|
8
|
+
// and 6to4 (RFC 3056). The check runs AFTER DNS resolution, so a
|
|
7
9
|
// hostname that resolves to 127.0.0.1 is denied exactly like the literal.
|
|
8
10
|
// Unresolvable names are denied too (fail closed, never 502-then-dial).
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
11
|
+
// Two things let a denied destination through. The TEST-ONLY
|
|
12
|
+
// `unsafeTestOnly.allowLoopback` (loopback + unspecified) is for fixtures.
|
|
13
|
+
// `allowLocal` (the `localLlm` setting) names exact `host:port` pairs, such as
|
|
14
|
+
// a local model server: only those pass the private/loopback check, never
|
|
15
|
+
// link-local (cloud metadata), and any other port on the same host is denied
|
|
16
|
+
// as before. There is no allowPrivate flag: the wall is default-deny.
|
|
12
17
|
import net from 'node:net';
|
|
13
18
|
import os from 'node:os';
|
|
14
19
|
import { lookup as dnsLookup } from 'node:dns/promises';
|
|
@@ -22,17 +27,76 @@ function normIp(ip) {
|
|
|
22
27
|
return s;
|
|
23
28
|
}
|
|
24
29
|
|
|
25
|
-
/** Embedded IPv4 in `::ffff:1.2.3.4`, or null. */
|
|
26
|
-
function mappedV4(ip) {
|
|
27
|
-
const m = ip.match(/^(?:.*:)?(\d+\.\d+\.\d+\.\d+)$/);
|
|
28
|
-
return m && net.isIP(m[1]) === 4 ? m[1] : null;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
30
|
function v4Parts(ip) {
|
|
32
31
|
return ip.split('.').map((p) => parseInt(p, 10));
|
|
33
32
|
}
|
|
34
33
|
|
|
35
|
-
/**
|
|
34
|
+
/**
|
|
35
|
+
* Parse IPv6 into its 8 groups, handling `::` anywhere and a trailing
|
|
36
|
+
* dotted quad (`::ffff:1.2.3.4`, `64:ff9b::1.2.3.4`).
|
|
37
|
+
*
|
|
38
|
+
* @param {string} ip normalized IP spelling
|
|
39
|
+
* @returns {number[]|null} 8 groups (0–0xffff), or null when not IPv6
|
|
40
|
+
*/
|
|
41
|
+
function v6Groups(ip) {
|
|
42
|
+
if (net.isIP(ip) !== 6) return null;
|
|
43
|
+
const dbl = ip.indexOf('::');
|
|
44
|
+
if (dbl >= 0 && ip.indexOf('::', dbl + 2) >= 0) return null;
|
|
45
|
+
const parts = (s) => s.split(':').filter((p) => p !== '');
|
|
46
|
+
const head = dbl >= 0 ? parts(ip.slice(0, dbl)) : ip.split(':');
|
|
47
|
+
const tail = dbl >= 0 ? parts(ip.slice(dbl + 2)) : [];
|
|
48
|
+
const val = (s) => {
|
|
49
|
+
if (s.includes('.')) {
|
|
50
|
+
if (net.isIP(s) !== 4) return null;
|
|
51
|
+
const p = s.split('.').map((x) => parseInt(x, 10));
|
|
52
|
+
return [(p[0] << 8) | p[1], (p[2] << 8) | p[3]];
|
|
53
|
+
}
|
|
54
|
+
if (!/^[0-9a-f]{1,4}$/.test(s)) return null;
|
|
55
|
+
return [parseInt(s, 16)];
|
|
56
|
+
};
|
|
57
|
+
/** @type {number[]} */
|
|
58
|
+
const hGroups = [];
|
|
59
|
+
/** @type {number[]} */
|
|
60
|
+
const tGroups = [];
|
|
61
|
+
for (const [list, out] of [[head, hGroups], [tail, tGroups]]) {
|
|
62
|
+
for (const s of list) {
|
|
63
|
+
const v = val(s);
|
|
64
|
+
if (!v) return null;
|
|
65
|
+
out.push(...v);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (dbl < 0) return hGroups.length === 8 ? hGroups : null;
|
|
69
|
+
if (hGroups.length + tGroups.length > 8) return null;
|
|
70
|
+
return [...hGroups, ...new Array(8 - hGroups.length - tGroups.length).fill(0), ...tGroups];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Dotted IPv4 from two groups. @param {number[]} g groups @param {number} i first group @returns {string} */
|
|
74
|
+
function v4Of(g, i) {
|
|
75
|
+
return `${(g[i] >> 8) & 255}.${g[i] & 255}.${(g[i + 1] >> 8) & 255}.${g[i + 1] & 255}`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Why a dotted IPv4 is denied, or null when it may go through. The one IPv4
|
|
80
|
+
* rule set: plain IPv4 and every embedded IPv4 use this function.
|
|
81
|
+
*
|
|
82
|
+
* @param {string} v4 dotted IPv4
|
|
83
|
+
* @param {boolean} allowLoopback test-only opt-in for loopback + unspecified
|
|
84
|
+
* @returns {string|null} `loopback` / `unspecified` / `link-local` / `host-local` / `private`, or null
|
|
85
|
+
*/
|
|
86
|
+
function v4Reason(v4, allowLoopback) {
|
|
87
|
+
const [a, b] = v4Parts(v4);
|
|
88
|
+
if (a === 127) return allowLoopback ? null : 'loopback';
|
|
89
|
+
if (a === 0) return allowLoopback ? null : 'unspecified';
|
|
90
|
+
if (a === 169 && b === 254) return 'link-local';
|
|
91
|
+
if (a === 10) return 'private';
|
|
92
|
+
if (a === 172 && b >= 16 && b <= 31) return 'private';
|
|
93
|
+
if (a === 192 && b === 168) return 'private';
|
|
94
|
+
if (a === 100 && b >= 64 && b <= 127) return 'private';
|
|
95
|
+
if (localIps().has(v4)) return 'host-local';
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** This machine's own interface addresses: IPv6 keyed by parsed groups, IPv4 dotted (see `normIp`). */
|
|
36
100
|
function localIps() {
|
|
37
101
|
const out = new Set();
|
|
38
102
|
let ifs = {};
|
|
@@ -45,7 +109,10 @@ function localIps() {
|
|
|
45
109
|
}
|
|
46
110
|
for (const addrs of Object.values(ifs)) {
|
|
47
111
|
for (const a of addrs ?? []) {
|
|
48
|
-
if (a
|
|
112
|
+
if (!a || !a.address) continue;
|
|
113
|
+
const norm = normIp(a.address);
|
|
114
|
+
const g = v6Groups(norm);
|
|
115
|
+
out.add(g ? g.join(':') : norm);
|
|
49
116
|
}
|
|
50
117
|
}
|
|
51
118
|
return out;
|
|
@@ -60,28 +127,25 @@ function localIps() {
|
|
|
60
127
|
*/
|
|
61
128
|
export function denyReasonForIp(rawIp, allowLoopback) {
|
|
62
129
|
const ip = normIp(rawIp);
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
if (
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
if (localIps().has(ip)) return 'host-local';
|
|
83
|
-
return null;
|
|
84
|
-
}
|
|
130
|
+
if (net.isIP(ip) === 4) return v4Reason(ip, allowLoopback);
|
|
131
|
+
const g = v6Groups(ip);
|
|
132
|
+
if (!g) return null;
|
|
133
|
+
const zero = (a, b) => g.slice(a, b).every((x) => x === 0);
|
|
134
|
+
if (zero(0, 8)) return allowLoopback ? null : 'unspecified';
|
|
135
|
+
if (zero(0, 7) && g[7] === 1) return allowLoopback ? null : 'loopback';
|
|
136
|
+
// IPv4-mapped ::ffff:0:0/96, then compat ::/96: the embedded IPv4 decides.
|
|
137
|
+
if (zero(0, 5) && g[5] === 0xffff) return v4Reason(v4Of(g, 6), allowLoopback);
|
|
138
|
+
if (zero(0, 6)) return v4Reason(v4Of(g, 6), allowLoopback);
|
|
139
|
+
// NAT64 64:ff9b::/96: the embedded IPv4 decides. Local-use 64:ff9b:1::/48
|
|
140
|
+
// is private outright: the IPv4 position depends on the prefix length,
|
|
141
|
+
// which the wall can't know.
|
|
142
|
+
if (g[0] === 0x64 && g[1] === 0xff9b && zero(2, 6)) return v4Reason(v4Of(g, 6), allowLoopback);
|
|
143
|
+
if (g[0] === 0x64 && g[1] === 0xff9b && g[2] === 1) return 'private';
|
|
144
|
+
// 6to4 2002::/16: the next 32 bits are the IPv4.
|
|
145
|
+
if (g[0] === 0x2002) return v4Reason(v4Of(g, 1), allowLoopback);
|
|
146
|
+
if ((g[0] & 0xffc0) === 0xfe80) return 'link-local';
|
|
147
|
+
if ((g[0] & 0xfe00) === 0xfc00) return 'private';
|
|
148
|
+
if (localIps().has(g.join(':'))) return 'host-local';
|
|
85
149
|
return null;
|
|
86
150
|
}
|
|
87
151
|
|
|
@@ -137,17 +201,20 @@ function interleaveIps(ips) {
|
|
|
137
201
|
* rebinding, with fallback when the first address refuses).
|
|
138
202
|
*
|
|
139
203
|
* @param {string} host CONNECT/request hostname
|
|
140
|
-
* @param {{ allowLoopback: boolean, resolveUpstream?: (host: string) => Promise<string[] | string | null> }} gate
|
|
204
|
+
* @param {{ allowLoopback: boolean, allowLocal?: ReadonlySet<string>, resolveUpstream?: (host: string) => Promise<string[] | string | null> }} gate
|
|
205
|
+
* @param {number} port destination port (matched against `gate.allowLocal`)
|
|
141
206
|
* @returns {Promise<{ ok: true, ips: string[] } | { ok: false, ip: string, reason: string }>}
|
|
142
207
|
*/
|
|
143
|
-
export async function checkUpstream(host, gate) {
|
|
208
|
+
export async function checkUpstream(host, gate, port) {
|
|
144
209
|
const ips = await resolveAllUpstream(host, gate.resolveUpstream);
|
|
145
210
|
if (!ips || !ips.length) {
|
|
146
211
|
return { ok: false, ip: host, reason: `unresolvable upstream denied: ${host}` };
|
|
147
212
|
}
|
|
213
|
+
const listed = gate.allowLocal?.has(`${host.toLowerCase()}:${port}`) === true;
|
|
148
214
|
for (const ip of ips) {
|
|
149
215
|
const kind = denyReasonForIp(ip, gate.allowLoopback);
|
|
150
|
-
|
|
216
|
+
// A listed host:port waives everything but link-local (cloud metadata).
|
|
217
|
+
if (kind && !(listed && kind !== 'link-local')) {
|
|
151
218
|
const where = ip === host ? host : `${host} (${ip})`;
|
|
152
219
|
return { ok: false, ip, reason: `${kind} upstream denied: ${where}` };
|
|
153
220
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Create a streaming card-number scanner.
|
|
3
|
+
* @returns {{ push(chunk: Buffer): boolean, readonly found: boolean, readonly tailLength: number }}
|
|
4
|
+
* `push` returns `found`; `tailLength` is the retained byte count (<= 40).
|
|
5
|
+
*/
|
|
6
|
+
export function createCardScanner(): {
|
|
7
|
+
push(chunk: Buffer): boolean;
|
|
8
|
+
readonly found: boolean;
|
|
9
|
+
readonly tailLength: number;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Replace every card candidate's digits with `*` except the last 4,
|
|
13
|
+
* keeping the separators.
|
|
14
|
+
* @param {string} text
|
|
15
|
+
* @returns {string}
|
|
16
|
+
*/
|
|
17
|
+
export function maskCards(text: string): string;
|
package/types/cli.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
1
|
+
#!/usr/bin/env -S node --max-semi-space-size=1
|
|
2
2
|
export {};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the config file lives.
|
|
3
|
+
*
|
|
4
|
+
* @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
|
|
5
|
+
* @returns {string} absolute path of `config.json`
|
|
6
|
+
*/
|
|
7
|
+
export function configPath(env?: NodeJS.ProcessEnv): string;
|
|
8
|
+
/**
|
|
9
|
+
* Read the config file over the defaults. No file means defaults.
|
|
10
|
+
*
|
|
11
|
+
* @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
|
|
12
|
+
* @returns {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number }} effective settings (`heldBodyMaxMB` absent means the library default)
|
|
13
|
+
* @throws {Error} naming the file (and the key) on invalid JSON, an unknown key or a bad value
|
|
14
|
+
*/
|
|
15
|
+
export function loadConfig(env?: NodeJS.ProcessEnv): {
|
|
16
|
+
mode: string;
|
|
17
|
+
holdTimeoutSec: number | string;
|
|
18
|
+
localLlm: string[];
|
|
19
|
+
labels: string[];
|
|
20
|
+
tenants: Record<string, string[]>;
|
|
21
|
+
heldBodyMaxMB?: number;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Settings for one `sbx run`: a CLI flag beats the file, the file beats the default.
|
|
25
|
+
*
|
|
26
|
+
* @param {object} [flags] values given on the command line
|
|
27
|
+
* @param {string} [flags.mode] `--mode`
|
|
28
|
+
* @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
|
|
29
|
+
* @returns {{ mode: string, holdTimeoutSec: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number }} effective settings (`heldBodyMaxMB` absent means the library default)
|
|
30
|
+
* @throws {Error} as {@link loadConfig}
|
|
31
|
+
*/
|
|
32
|
+
export function resolveConfig(flags?: {
|
|
33
|
+
mode?: string | undefined;
|
|
34
|
+
}, env?: NodeJS.ProcessEnv): {
|
|
35
|
+
mode: string;
|
|
36
|
+
holdTimeoutSec: number | string;
|
|
37
|
+
localLlm: string[];
|
|
38
|
+
labels: string[];
|
|
39
|
+
tenants: Record<string, string[]>;
|
|
40
|
+
heldBodyMaxMB?: number;
|
|
41
|
+
};
|