barebox 0.12.0 → 0.14.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 +32 -0
- package/README.md +69 -135
- package/barebox.context.md +24 -5
- package/package.json +2 -2
- package/src/cli.js +8 -9
- package/src/config.js +18 -2
- package/src/effect.js +139 -0
- package/src/holds.js +68 -20
- package/src/launcher.js +1 -1
- package/src/lists.js +78 -1
- package/src/policy.js +1 -1
- package/src/prompt.js +54 -2
- package/src/proxy.js +166 -21
- package/src/run.js +4 -2
- package/types/config.d.ts +10 -2
- package/types/effect.d.ts +31 -0
- package/types/holds.d.ts +37 -4
- package/types/lists.d.ts +20 -0
- package/types/prompt.d.ts +31 -1
- package/types/proxy.d.ts +8 -0
- package/types/run.d.ts +14 -1
package/src/effect.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// effect.js — what a request body does: the recipient, amount and currency
|
|
2
|
+
// fields in it, found by common field names (generic, no per-vendor rules).
|
|
3
|
+
// Pure (no I/O). The caller passes the body text the body view produced.
|
|
4
|
+
//
|
|
5
|
+
// The rule: return every match up to LIST_MAX + 1, shallowest path first, never
|
|
6
|
+
// only the first, so a decoy top-level `to` can never hide a nested real
|
|
7
|
+
// recipient. A list that reaches LIST_MAX + 1 means "more than LIST_MAX": the
|
|
8
|
+
// caller lists none of them (too many to tell the real one). A body
|
|
9
|
+
// that cannot be read says why in `notRead` instead of showing nothing.
|
|
10
|
+
import { maskCards } from './cardscan.js';
|
|
11
|
+
|
|
12
|
+
const NAMES = {
|
|
13
|
+
recipient: new Set(['to', 'recipient', 'recipients', 'email', 'channel', 'chat_id', 'phone']),
|
|
14
|
+
amount: new Set(['amount', 'value', 'amount_money', 'total']),
|
|
15
|
+
currency: new Set(['currency', 'currency_code']),
|
|
16
|
+
};
|
|
17
|
+
const VALUE_CAP = 200;
|
|
18
|
+
const PATH_CAP = 200;
|
|
19
|
+
/** The one limit: a kind with more than this many matches is shown as "more than LIST_MAX", never as a list. Each kind keeps at most LIST_MAX + 1. */
|
|
20
|
+
export const LIST_MAX = 5;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @typedef {object} EffectField
|
|
24
|
+
* @property {string} path where it sits in the body: `a.b[0].c` for JSON, the key as sent for a form
|
|
25
|
+
* @property {string} value the scalar value, masked for card numbers and cut at 200 chars
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @typedef {object} Effect
|
|
30
|
+
* @property {EffectField[]} recipient
|
|
31
|
+
* @property {EffectField[]} amount
|
|
32
|
+
* @property {EffectField[]} currency
|
|
33
|
+
* @property {string|null} notRead why the body was not read (the three lists are then empty), else null
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
/** @param {string} reason @returns {Effect} */
|
|
37
|
+
function unread(reason) {
|
|
38
|
+
return { recipient: [], amount: [], currency: [], notRead: reason };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @param {string} name a key name
|
|
43
|
+
* @returns {'recipient'|'amount'|'currency'|null}
|
|
44
|
+
*/
|
|
45
|
+
function kindOf(name) {
|
|
46
|
+
const n = name.toLowerCase();
|
|
47
|
+
for (const kind of /** @type {const} */ (['recipient', 'amount', 'currency'])) {
|
|
48
|
+
if (NAMES[kind].has(n)) return kind;
|
|
49
|
+
}
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @param {Effect} out
|
|
55
|
+
* @param {'recipient'|'amount'|'currency'} kind
|
|
56
|
+
* @param {string} path
|
|
57
|
+
* @param {unknown} value
|
|
58
|
+
*/
|
|
59
|
+
function add(out, kind, path, value) {
|
|
60
|
+
if (out[kind].length > LIST_MAX) return;
|
|
61
|
+
out[kind].push({ path: path.slice(0, PATH_CAP), value: maskCards(String(value)).slice(0, VALUE_CAP) });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Breadth-first, so matches come out shallowest first and in document order
|
|
66
|
+
* within a depth, and a deeply nested body cannot overflow the stack. A
|
|
67
|
+
* scalar inside an array is judged by the key the array sits under.
|
|
68
|
+
*
|
|
69
|
+
* @param {Effect} out
|
|
70
|
+
* @param {unknown} root
|
|
71
|
+
*/
|
|
72
|
+
function walkJson(out, root) {
|
|
73
|
+
/** @type {{ v: unknown, path: string, key: string|null }[]} */
|
|
74
|
+
const queue = [{ v: root, path: '', key: null }];
|
|
75
|
+
for (let i = 0; i < queue.length; i++) {
|
|
76
|
+
const { v, path, key } = queue[i];
|
|
77
|
+
if (Array.isArray(v)) {
|
|
78
|
+
v.forEach((item, n) => queue.push({ v: item, path: path.length >= PATH_CAP ? path : `${path}[${n}]`.slice(0, PATH_CAP), key }));
|
|
79
|
+
} else if (v !== null && typeof v === 'object') {
|
|
80
|
+
for (const k of Object.keys(v)) {
|
|
81
|
+
queue.push({ v: /** @type {Record<string, unknown>} */ (v)[k], path: path.length >= PATH_CAP ? path : (path ? `${path}.${k}` : k).slice(0, PATH_CAP), key: k });
|
|
82
|
+
}
|
|
83
|
+
} else if (v !== null && key !== null) {
|
|
84
|
+
const kind = kindOf(key);
|
|
85
|
+
if (kind) add(out, kind, path, v);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* A form key `metadata[x]` is named by its last bracket segment; the path is
|
|
92
|
+
* the key as sent. Shallowest first: fewer bracket segments first, stable.
|
|
93
|
+
*
|
|
94
|
+
* @param {Effect} out
|
|
95
|
+
* @param {string} text
|
|
96
|
+
*/
|
|
97
|
+
function walkForm(out, text) {
|
|
98
|
+
const rows = [];
|
|
99
|
+
for (const [k, v] of new URLSearchParams(text)) {
|
|
100
|
+
const segs = k.split(/\[|\]/).filter(Boolean);
|
|
101
|
+
rows.push({ k, v, depth: segs.length, name: segs[segs.length - 1] ?? k });
|
|
102
|
+
}
|
|
103
|
+
rows.sort((a, b) => a.depth - b.depth);
|
|
104
|
+
for (const { k, v, name } of rows) {
|
|
105
|
+
const kind = kindOf(name);
|
|
106
|
+
if (kind) add(out, kind, k, v);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Find every recipient, amount and currency field in a body.
|
|
112
|
+
*
|
|
113
|
+
* @param {string|Buffer} text the body text (decoded when the body view decoded it)
|
|
114
|
+
* @param {string|undefined} contentType the Content-Type header value
|
|
115
|
+
* @param {'plain'|'decoded'|'truncated'|'unread'|'over'} state the body view state, or `over` when the body
|
|
116
|
+
* is over 64 KB and was not viewed
|
|
117
|
+
* @returns {Effect}
|
|
118
|
+
*/
|
|
119
|
+
export function findEffect(text, contentType, state) {
|
|
120
|
+
if (state === 'unread') return unread('encoding not decoded');
|
|
121
|
+
if (state === 'over') return unread('body over 64 KB');
|
|
122
|
+
const type = String(contentType ?? '').split(';')[0].trim().toLowerCase();
|
|
123
|
+
const isJson = type === 'application/json' || type.endsWith('+json');
|
|
124
|
+
const isForm = type === 'application/x-www-form-urlencoded';
|
|
125
|
+
if (!isJson && !isForm) return unread(`${type || 'no content type'} not read`);
|
|
126
|
+
const out = { recipient: [], amount: [], currency: [], notRead: null };
|
|
127
|
+
if (isForm) {
|
|
128
|
+
walkForm(out, String(text));
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
let parsed;
|
|
132
|
+
try {
|
|
133
|
+
parsed = JSON.parse(String(text));
|
|
134
|
+
} catch {
|
|
135
|
+
return unread('body is not valid JSON');
|
|
136
|
+
}
|
|
137
|
+
walkJson(out, parsed);
|
|
138
|
+
return out;
|
|
139
|
+
}
|
package/src/holds.js
CHANGED
|
@@ -117,6 +117,10 @@ const MAX_WAITING_PER_AGENT = 16;
|
|
|
117
117
|
* @property {string} letter the matched rwx letter, `'x'` when the ask names none
|
|
118
118
|
* @property {string} bodyPreview request body preview, utf8, capped at ASK_BODY_LIMIT bytes, card numbers masked
|
|
119
119
|
* @property {boolean} truncated true when the body exceeded ASK_BODY_LIMIT
|
|
120
|
+
* @property {{ kind: 'pay'|'send'|string, entry: string }} [floor] present when the request hit a domain the user listed in config `floor` (kind: which list, entry: the matching entry)
|
|
121
|
+
* @property {import('./effect.js').Effect} [effect] present on a floor request with a body: the recipient, amount and currency fields found in it (values masked for card numbers), or why it was not read
|
|
122
|
+
* @property {string} [keyLast4] present on a model call whose key is not this run's: the key's last 4 characters (never more)
|
|
123
|
+
* @property {'none'|'other'} [modelKey] present on a model call whose key is not this run's: 'none' (no key header) or 'other' (a key, possibly too short for a last 4)
|
|
120
124
|
* @property {number} waitingSec 0 at park; readers use the file mtime for a live value
|
|
121
125
|
* @property {string|null} expiresAt ISO-8601 UTC deadline, or null when `timeoutMs: 'never'`
|
|
122
126
|
*/
|
|
@@ -128,20 +132,32 @@ const MAX_WAITING_PER_AGENT = 16;
|
|
|
128
132
|
*/
|
|
129
133
|
|
|
130
134
|
/**
|
|
131
|
-
*
|
|
135
|
+
* Write `text` to a fresh 0600 temp file next to `file` (parent made on demand).
|
|
136
|
+
* The caller renames or links it into place.
|
|
132
137
|
*
|
|
133
|
-
* @param {string} file destination path
|
|
138
|
+
* @param {string} file destination path the temp file sits beside
|
|
134
139
|
* @param {string} text content
|
|
135
|
-
* @returns {
|
|
140
|
+
* @returns {string} path of the temp file
|
|
136
141
|
*/
|
|
137
|
-
export function
|
|
142
|
+
export function writeTmpFile(file, text) {
|
|
138
143
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
139
144
|
const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
|
|
140
145
|
// 0600, not the 0644 default: asks carry the audit trail and unredacted
|
|
141
146
|
// body previews, and answers carry the decision. (Umask can only remove
|
|
142
147
|
// bits from 0600, never add group/other access.)
|
|
143
148
|
fs.writeFileSync(tmp, text, { mode: 0o600 });
|
|
144
|
-
|
|
149
|
+
return tmp;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Atomic write: tmp file + rename, so readers never see a partial payload.
|
|
154
|
+
*
|
|
155
|
+
* @param {string} file destination path
|
|
156
|
+
* @param {string} text content
|
|
157
|
+
* @returns {void}
|
|
158
|
+
*/
|
|
159
|
+
export function writeFileAtomic(file, text) {
|
|
160
|
+
fs.renameSync(writeTmpFile(file, text), file);
|
|
145
161
|
}
|
|
146
162
|
|
|
147
163
|
let consumeN = 0;
|
|
@@ -234,8 +250,8 @@ export function normalizeDecision(input, { approveAlias = false } = {}) {
|
|
|
234
250
|
* @param {number} [opts.pollMs] answer poll interval in ms for the default file checkpoint (default 250, PRD Q9)
|
|
235
251
|
* @param {OnEvent|null} [opts.onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon
|
|
236
252
|
* @param {(entry: object) => void} opts.onApprove forward the parked request upstream
|
|
237
|
-
* @param {(entry: object, reason: string) => void} opts.onDeny refuse the parked request
|
|
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
|
|
253
|
+
* @param {(entry: object, reason: string, answered: boolean) => void} opts.onDeny refuse the parked request; `answered`: a person's answer or the hold timeout ended it (not a cancel, a close or a channel failure)
|
|
254
|
+
* @returns {{ add: (entry: object) => string|null, dropBody: (id: string) => void, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string, answered?: boolean) => void }) => { state: 'now'|'queued'|'full', id: string, arrivedAt: number, cancel: () => void }, abandon: (id: string) => void, abandonSocket: (sock: object) => void, wait: (agent: string) => (() => void)|null, pending: () => HeldRequest[], close: () => void }} queue handle
|
|
239
255
|
*/
|
|
240
256
|
export function createHolds({ log, timeoutMs = 120000,
|
|
241
257
|
maxBody = DEFAULT_HOLD_MAX_BODY, runtime = null, onAsk = null, pollMs = DEFAULT_POLL_MS,
|
|
@@ -307,7 +323,9 @@ export function createHolds({ log, timeoutMs = 120000,
|
|
|
307
323
|
* @type {Map<string, { holder: object|null, line: Array<object> }>}
|
|
308
324
|
*/
|
|
309
325
|
const slots = new Map();
|
|
310
|
-
/**
|
|
326
|
+
/** Requests waiting behind another request's open model-key ask, by agent. @type {Map<string, number>} */
|
|
327
|
+
const waits = new Map();
|
|
328
|
+
/** Internal reserve state by returned handle identity. @type {WeakMap<object, { agent: string, onReady: () => void, onExpire: (reason: string, answered?: boolean) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean, id: string }>} */
|
|
311
329
|
const handleState = new WeakMap();
|
|
312
330
|
|
|
313
331
|
/**
|
|
@@ -335,7 +353,7 @@ export function createHolds({ log, timeoutMs = 120000,
|
|
|
335
353
|
if (!s.holder && s.line.length === 0) slots.delete(agent);
|
|
336
354
|
}
|
|
337
355
|
}
|
|
338
|
-
st.onExpire(reason);
|
|
356
|
+
st.onExpire(reason, true);
|
|
339
357
|
}
|
|
340
358
|
|
|
341
359
|
/**
|
|
@@ -383,6 +401,10 @@ export function createHolds({ log, timeoutMs = 120000,
|
|
|
383
401
|
letter: entry.letter ?? 'x',
|
|
384
402
|
bodyPreview: entry.preview,
|
|
385
403
|
truncated: entry.bodyBytes > ASK_BODY_LIMIT,
|
|
404
|
+
...(entry.floor ? { floor: entry.floor } : {}),
|
|
405
|
+
...(entry.effect ? { effect: entry.effect } : {}),
|
|
406
|
+
...(entry.keyLast4 ? { keyLast4: entry.keyLast4 } : {}),
|
|
407
|
+
...(entry.modelKey ? { modelKey: entry.modelKey } : {}),
|
|
386
408
|
waitingSec: 0,
|
|
387
409
|
// ISO-8601 UTC (not epoch ms): readable in `sbx pending` and logs.
|
|
388
410
|
expiresAt: ms === null ? null : new Date(entry.t0 + ms).toISOString(),
|
|
@@ -408,7 +430,7 @@ export function createHolds({ log, timeoutMs = 120000,
|
|
|
408
430
|
try { fs.unlinkSync(paths.heldFile(id)); } catch {}
|
|
409
431
|
}
|
|
410
432
|
|
|
411
|
-
function settle(id, approved, reason) {
|
|
433
|
+
function settle(id, approved, reason, answered = false) {
|
|
412
434
|
const h = queue.get(id);
|
|
413
435
|
if (!h) return `unknown ${id}`;
|
|
414
436
|
queue.delete(id);
|
|
@@ -422,7 +444,7 @@ export function createHolds({ log, timeoutMs = 120000,
|
|
|
422
444
|
} else {
|
|
423
445
|
dropBody(id);
|
|
424
446
|
log({ ev: 'decide', id, agent: h.agent, decision, reason });
|
|
425
|
-
onDeny(h, reason);
|
|
447
|
+
onDeny(h, reason, answered);
|
|
426
448
|
}
|
|
427
449
|
onEvent?.({ type: 'decided', id, decision, reason: reason || undefined });
|
|
428
450
|
return approved ? `approved ${id}` : `denied ${id}`;
|
|
@@ -456,15 +478,17 @@ export function createHolds({ log, timeoutMs = 120000,
|
|
|
456
478
|
if (!useFiles) {
|
|
457
479
|
/** @type {{ decision?: unknown, reason?: unknown } | null} */
|
|
458
480
|
let raw = null;
|
|
481
|
+
let failed = false;
|
|
459
482
|
try {
|
|
460
483
|
raw = await onAsk(ask);
|
|
461
484
|
} catch (e) {
|
|
485
|
+
failed = true;
|
|
462
486
|
const msg = e instanceof Error ? e.message : String(e);
|
|
463
487
|
raw = { decision: 'deny', reason: `onAsk failed: ${msg}` };
|
|
464
488
|
}
|
|
465
489
|
const norm = normalizeDecision(raw);
|
|
466
490
|
if (norm && norm.decision === 'allow') settle(entry.id, true, '');
|
|
467
|
-
else settle(entry.id, false, norm?.reason ?? 'denied');
|
|
491
|
+
else settle(entry.id, false, norm?.reason ?? 'denied', !failed && norm !== null);
|
|
468
492
|
}
|
|
469
493
|
}
|
|
470
494
|
|
|
@@ -503,7 +527,7 @@ export function createHolds({ log, timeoutMs = 120000,
|
|
|
503
527
|
log({ ev: 'stale-answer', id, note: 'unknown or already-settled id; ignored' });
|
|
504
528
|
continue;
|
|
505
529
|
}
|
|
506
|
-
settle(id, norm.decision === 'allow', norm.reason ?? '');
|
|
530
|
+
settle(id, norm.decision === 'allow', norm.reason ?? '', true);
|
|
507
531
|
}
|
|
508
532
|
}
|
|
509
533
|
|
|
@@ -521,7 +545,8 @@ export function createHolds({ log, timeoutMs = 120000,
|
|
|
521
545
|
* parks nothing and returns `null`. Without `slot`, parks exactly as
|
|
522
546
|
* before, without limit.
|
|
523
547
|
*
|
|
524
|
-
* The entry carries
|
|
548
|
+
* The entry also carries `floor` and `effect` for a floor request, and `keyLast4` / `modelKey` for a model call with another key (ask file only).
|
|
549
|
+
* It carries the masked `preview` and the full `bodyBytes`, never
|
|
525
550
|
* the body itself (the proxy spooled it to `heldFile(id)`). `finish` is
|
|
526
551
|
* the proxy's resolver for the request's pending ask: the queue never
|
|
527
552
|
* calls it directly, `onApprove` / `onDeny` do.
|
|
@@ -529,7 +554,7 @@ export function createHolds({ log, timeoutMs = 120000,
|
|
|
529
554
|
* @param {object} entry queue entry
|
|
530
555
|
* @returns {string|null} hold id, or null for a finished slot
|
|
531
556
|
*/
|
|
532
|
-
add({ agent, method, url, preview = '', bodyBytes = 0, sock, note, letter, finish, slot, arrivedAt }) {
|
|
557
|
+
add({ agent, method, url, preview = '', bodyBytes = 0, effect, floor, keyLast4, modelKey, sock, note, letter, finish, slot, arrivedAt }) {
|
|
533
558
|
const hst = typeof slot === 'object' && slot !== null ? handleState.get(slot) : undefined;
|
|
534
559
|
const s = slots.get(agent);
|
|
535
560
|
if (slot && (!hst || hst.done || !s || s.holder !== slot)) return null;
|
|
@@ -537,10 +562,10 @@ export function createHolds({ log, timeoutMs = 120000,
|
|
|
537
562
|
const ms = deadlineMs();
|
|
538
563
|
const t0 = typeof arrivedAt === 'number' ? arrivedAt : Date.now();
|
|
539
564
|
const entry = {
|
|
540
|
-
id, agent, method, url, preview, bodyBytes, sock, note, letter, finish, t0,
|
|
565
|
+
id, agent, method, url, preview, bodyBytes, effect, floor, keyLast4, modelKey, sock, note, letter, finish, t0,
|
|
541
566
|
slot: null,
|
|
542
567
|
timer: ms === null ? null
|
|
543
|
-
: setTimeout(() => settle(id, false, 'hold timeout'), Math.max(0, ms - (Date.now() - t0))),
|
|
568
|
+
: setTimeout(() => settle(id, false, 'hold timeout', true), Math.max(0, ms - (Date.now() - t0))),
|
|
544
569
|
};
|
|
545
570
|
// Unref: a parked `never` hold must not keep the process alive by itself.
|
|
546
571
|
if (entry.timer?.unref) entry.timer.unref();
|
|
@@ -561,7 +586,7 @@ export function createHolds({ log, timeoutMs = 120000,
|
|
|
561
586
|
/**
|
|
562
587
|
* Ask for this agent's hold slot before reading a held request's body.
|
|
563
588
|
* @param {string} agent
|
|
564
|
-
* @param {{ onReady: () => void, onExpire: (reason: string) => void }} cbs
|
|
589
|
+
* @param {{ onReady: () => void, onExpire: (reason: string, answered?: boolean) => void }} cbs
|
|
565
590
|
* The handle's `id` is the id its hold will have (empty when `full`), so
|
|
566
591
|
* the body file can be named before the hold parks.
|
|
567
592
|
* @returns {{ state: 'now'|'queued'|'full', id: string, arrivedAt: number, cancel: () => void }}
|
|
@@ -572,7 +597,7 @@ export function createHolds({ log, timeoutMs = 120000,
|
|
|
572
597
|
// receives that same object as `slot`, so holder comparisons use it.
|
|
573
598
|
// The one deadline timer lives here, armed below for 'now' and
|
|
574
599
|
// 'queued' alike; expiry runs through `expireReservation` only.
|
|
575
|
-
/** @type {{ agent: string, onReady: () => void, onExpire: (reason: string) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean, id: string }} */
|
|
600
|
+
/** @type {{ agent: string, onReady: () => void, onExpire: (reason: string, answered?: boolean) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean, id: string }} */
|
|
576
601
|
const st = { agent, onReady, onExpire, timer: null, consumed: false, done: false, id: '' };
|
|
577
602
|
const s0 = slots.get(agent);
|
|
578
603
|
/** @type {'now'|'queued'|'full'} */
|
|
@@ -630,7 +655,7 @@ export function createHolds({ log, timeoutMs = 120000,
|
|
|
630
655
|
removeAskFile(id);
|
|
631
656
|
dropBody(id);
|
|
632
657
|
log({ ev: 'hold-abandoned', id, agent: h.agent, method: h.method, url: h.url });
|
|
633
|
-
onDeny(h, 'client gone');
|
|
658
|
+
onDeny(h, 'client gone', false);
|
|
634
659
|
onEvent?.({ type: 'decided', id, decision: 'deny', reason: 'client gone' });
|
|
635
660
|
},
|
|
636
661
|
|
|
@@ -642,6 +667,29 @@ export function createHolds({ log, timeoutMs = 120000,
|
|
|
642
667
|
|
|
643
668
|
dropBody,
|
|
644
669
|
|
|
670
|
+
/**
|
|
671
|
+
* A place among the agent's waiters (requests waiting behind an open model-key ask), bounded
|
|
672
|
+
* by the same MAX_WAITING_PER_AGENT as the hold line. The one owner of that count.
|
|
673
|
+
*
|
|
674
|
+
* @param {string} agent agent name
|
|
675
|
+
* @returns {(() => void)|null} the release (idempotent), or null when the agent already has the maximum waiting
|
|
676
|
+
*/
|
|
677
|
+
wait(agent) {
|
|
678
|
+
const n = waits.get(agent) ?? 0;
|
|
679
|
+
if (n >= MAX_WAITING_PER_AGENT) {
|
|
680
|
+
log({ ev: 'hold-queue-full', agent, waiting: true });
|
|
681
|
+
return null;
|
|
682
|
+
}
|
|
683
|
+
waits.set(agent, n + 1);
|
|
684
|
+
let done = false;
|
|
685
|
+
return () => {
|
|
686
|
+
if (done) return;
|
|
687
|
+
done = true;
|
|
688
|
+
const left = (waits.get(agent) ?? 1) - 1;
|
|
689
|
+
if (left > 0) waits.set(agent, left); else waits.delete(agent);
|
|
690
|
+
};
|
|
691
|
+
},
|
|
692
|
+
|
|
645
693
|
pending() { return [...queue.values()].map(pub); },
|
|
646
694
|
|
|
647
695
|
close() {
|
package/src/launcher.js
CHANGED
|
@@ -268,7 +268,7 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
|
|
|
268
268
|
// same real path, so it is subsumed here.
|
|
269
269
|
const same = bases.findIndex(([realBase]) => realRt === realBase);
|
|
270
270
|
if (same >= 0) {
|
|
271
|
-
const what = same ===
|
|
271
|
+
const what = roots[same] === home ? 'HOME' : roots[same] === proj ? 'the project dir' : roots[same] === nodeBind ? 'the Node install dir' : roots[same];
|
|
272
272
|
throw new Error(`launch: runtime must not be ${what} itself (its sockets cannot be hidden there)`);
|
|
273
273
|
}
|
|
274
274
|
// Mask the sandbox-visible spelling join(root, relative(realRoot, realRt)):
|
package/src/lists.js
CHANGED
|
@@ -6,9 +6,18 @@
|
|
|
6
6
|
// every server in it). The host is checked in a Map first: rwxmap's `match()` runs
|
|
7
7
|
// a classifier on every miss, and most requests are for hosts on no list.
|
|
8
8
|
import { matcherFrom } from 'rwxmap/match';
|
|
9
|
+
import { hostMatcher } from 'bareguard';
|
|
9
10
|
|
|
10
11
|
const METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'];
|
|
11
12
|
|
|
13
|
+
/**
|
|
14
|
+
* The one trailing-dot rule: `api.anthropic.com.` is `api.anthropic.com`.
|
|
15
|
+
*
|
|
16
|
+
* @param {string} host a hostname
|
|
17
|
+
* @returns {string} the host without one trailing dot
|
|
18
|
+
*/
|
|
19
|
+
const stripDot = (host) => (host.endsWith('.') ? host.slice(0, -1) : host);
|
|
20
|
+
|
|
12
21
|
/**
|
|
13
22
|
* The one place a request URL is normalised: one trailing dot is stripped from the
|
|
14
23
|
* host (`api.anthropic.com.` is `api.anthropic.com`). Throws like `URL` on a non-URL.
|
|
@@ -18,7 +27,7 @@ const METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'];
|
|
|
18
27
|
*/
|
|
19
28
|
export function normalizeUrl(url) {
|
|
20
29
|
const u = new URL(url);
|
|
21
|
-
|
|
30
|
+
u.hostname = stripDot(u.hostname);
|
|
22
31
|
return u.href;
|
|
23
32
|
}
|
|
24
33
|
|
|
@@ -75,3 +84,71 @@ export function endpointList(entries, makeMatcher = matcherFrom) {
|
|
|
75
84
|
},
|
|
76
85
|
};
|
|
77
86
|
}
|
|
87
|
+
|
|
88
|
+
/** `"METHOD host/path"` has a space; a host or `*.domain` entry never does. @param {unknown} e @returns {boolean} */
|
|
89
|
+
export const isEndpoint = (e) => typeof e === 'string' && e.includes(' ');
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The floor's endpoint spelling rule, for the request path only: per segment drop
|
|
93
|
+
* `;params`, decode `%XX` of unreserved characters (`A-Z a-z 0-9 - . _ ~`), lowercase.
|
|
94
|
+
* Reserved escapes (`%2F`) stay, so `/v1/charges%2Fx` is still a different path.
|
|
95
|
+
*
|
|
96
|
+
* @param {string} url full request URL
|
|
97
|
+
* @returns {string} the same URL with the path spelled one way
|
|
98
|
+
*/
|
|
99
|
+
function floorSpelling(url) {
|
|
100
|
+
const u = new URL(url);
|
|
101
|
+
u.pathname = u.pathname.split('/').map((seg) => seg.split(';')[0]
|
|
102
|
+
.replace(/%([0-9A-Fa-f]{2})/g, (m, h) => { const c = String.fromCharCode(parseInt(h, 16)); return /[A-Za-z0-9\-._~]/.test(c) ? c : m; })
|
|
103
|
+
.toLowerCase()).join('/');
|
|
104
|
+
return u.href;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Build the floor lists (M11): the domains the user listed for payments (`pay`)
|
|
109
|
+
* and sends (`send`). A host or `*.domain` entry hits any request whose method is
|
|
110
|
+
* not GET/HEAD; a `"METHOD host/path"` entry hits only that endpoint. Zero built-in
|
|
111
|
+
* entries. `pay` wins when an entry is in both.
|
|
112
|
+
*
|
|
113
|
+
* @param {{ pay?: string[], send?: string[] }} [lists] the config `floor` key
|
|
114
|
+
* @param {typeof matcherFrom} [makeMatcher] builds one host's matcher (a test counts its `match` calls)
|
|
115
|
+
* @returns {{ match: (method: string, hostname: string, url: string) => { kind: 'pay'|'send', entry: string } | null }} `match` takes the request's parsed hostname; it throws (the caller fails closed) on a hostname `hostMatcher` refuses
|
|
116
|
+
*/
|
|
117
|
+
export function floorList({ pay = [], send = [] } = {}, makeMatcher = matcherFrom) {
|
|
118
|
+
const kinds = /** @type {const} */ (['pay', 'send']).map((kind) => {
|
|
119
|
+
const entries = kind === 'pay' ? pay : send;
|
|
120
|
+
const hostEntries = entries.filter((e) => !isEndpoint(e));
|
|
121
|
+
const endpointEntries = entries.filter(isEndpoint);
|
|
122
|
+
// Entry paths are lowercased to match the lowercased request path; `written` maps back to the string the user wrote.
|
|
123
|
+
/** @type {Map<string, string>} */
|
|
124
|
+
const written = new Map();
|
|
125
|
+
const lowered = endpointEntries.map((e) => {
|
|
126
|
+
const { method, host, path } = parseEntry(e);
|
|
127
|
+
const l = `${method} ${host}${path.toLowerCase()}`;
|
|
128
|
+
if (!written.has(l)) written.set(l, e);
|
|
129
|
+
return l;
|
|
130
|
+
});
|
|
131
|
+
return {
|
|
132
|
+
kind,
|
|
133
|
+
written,
|
|
134
|
+
hosts: hostEntries.length ? hostMatcher(hostEntries) : null,
|
|
135
|
+
endpoints: endpointEntries.length ? endpointList(lowered, makeMatcher) : null,
|
|
136
|
+
// The port is dropped: the request's hostname never carries one; endpointList then checks it exactly.
|
|
137
|
+
endpointHosts: new Set(endpointEntries.map((e) => parseEntry(e).host.replace(/:\d+$/, ''))),
|
|
138
|
+
};
|
|
139
|
+
});
|
|
140
|
+
return {
|
|
141
|
+
match(method, hostname, url) {
|
|
142
|
+
const host = stripDot(hostname);
|
|
143
|
+
const m = method.toUpperCase();
|
|
144
|
+
const write = m !== 'GET' && m !== 'HEAD';
|
|
145
|
+
for (const { kind, written, hosts, endpoints, endpointHosts } of kinds) {
|
|
146
|
+
const byHost = write && hosts ? hosts.match(host) : null;
|
|
147
|
+
if (byHost !== null) return { kind, entry: byHost };
|
|
148
|
+
const byEndpoint = endpoints && endpointHosts.has(host) ? endpoints.match(method, floorSpelling(url)) : null;
|
|
149
|
+
if (byEndpoint !== null) return { kind, entry: /** @type {string} */ (written.get(byEndpoint)) };
|
|
150
|
+
}
|
|
151
|
+
return null;
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
}
|
package/src/policy.js
CHANGED
|
@@ -140,7 +140,7 @@ export function toolFor(matcher, tools, method, url, models) {
|
|
|
140
140
|
}
|
|
141
141
|
|
|
142
142
|
/** @type {Record<string, Record<string, 'ask' | 'deny'>>} */
|
|
143
|
-
const FLAGS = { cardLike: { true: 'ask' }, paymentPath: { true: 'ask' } };
|
|
143
|
+
const FLAGS = { cardLike: { true: 'ask' }, paymentPath: { true: 'ask' }, floor: { pay: 'ask', send: 'ask' } };
|
|
144
144
|
|
|
145
145
|
/** Payment-destination path fragments: the URL-visible half of the floor (PRD section 2). */
|
|
146
146
|
const PAYMENT_PATHS = ['/checkout', '/payment', '/orders', '/purchase'];
|
package/src/prompt.js
CHANGED
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
// question open is dropped (so a `y` typed during h1 never approves h2), and
|
|
9
9
|
// once a hold is decided elsewhere nothing is written for it.
|
|
10
10
|
import { safe } from './runtime.js';
|
|
11
|
+
import { isEndpoint } from './lists.js';
|
|
12
|
+
import { LIST_MAX } from './effect.js';
|
|
11
13
|
|
|
12
14
|
const BODY_CHARS = 200;
|
|
13
15
|
const EOL = /\r\n|\r|\n/;
|
|
@@ -27,7 +29,51 @@ export const ANSI = { bold: '\x1b[1m', dim: '\x1b[2m', red: '\x1b[31m', green: '
|
|
|
27
29
|
*/
|
|
28
30
|
export const paint = (on, codes, text) => (on ? `${codes}${text}${ANSI.reset}` : text);
|
|
29
31
|
|
|
30
|
-
/** @typedef {{ id: string, agent?: string, method: string, url: string, rule: string, letter: string, bodyPreview?: string, expiresAt?: string|null }} AskRecord */
|
|
32
|
+
/** @typedef {{ id: string, agent?: string, method: string, url: string, rule: string, letter: string, bodyPreview?: string, expiresAt?: string|null, floor?: { kind: string, entry: string }, effect?: import('./effect.js').Effect, keyLast4?: string, modelKey?: 'none'|'other' }} AskRecord */
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The `To:` / `Amount:` / `Currency:` lines of a floor request, or one `Effect:` line saying why none was read.
|
|
36
|
+
* Up to LIST_MAX fields are all listed; more than that lists none (too many to tell the real one).
|
|
37
|
+
*
|
|
38
|
+
* @param {AskRecord['effect']} effect the ask's effect, absent when the request had no body
|
|
39
|
+
* @param {boolean} color paint with ANSI escapes
|
|
40
|
+
* @returns {string[]} zero or more lines
|
|
41
|
+
*/
|
|
42
|
+
export function effectLines(effect, color) {
|
|
43
|
+
if (!effect) return [];
|
|
44
|
+
const { bold } = ANSI;
|
|
45
|
+
if (effect.notRead !== null) return [` ${paint(color, bold, 'Effect:')} not read (${safe(effect.notRead)})`];
|
|
46
|
+
/** @type {[string, { path: string, value: string }[]][]} */
|
|
47
|
+
const rows = [['To:', effect.recipient], ['Amount:', effect.amount], ['Currency:', effect.currency]];
|
|
48
|
+
if (rows.every(([, f]) => !f.length)) return [` ${paint(color, bold, 'Effect:')} body read, no recipient, amount or currency field recognised`];
|
|
49
|
+
return rows.filter(([, f]) => f.length).map(([label, f]) => {
|
|
50
|
+
const shown = f.length > LIST_MAX
|
|
51
|
+
? `more than ${LIST_MAX} fields (not listed: too many to tell the real one)`
|
|
52
|
+
: f.map((x) => `${safe(x.path)}=${safe(x.value)}`).join('; ');
|
|
53
|
+
return ` ${paint(color, bold, label)} ${shown}`;
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The ` floor=<kind> entry=<entry>` tail of a one-line ask (`sbx pending`, the non-terminal `ask` line); empty without a floor hit.
|
|
59
|
+
*
|
|
60
|
+
* @param {AskRecord} ask the parked request
|
|
61
|
+
* @returns {string} the tail, or ''
|
|
62
|
+
*/
|
|
63
|
+
export function floorTail(ask) {
|
|
64
|
+
return ask.floor ? ` floor=${safe(ask.floor.kind)} entry=${safe(ask.floor.entry)}` : '';
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The ` key=…<last 4>` tail of a one-line ask (`sbx pending`, the non-terminal `ask` line); ` key=none` or ` key=other` when there is no last 4 to show; empty unless the ask is a model call with another key.
|
|
69
|
+
*
|
|
70
|
+
* @param {AskRecord} ask the parked request
|
|
71
|
+
* @returns {string} the tail, or ''
|
|
72
|
+
*/
|
|
73
|
+
export function keyTail(ask) {
|
|
74
|
+
if (ask.keyLast4) return ` key=…${safe(ask.keyLast4)}`;
|
|
75
|
+
return ask.modelKey ? ` key=${ask.modelKey}` : '';
|
|
76
|
+
}
|
|
31
77
|
|
|
32
78
|
/**
|
|
33
79
|
* Plain-language lines for one ask record. Every agent-controlled byte goes
|
|
@@ -48,8 +94,13 @@ export function questionLines(ask, now = Date.now(), color = false) {
|
|
|
48
94
|
: method === 'DELETE' ? 'DELETE data on'
|
|
49
95
|
: `make a ${method} request to`;
|
|
50
96
|
const rule = safe(ask.rule);
|
|
51
|
-
const why = rule === 'flags.
|
|
97
|
+
const why = rule === 'flags.floor' && ask.floor
|
|
98
|
+
? `${ask.floor.kind === 'send' ? 'a send' : 'a payment'} to ${isEndpoint(ask.floor.entry) ? 'an endpoint' : 'a domain'} you listed (${safe(ask.floor.entry)})`
|
|
99
|
+
: rule === 'flags.cardLike' ? 'it contains what looks like a card number'
|
|
52
100
|
: rule === 'flags.paymentPath' ? 'the address looks like a payment'
|
|
101
|
+
: ask.keyLast4 ? `a model call with a key that is not this run's (…${safe(ask.keyLast4)})`
|
|
102
|
+
: ask.modelKey === 'none' ? 'a model call with no key'
|
|
103
|
+
: ask.modelKey ? "a model call with a key that is not this run's"
|
|
53
104
|
: ask.letter === 'w' ? 'a change (reversible: the vendor says it can be undone)'
|
|
54
105
|
: ask.letter === 'x' ? "a change barebox can't undo"
|
|
55
106
|
: rule;
|
|
@@ -63,6 +114,7 @@ export function questionLines(ask, now = Date.now(), color = false) {
|
|
|
63
114
|
` ${paint(color, bold, 'Why:')} ${why}`,
|
|
64
115
|
` ${paint(color, bold, 'URL:')} ${paint(color, cyan, `${method} ${safe(ask.url)}`)}`,
|
|
65
116
|
];
|
|
117
|
+
lines.push(...effectLines(ask.effect, color));
|
|
66
118
|
const body = safe(ask.bodyPreview).slice(0, BODY_CHARS);
|
|
67
119
|
if (body) lines.push(` ${paint(color, bold, 'Data:')} ${paint(color, dim, body)}`);
|
|
68
120
|
const tail = `(hold ${safe(ask.id)})${left === null || Number.isNaN(left) ? '' : ` — no answer in ${left} s means No`}`;
|