barebox 0.13.0 → 0.15.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 +22 -0
- package/README.md +58 -127
- package/barebox.context.md +32 -4
- package/package.json +1 -1
- package/primitives.json +1 -1
- package/src/cli.js +20 -10
- package/src/config.js +21 -2
- package/src/holds.js +63 -20
- package/src/launcher.js +1 -1
- package/src/lists.js +1 -1
- package/src/policy.js +5 -1
- package/src/prompt.js +39 -2
- package/src/proxy.js +330 -44
- package/src/run.js +10 -4
- package/types/config.d.ts +12 -2
- package/types/holds.d.ts +24 -4
- package/types/lists.d.ts +1 -0
- package/types/policy.d.ts +2 -0
- package/types/prompt.d.ts +19 -1
- package/types/proxy.d.ts +17 -3
- package/types/run.d.ts +21 -2
package/src/proxy.js
CHANGED
|
@@ -18,19 +18,34 @@ import https from 'node:https';
|
|
|
18
18
|
import fs from 'node:fs';
|
|
19
19
|
import path from 'node:path';
|
|
20
20
|
import { ensureCA, certFor, HOST_RE } from './certs.js';
|
|
21
|
-
import { createCardScanner } from './cardscan.js';
|
|
21
|
+
import { createCardScanner, maskCards } from './cardscan.js';
|
|
22
22
|
import { ASK_BODY_LIMIT, DEFAULT_HOLD_MAX_BODY, bodyPreview, createHolds } from './holds.js';
|
|
23
23
|
import { viewBody } from './bodyview.js';
|
|
24
24
|
import { claimRuntime, ensurePrivateDir, runtimePaths } from './runtime.js';
|
|
25
|
-
import { paymentPath, toolFor, buildTools, modelTools, modelList, emptyMatcher } from './policy.js';
|
|
25
|
+
import { paymentPath, toolFor, buildTools, modelTools, modelList, emptyMatcher, MODEL_HOSTS } from './policy.js';
|
|
26
26
|
import { checkUpstream } from './wall.js';
|
|
27
|
-
import { floorList } from './lists.js';
|
|
27
|
+
import { floorList, stripDot } from './lists.js';
|
|
28
28
|
import { findEffect } from './effect.js';
|
|
29
29
|
import { findPlaceholders, urlPlaceholders, applySecrets } from './secrets.js';
|
|
30
|
-
import { Gate } from 'bareguard';
|
|
30
|
+
import { Gate, hostMatcher } from 'bareguard';
|
|
31
31
|
|
|
32
32
|
const AGENT = Symbol('agent');
|
|
33
33
|
const SECURE = Symbol('secure');
|
|
34
|
+
|
|
35
|
+
/** The URL a proxied request targets (absolute-form, else built from Host), or null when it has none. @param {import('node:http').IncomingMessage} creq */
|
|
36
|
+
function targetUrl(creq) {
|
|
37
|
+
const target = creq.url || '';
|
|
38
|
+
try {
|
|
39
|
+
if (/^https?:\/\//i.test(target)) return new URL(target);
|
|
40
|
+
const host = creq.headers.host;
|
|
41
|
+
if (!host) return null;
|
|
42
|
+
return new URL(`${/** @type {any} */ (creq.socket)[SECURE] === true ? 'https' : 'http'}://${host}${target}`);
|
|
43
|
+
} catch { return null; }
|
|
44
|
+
}
|
|
45
|
+
/** The url as the audit may show it: userinfo whole to `***`, then card numbers masked (a string with no scheme gets the card mask only). @param {string} url */
|
|
46
|
+
function maskUrl(url) {
|
|
47
|
+
return maskCards(url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@]*@/i, '$1***@'));
|
|
48
|
+
}
|
|
34
49
|
const IP_RE = /^\d+\.\d+\.\d+\.\d+$/;
|
|
35
50
|
// Hop-by-hop headers must not be forwarded: node's HTTP stack re-frames.
|
|
36
51
|
const HOP_REQ = new Set(['proxy-connection', 'proxy-authorization']);
|
|
@@ -43,6 +58,8 @@ const MAX_AGENTS = 40;
|
|
|
43
58
|
// Agents that browse many hosts must not grow the proxy without limit: one TLS context per host, at most this many.
|
|
44
59
|
const MAX_MITM_CONTEXTS = 256;
|
|
45
60
|
const EMPTY = Buffer.alloc(0);
|
|
61
|
+
/** The request headers that carry a model API key (M12). */
|
|
62
|
+
const KEY_HEADERS = ['x-api-key', 'authorization'];
|
|
46
63
|
const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
|
|
47
64
|
'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade']);
|
|
48
65
|
|
|
@@ -58,6 +75,7 @@ const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
|
|
|
58
75
|
* @property {{ matcher: { match: (method: string, url: string) => { key: string, source: string } }, tools: Record<string, any> }} [labels] the loaded label files (see `loadLabels`); omitted means no labels, only the built-in model endpoints
|
|
59
76
|
* @property {string[]} [allowLocal] exact `host:port` pairs (the `localLlm` setting) that may pass the wall's private/loopback check; any other local destination is still denied
|
|
60
77
|
* @property {{ pay?: string[], send?: string[] }} [floor] the config `floor` key (M11): a write to a listed host or `*.domain`, or a request matching a listed `"METHOD host/path"`, asks in every mode (the gate flag `floor`); the question shows the recipient, amount and currency found in the body. Omitted means no floor lists.
|
|
78
|
+
* @property {{ allow?: string[], deny?: string[], unknown?: 'ask' | 'deny' | 'allow' }} [hosts] M14: `deny` hosts (exact or `*.domain`) are refused before DNS in every mode; `allow` hosts never get the first-contact ask; any other host follows `unknown`: `'ask'` asks once per host (allow for this run, or deny), `'deny'` refuses it at once, `'allow'` (the default here) lets it through. Model endpoint hosts, each secret's hosts and the `allowLocal` hosts are never asked. Needs `gateFor` for `'ask'`; without it `'ask'` refuses.
|
|
61
79
|
* @property {HoldOptions} [hold] hold queue config (deadline, caps, ask seam)
|
|
62
80
|
* @property {number} [upstreamTimeoutMs] give up on an upstream response after this (default 120000)
|
|
63
81
|
* @property {object} [unsafeTestOnly] TEST-ONLY escape hatch: everything under
|
|
@@ -69,7 +87,7 @@ const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
|
|
|
69
87
|
* DNS stub: replaces the wall's resolver so rebinding is testable. Production omits it.
|
|
70
88
|
* @property {import('./secrets.js').Secret[]} [secrets] the loaded secrets (`loadSecrets`): a request carrying a secret's placeholder in a header gets the real value there only after the gate allowed it and only for a bound host; for any other host it is refused `403 denied: secret.host`. The value never reaches the audit file, an ask or an error body.
|
|
71
89
|
* @property {number} [clientIdleMs] kill a client tunnel idle this long; never fires mid-request (default 60000)
|
|
72
|
-
* @property {(entry: Record<string, unknown>) => Record<string, unknown>} [redact] log redaction hook, applied after built-in secret scrubbing; its result becomes the `meta` of an `annotate` line (default: identity)
|
|
90
|
+
* @property {(entry: Record<string, unknown>) => Record<string, unknown>} [redact] log redaction hook, applied after built-in secret scrubbing; its result becomes the `meta` of an `annotate` line, and the `url` it sees already has userinfo and card numbers masked (default: identity)
|
|
73
91
|
*/
|
|
74
92
|
|
|
75
93
|
/**
|
|
@@ -114,7 +132,7 @@ const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
|
|
|
114
132
|
*/
|
|
115
133
|
|
|
116
134
|
/**
|
|
117
|
-
* Start the front-door proxy. Every request is audited with its method and URL, and a request with a body also with its byte count and SHA-256 (never headers or body text); bytes go upstream untouched. Requests the hold rule
|
|
135
|
+
* Start the front-door proxy. Every request is audited with its method and URL, and a request with a body also with its byte count and SHA-256 (never headers or body text); barebox's own audit lines mask userinfo and card numbers in the URL, the gate's decision lines keep it as sent; bytes go upstream untouched. Requests the hold rule
|
|
118
136
|
* flags park for a human decision instead of forwarding.
|
|
119
137
|
*
|
|
120
138
|
* @param {ProxyOptions} opts
|
|
@@ -132,7 +150,7 @@ export function createProxy(opts) {
|
|
|
132
150
|
upstreamCa = null, hold = null, gateFor = null, allowLocal = [], floor = null, labels = null,
|
|
133
151
|
upstreamTimeoutMs = 120000, clientIdleMs = 60000,
|
|
134
152
|
unsafeTestOnly = null, secrets = [],
|
|
135
|
-
redact = (e) => e } = opts ?? {};
|
|
153
|
+
redact = (e) => e, hosts = {} } = opts ?? {};
|
|
136
154
|
const { allowLoopback = false, resolveUpstream = null } = unsafeTestOnly ?? {};
|
|
137
155
|
const gate = {
|
|
138
156
|
allowLoopback, resolveUpstream: resolveUpstream ?? undefined,
|
|
@@ -144,8 +162,17 @@ export function createProxy(opts) {
|
|
|
144
162
|
const matcher = labels?.matcher ?? emptyMatcher;
|
|
145
163
|
const tools = buildTools(labels?.tools, [...allowLocal]);
|
|
146
164
|
const models = modelTools(labels?.tools, [...allowLocal]);
|
|
165
|
+
// The built-in endpoints only: a `localLlm` server is free without a key check (M12).
|
|
166
|
+
const builtinModels = modelTools(labels?.tools, []);
|
|
147
167
|
const modelEndpoints = modelList([...allowLocal]);
|
|
148
168
|
const floors = floorList(floor ?? {});
|
|
169
|
+
const hostDeny = hosts.deny?.length ? hostMatcher(hosts.deny) : null;
|
|
170
|
+
const hostAllow = hosts.allow?.length ? hostMatcher(hosts.allow) : null;
|
|
171
|
+
const hostUnknown = hosts.unknown ?? 'allow';
|
|
172
|
+
if (!['ask', 'deny', 'allow'].includes(hostUnknown)) throw new Error(`createProxy: hosts.unknown must be ask|deny|allow, got ${JSON.stringify(hostUnknown)}`);
|
|
173
|
+
// Never a first-contact ask (M14): the model endpoints, each secret's hosts and the local model servers.
|
|
174
|
+
const hostExempt = new Set([...MODEL_HOSTS, ...secrets.flatMap((x) => x.hosts.map((h) => h.toLowerCase())),
|
|
175
|
+
...allowLocal.map((e) => String(e).toLowerCase().replace(/:\d+$/, ''))]);
|
|
149
176
|
if (!logFile) throw new Error('createProxy: logFile is required');
|
|
150
177
|
if (typeof runtime !== 'string' || !runtime) throw new Error('createProxy: runtime is required');
|
|
151
178
|
// One live proxy per runtime, enforced here: claimed before the hold
|
|
@@ -222,8 +249,10 @@ export function createProxy(opts) {
|
|
|
222
249
|
meta['reason'] = cut(meta['reason'], 200);
|
|
223
250
|
return meta;
|
|
224
251
|
};
|
|
225
|
-
/** @param {Record<string, unknown>}
|
|
226
|
-
async function writeLog(
|
|
252
|
+
/** @param {Record<string, unknown>} o0 */
|
|
253
|
+
async function writeLog(o0) {
|
|
254
|
+
// One writer of the masked url: `where` and `meta` both read `o`.
|
|
255
|
+
const o = typeof o0['url'] === 'string' ? { ...o0, url: maskUrl(o0['url']) } : o0;
|
|
227
256
|
const agent = typeof o['agent'] === 'string' ? o['agent'] : null;
|
|
228
257
|
// Never build a gate from here: a built one, else the sbx gate.
|
|
229
258
|
const entry = agent ? gates.get(agent) : undefined;
|
|
@@ -273,7 +302,9 @@ export function createProxy(opts) {
|
|
|
273
302
|
// The one writer of a proxied HTTP error: logs it, answers it.
|
|
274
303
|
function denyRes(cres, code, note) {
|
|
275
304
|
const sock = cres.socket;
|
|
276
|
-
|
|
305
|
+
const req = cres.req;
|
|
306
|
+
const url = req ? (targetUrl(req)?.toString() ?? req.url) : undefined;
|
|
307
|
+
log({ ev: 'deny', agent: agentOf(sock), code, note, ...(req?.method ? { method: req.method } : {}), ...(url ? { url } : {}) });
|
|
277
308
|
try {
|
|
278
309
|
if (!cres.headersSent && !sock.destroyed) {
|
|
279
310
|
cres.writeHead(code, { 'content-type': 'text/plain', connection: 'close' });
|
|
@@ -282,9 +313,10 @@ export function createProxy(opts) {
|
|
|
282
313
|
} catch {}
|
|
283
314
|
}
|
|
284
315
|
|
|
285
|
-
//
|
|
286
|
-
|
|
287
|
-
|
|
316
|
+
// Raw sockets: pre-HTTP (CONNECT line, oversized head, walled CONNECT, cert failure) and the
|
|
317
|
+
// upgrade / inner CONNECT refusals below. `url` is the target, for the proxy log only.
|
|
318
|
+
function denyRaw(sock, code, note, url) {
|
|
319
|
+
log({ ev: 'deny', agent: agentOf(sock), code, note, ...(url ? { url } : {}) });
|
|
288
320
|
if (sock.destroyed) return;
|
|
289
321
|
try { sock.end(`HTTP/1.1 ${code} ${note}\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n${note}\n`); }
|
|
290
322
|
catch {}
|
|
@@ -439,7 +471,7 @@ export function createProxy(opts) {
|
|
|
439
471
|
// A parked request's pending ask ends here: handleRequest, awaiting
|
|
440
472
|
// its gate, then forwards or refuses.
|
|
441
473
|
onApprove: (h) => h.finish({ decision: 'allow' }),
|
|
442
|
-
onDeny: (h, reason) => h.finish({ decision: 'deny', reason }),
|
|
474
|
+
onDeny: (h, reason, answered, timedOut) => h.finish({ decision: 'deny', reason, answered, timedOut }),
|
|
443
475
|
}) : null;
|
|
444
476
|
} catch (e) {
|
|
445
477
|
releaseClaim();
|
|
@@ -479,6 +511,129 @@ export function createProxy(opts) {
|
|
|
479
511
|
return e.p;
|
|
480
512
|
}
|
|
481
513
|
|
|
514
|
+
/**
|
|
515
|
+
* M12: SHA-256 of the model keys a human allowed in this run. `rememberKey` is the one writer; it
|
|
516
|
+
* lives with the proxy, so it is gone with it. A key's bytes are never kept, logged or asked.
|
|
517
|
+
*
|
|
518
|
+
* @type {Set<string>}
|
|
519
|
+
*/
|
|
520
|
+
const allowedKeys = new Set();
|
|
521
|
+
/** @param {string} hash */
|
|
522
|
+
const rememberKey = (hash) => { allowedKeys.add(hash); };
|
|
523
|
+
/**
|
|
524
|
+
* M12: one open ask per unknown key. Parallel calls with that key wait on it instead of asking again.
|
|
525
|
+
*
|
|
526
|
+
* @type {Map<string, Promise<'allow'|'deny'|'none'>>}
|
|
527
|
+
*/
|
|
528
|
+
const keyAsks = new Map();
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* M14: what a person decided about each host in this run, shared by every agent of the proxy.
|
|
532
|
+
* `rememberHost` is the one writer; the Map is gone with the proxy.
|
|
533
|
+
*
|
|
534
|
+
* @type {Map<string, 'allow'|'deny'>}
|
|
535
|
+
*/
|
|
536
|
+
const runHosts = new Map();
|
|
537
|
+
/** @param {string} host @param {'allow'|'deny'} d */
|
|
538
|
+
const rememberHost = (host, d) => { runHosts.set(host, d); };
|
|
539
|
+
/** Hosts refused by `unknown: 'deny'` this run. @type {Set<string>} */
|
|
540
|
+
const refusedHosts = new Set();
|
|
541
|
+
/**
|
|
542
|
+
* M14: one open ask per unknown host; parallel requests wait on it instead of asking again. It settles with
|
|
543
|
+
* the leader's outcome: `'timeout'` (the hold timeout) denies the waiters at once, as M12's `settleKey`;
|
|
544
|
+
* any other value sends a waiter back to `hostDecision`.
|
|
545
|
+
*
|
|
546
|
+
* @type {Map<string, Promise<'allow'|'deny'|'timeout'|'none'>>}
|
|
547
|
+
*/
|
|
548
|
+
const hostAsks = new Map();
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* M14: the one host decision, on the name alone (before any DNS). In order: the deny list, a
|
|
552
|
+
* person's earlier deny, the allow list / a person's earlier allow / an exempt host, then `unknown`.
|
|
553
|
+
* A host the matchers cannot check is refused (fail closed).
|
|
554
|
+
*
|
|
555
|
+
* @param {string} rawHost a request or CONNECT host name
|
|
556
|
+
* @returns {{ d: 'allow'|'deny'|'unknown', host: string, reason?: string, entry?: string }}
|
|
557
|
+
*/
|
|
558
|
+
function hostDecision(rawHost) {
|
|
559
|
+
const host = stripDot(rawHost.toLowerCase());
|
|
560
|
+
try {
|
|
561
|
+
const entry = hostDeny?.match(host);
|
|
562
|
+
if (entry) return { d: 'deny', host, reason: 'denied: host', entry };
|
|
563
|
+
if (runHosts.get(host) === 'deny') return { d: 'deny', host, reason: 'denied: host' };
|
|
564
|
+
if (runHosts.get(host) === 'allow' || hostExempt.has(host) || hostAllow?.match(host)) return { d: 'allow', host };
|
|
565
|
+
} catch {
|
|
566
|
+
return { d: 'deny', host, reason: 'denied: host not checkable' };
|
|
567
|
+
}
|
|
568
|
+
if (hostUnknown === 'allow') return { d: 'allow', host };
|
|
569
|
+
if (hostUnknown === 'ask' && gateFor) return { d: 'unknown', host };
|
|
570
|
+
return { d: 'deny', host, reason: 'denied: host not in hosts.allow' };
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/** M14: the audit line and run report for a host refused with no gate call. @param {string} agent @param {{ host: string, reason?: string, entry?: string }} hd */
|
|
574
|
+
function hostRefusal(agent, hd) {
|
|
575
|
+
if (hd.reason === 'denied: host not in hosts.allow') refusedHosts.add(hd.host);
|
|
576
|
+
log({ ev: 'host', agent, host: hd.host, decision: 'deny', reason: hd.reason, ...(hd.entry ? { entry: hd.entry } : {}) });
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* M14: the first request to a host nobody decided yet asks the person (the `newHost` flag on a
|
|
581
|
+
* `net.host` action, run on this agent's own gate). The body stays unread. A person's answer is
|
|
582
|
+
* remembered for the run; a hold timeout, a cancel, a close or a failure is not.
|
|
583
|
+
*
|
|
584
|
+
* @param {import('node:http').ServerResponse} cres @param {string} agent @param {string} method @param {string} urlStr @param {string} host
|
|
585
|
+
* @param {import('node:http').IncomingMessage} creq
|
|
586
|
+
* @returns {Promise<{ outcome: string, reason?: string|null, rule?: string, asked: boolean, status: number|null, timedOut: boolean }>}
|
|
587
|
+
*/
|
|
588
|
+
async function askHost(creq, cres, agent, method, urlStr, host) {
|
|
589
|
+
const rid = `r${++ridN}`;
|
|
590
|
+
/** @type {RequestCtx} */
|
|
591
|
+
const ctx = { agent, method, url: urlStr, headers: { ...creq.headers }, creq, cres, tee: makeTee(),
|
|
592
|
+
hasBody: false, chunks: [], over: false, freeWork: () => {}, asked: false, status: null, heldId: null,
|
|
593
|
+
endAsk: null, decodedHead: null, effect: null, keyLast4: '', modelKey: '', askRule: null, answered: false, timedOut: false };
|
|
594
|
+
inflightCtx.set(rid, ctx);
|
|
595
|
+
try {
|
|
596
|
+
const g = await gateOf(agent);
|
|
597
|
+
const d = await decideAction(g, { type: 'net', tool: 'net.host', url: urlStr, method, agent, rid, newHost: true });
|
|
598
|
+
if (d.outcome === 'allow') rememberHost(host, 'allow');
|
|
599
|
+
else if (ctx.asked && ctx.answered && !ctx.timedOut) rememberHost(host, 'deny');
|
|
600
|
+
return { ...d, asked: ctx.asked, status: ctx.status, timedOut: ctx.timedOut };
|
|
601
|
+
} finally {
|
|
602
|
+
inflightCtx.delete(rid);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* The model key of a header: `x-api-key`, or `Authorization` without a leading `Bearer `.
|
|
608
|
+
* @param {Record<string, string | string[] | undefined>} headers @param {string} name @returns {string}
|
|
609
|
+
*/
|
|
610
|
+
function keyIn(headers, name) {
|
|
611
|
+
const v = headers[name];
|
|
612
|
+
const raw = String((Array.isArray(v) ? v[0] : v) ?? '');
|
|
613
|
+
return (name === 'authorization' ? raw.replace(/^Bearer\s+/i, '') : raw).trim();
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/**
|
|
617
|
+
* M12: is this built-in model call carrying a key that is not this run's? A key header is the
|
|
618
|
+
* run's when it holds a bound placeholder or its hash was allowed; every other key is "other".
|
|
619
|
+
* With no key header at all the call is "other" too, with nothing to remember.
|
|
620
|
+
*
|
|
621
|
+
* @param {Record<string, string | string[] | undefined>} headers the request headers
|
|
622
|
+
* @param {{ header: string, bound: boolean }[]} found the request's placeholders
|
|
623
|
+
* @returns {null | { hash: string | null, last4: string }} null: the run's key; else the key's hash and last 4 characters (null and '' for no key)
|
|
624
|
+
*/
|
|
625
|
+
function otherKey(headers, found) {
|
|
626
|
+
const present = KEY_HEADERS.filter((h) => keyIn(headers, h));
|
|
627
|
+
if (!present.length) return { hash: null, last4: '' };
|
|
628
|
+
for (const h of present) {
|
|
629
|
+
if (found.some((f) => f.bound && f.header === h)) continue;
|
|
630
|
+
const key = keyIn(headers, h);
|
|
631
|
+
const hash = crypto.createHash('sha256').update(key).digest('hex');
|
|
632
|
+
if (!allowedKeys.has(hash)) return { hash, last4: key.length >= 8 ? key.slice(-4) : '' };
|
|
633
|
+
}
|
|
634
|
+
return null;
|
|
635
|
+
}
|
|
636
|
+
|
|
482
637
|
/**
|
|
483
638
|
* Requests inside `gate.check()`, by `rid`: how the human channel finds
|
|
484
639
|
* the request an ask is about. handleRequest sets and deletes each entry
|
|
@@ -508,6 +663,11 @@ export function createProxy(opts) {
|
|
|
508
663
|
* @property {string|null} heldId id of the held body file, once spooled
|
|
509
664
|
* @property {((reason: string) => void)|null} endAsk end a not-yet-parked ask as a denial
|
|
510
665
|
* @property {Buffer|null} decodedHead copy of the first 4 KB of a gzip/deflate body, decoded (the ask preview)
|
|
666
|
+
* @property {'none'|'other'|''} modelKey 'none' (no key header) or 'other' for a model call whose key is not this run's; '' otherwise
|
|
667
|
+
* @property {string} keyLast4 last 4 characters of a model key that is not this run's ('' when none): shown in the ask, never the key
|
|
668
|
+
* @property {string|null} askRule the rule the human channel was asked about (null: not asked)
|
|
669
|
+
* @property {boolean} answered a person's answer or the hold timeout ended the ask (set by the hold's `finish`); false for a cancel, a close or a failure
|
|
670
|
+
* @property {boolean} timedOut the hold timeout ended the ask (so `answered && !timedOut` is a person's answer)
|
|
511
671
|
* @property {import('./effect.js').Effect|null} effect the recipient/amount/currency fields found in the body of a floor request (ask file only, never the audit); null when there is none
|
|
512
672
|
*/
|
|
513
673
|
|
|
@@ -522,6 +682,7 @@ export function createProxy(opts) {
|
|
|
522
682
|
const ctx = inflightCtx.get(String(event?.action?.rid));
|
|
523
683
|
if (!ctx) return { decision: 'deny', reason: 'request gone' };
|
|
524
684
|
ctx.asked = true;
|
|
685
|
+
ctx.askRule = event.rule ?? null;
|
|
525
686
|
return holdRequest(ctx, event);
|
|
526
687
|
}
|
|
527
688
|
|
|
@@ -546,18 +707,21 @@ export function createProxy(opts) {
|
|
|
546
707
|
let dead = false;
|
|
547
708
|
/** @type {import('node:fs').WriteStream|null} */
|
|
548
709
|
let ws = null;
|
|
549
|
-
/** @param {{ decision: 'allow' | 'deny', reason?: string }} d */
|
|
710
|
+
/** @param {{ decision: 'allow' | 'deny', reason?: string, answered?: boolean, timedOut?: boolean }} d */
|
|
550
711
|
const finish = (d) => {
|
|
551
712
|
if (settled) return;
|
|
552
713
|
settled = true;
|
|
553
714
|
ctx.endAsk = null;
|
|
554
|
-
|
|
715
|
+
const { answered, timedOut, ...rest } = d; // the one place `answered` and `timedOut` are set: present only when true
|
|
716
|
+
ctx.answered = answered === true;
|
|
717
|
+
ctx.timedOut = timedOut === true;
|
|
718
|
+
resolve(ctx.answered ? d : rest);
|
|
555
719
|
};
|
|
556
|
-
/** @param {string} reason @param {number} [status] */
|
|
557
|
-
const refuse = (reason, status) => {
|
|
720
|
+
/** @param {string} reason @param {number} [status] @param {boolean} [answered] the hold timeout ended it @param {boolean} [timedOut] */
|
|
721
|
+
const refuse = (reason, status, answered, timedOut) => {
|
|
558
722
|
if (settled) return; // a late failure must not rewrite the settled deny's status
|
|
559
723
|
if (status) ctx.status = status;
|
|
560
|
-
finish({ decision: 'deny', reason });
|
|
724
|
+
finish({ decision: 'deny', reason, answered, timedOut });
|
|
561
725
|
};
|
|
562
726
|
const abort = () => {
|
|
563
727
|
if (dead) return;
|
|
@@ -576,7 +740,7 @@ export function createProxy(opts) {
|
|
|
576
740
|
if (!sock || sock.destroyed) { refuse('client gone'); return; }
|
|
577
741
|
const slot = queue.reserve(agent, {
|
|
578
742
|
onReady: () => stream(),
|
|
579
|
-
onExpire: (why) => { abort(); refuse(why); },
|
|
743
|
+
onExpire: (why, answered, timedOut) => { abort(); refuse(why, undefined, answered, timedOut); },
|
|
580
744
|
});
|
|
581
745
|
if (slot.state === 'full') { ctx.freeWork(); refuse('hold queue full', 429); return; }
|
|
582
746
|
ctx.endAsk = (why) => fail(why);
|
|
@@ -618,6 +782,8 @@ export function createProxy(opts) {
|
|
|
618
782
|
preview: bodyPreview(ctx.decodedHead ?? ctx.tee.head), bodyBytes: ctx.tee.bytes,
|
|
619
783
|
effect: ctx.effect ?? undefined,
|
|
620
784
|
...(event.action?.floor ? { floor: { kind: String(event.action.floor), entry: String(event.action.floorEntry) } } : {}),
|
|
785
|
+
...(ctx.keyLast4 ? { keyLast4: ctx.keyLast4 } : {}),
|
|
786
|
+
...(ctx.modelKey ? { modelKey: ctx.modelKey } : {}),
|
|
621
787
|
sock, note: event.rule ?? 'ask', letter: event.rwxLetter, finish,
|
|
622
788
|
slot, arrivedAt: slot.arrivedAt }) !== null;
|
|
623
789
|
};
|
|
@@ -659,26 +825,11 @@ export function createProxy(opts) {
|
|
|
659
825
|
async function handleRequest(creq, cres) {
|
|
660
826
|
const sock = creq.socket;
|
|
661
827
|
const agent = agentOf(sock);
|
|
662
|
-
const
|
|
663
|
-
|
|
664
|
-
let url;
|
|
665
|
-
try {
|
|
666
|
-
if (/^https?:\/\//i.test(target)) url = new URL(target);
|
|
667
|
-
else {
|
|
668
|
-
const host = creq.headers.host;
|
|
669
|
-
if (!host) throw new Error('no host');
|
|
670
|
-
url = new URL(`${secure ? 'https' : 'http'}://${host}${target}`);
|
|
671
|
-
}
|
|
672
|
-
} catch { denyRes(cres, 400, 'bad request target'); return; }
|
|
828
|
+
const url = targetUrl(creq);
|
|
829
|
+
if (!url) { denyRes(cres, 400, 'bad request target'); return; }
|
|
673
830
|
const method = creq.method;
|
|
674
831
|
if (!method) { denyRes(cres, 400, 'bad request method'); return; }
|
|
675
832
|
const urlStr = url.toString();
|
|
676
|
-
const verdict = await checkUpstream(url.hostname, gate, portOf(url));
|
|
677
|
-
if (!verdict.ok) {
|
|
678
|
-
try { creq.resume(); } catch {}
|
|
679
|
-
denyRes(cres, 403, verdict.reason);
|
|
680
|
-
return;
|
|
681
|
-
}
|
|
682
833
|
// The request's one id: the audit lines of its secret swap, its body and
|
|
683
834
|
// its gate decision all carry it.
|
|
684
835
|
const rid = `r${++ridN}`;
|
|
@@ -711,6 +862,69 @@ export function createProxy(opts) {
|
|
|
711
862
|
denyRes(cres, 403, 'denied: secret.url');
|
|
712
863
|
return;
|
|
713
864
|
}
|
|
865
|
+
// The secret refusals above need only the host name. Pause before the host decision and the
|
|
866
|
+
// wall: neither may lose body bytes while they wait.
|
|
867
|
+
creq.pause();
|
|
868
|
+
// M14: the host decision comes before any DNS (`checkUpstream`).
|
|
869
|
+
let hd = hostDecision(url.hostname);
|
|
870
|
+
while (hd.d === 'unknown') {
|
|
871
|
+
const open = hostAsks.get(hd.host);
|
|
872
|
+
if (open) {
|
|
873
|
+
// Wait for the open ask on this host; hold a place among the agent's waiters while we do.
|
|
874
|
+
const release = holds ? holds.wait(agent) : () => {};
|
|
875
|
+
if (!release) {
|
|
876
|
+
discard(creq);
|
|
877
|
+
denyRes(cres, 429, 'denied: hold queue full');
|
|
878
|
+
return;
|
|
879
|
+
}
|
|
880
|
+
/** @type {() => void} */
|
|
881
|
+
let onGone = () => {};
|
|
882
|
+
const gone = new Promise((r) => { onGone = () => r('gone'); cres.once('close', onGone); });
|
|
883
|
+
const r = await Promise.race([open, gone]);
|
|
884
|
+
cres.off('close', onGone);
|
|
885
|
+
release();
|
|
886
|
+
if (r === 'gone') { discard(creq); return; }
|
|
887
|
+
if (r === 'timeout') {
|
|
888
|
+
// The hold timeout denies every waiter at once; nothing is remembered, so the next new request asks again.
|
|
889
|
+
discard(creq);
|
|
890
|
+
denyRes(cres, 403, 'denied: hold timeout');
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
hd = hostDecision(url.hostname);
|
|
894
|
+
continue;
|
|
895
|
+
}
|
|
896
|
+
/** @type {(r: 'allow'|'deny'|'timeout'|'none') => void} */
|
|
897
|
+
let endAsk = () => {};
|
|
898
|
+
hostAsks.set(hd.host, new Promise((r) => { endAsk = r; }));
|
|
899
|
+
let d;
|
|
900
|
+
let settled = /** @type {'allow'|'deny'|'timeout'|'none'} */ ('none');
|
|
901
|
+
try {
|
|
902
|
+
d = await askHost(creq, cres, agent, method, urlStr, hd.host);
|
|
903
|
+
// A person's answer is remembered, so the waiters re-decide; the hold timeout denies them. A cancel or a close settles 'deny' without remembering, and a failure leaves 'none'; either way the waiters re-decide, find the host still unknown, and the next one asks.
|
|
904
|
+
settled = d.timedOut ? 'timeout' : d.outcome === 'allow' ? 'allow' : 'deny';
|
|
905
|
+
} finally {
|
|
906
|
+
hostAsks.delete(hd.host);
|
|
907
|
+
endAsk(settled);
|
|
908
|
+
}
|
|
909
|
+
if (d.outcome !== 'allow') {
|
|
910
|
+
discard(creq);
|
|
911
|
+
denyRes(cres, d.status ?? 403, d.asked ? `denied: ${d.reason ?? 'denied'}` : `denied: ${d.rule ?? 'gate'}${d.reason ? `: ${d.reason}` : ''}`);
|
|
912
|
+
return;
|
|
913
|
+
}
|
|
914
|
+
hd = hostDecision(url.hostname);
|
|
915
|
+
}
|
|
916
|
+
if (hd.d === 'deny') {
|
|
917
|
+
hostRefusal(agent, hd);
|
|
918
|
+
discard(creq);
|
|
919
|
+
denyRes(cres, 403, /** @type {string} */ (hd.reason));
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
const verdict = await checkUpstream(url.hostname, gate, portOf(url));
|
|
923
|
+
if (!verdict.ok) {
|
|
924
|
+
try { creq.resume(); } catch {}
|
|
925
|
+
denyRes(cres, 403, verdict.reason);
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
714
928
|
/** The headers to forward: the real values in, one audit line per swap. @param {Record<string, string | string[] | undefined>} headers */
|
|
715
929
|
const withSecrets = (headers) => {
|
|
716
930
|
if (!found.length) return headers;
|
|
@@ -724,7 +938,6 @@ export function createProxy(opts) {
|
|
|
724
938
|
// flowing mode and starve whoever reads it next. The tee sees every body
|
|
725
939
|
// byte once, whatever path reads it, and feeds the ask (a masked
|
|
726
940
|
// 4 KB preview) and the audit's `body` fact (byte count and SHA-256).
|
|
727
|
-
creq.pause();
|
|
728
941
|
const tee = makeTee();
|
|
729
942
|
creq.on('data', (c) => tee.push(c));
|
|
730
943
|
// `end` fires once the whole body was read, whichever path read it (also
|
|
@@ -748,7 +961,53 @@ export function createProxy(opts) {
|
|
|
748
961
|
/** @type {() => void} */
|
|
749
962
|
let free = () => {};
|
|
750
963
|
const freeWork = () => { if (!freed) { freed = true; free(); } };
|
|
964
|
+
// M12: the open ask this request leads for its unknown model key, if any (see `keyAsks`).
|
|
965
|
+
/** @type {((r: 'allow'|'deny'|'none') => void) | null} */
|
|
966
|
+
let settleKey = null;
|
|
751
967
|
try {
|
|
968
|
+
// A model call is never card-scanned (user decision, Nov 2); the floor keeps every other request.
|
|
969
|
+
let tool = toolFor(matcher, tools, method, urlStr, modelEndpoints);
|
|
970
|
+
// M12: a call to a built-in model endpoint is a model call only with this run's key; any
|
|
971
|
+
// other key (or none) makes it a plain `x` POST. Parallel calls with one unknown key wait
|
|
972
|
+
// for the one open ask instead of asking again.
|
|
973
|
+
let unknownKey = null;
|
|
974
|
+
if (builtinModels.has(tool)) {
|
|
975
|
+
for (;;) {
|
|
976
|
+
unknownKey = otherKey(creq.headers, found);
|
|
977
|
+
const open = unknownKey?.hash ? keyAsks.get(unknownKey.hash) : undefined;
|
|
978
|
+
if (!open) break;
|
|
979
|
+
// A waiter holds a place among the agent's waiters (the queue owns the count), and loses it
|
|
980
|
+
// when its client goes or the ask ends.
|
|
981
|
+
const release = holds ? holds.wait(agent) : () => {};
|
|
982
|
+
if (!release) {
|
|
983
|
+
discard(creq);
|
|
984
|
+
denyRes(cres, 429, 'denied: hold queue full');
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
/** @type {() => void} */
|
|
988
|
+
let onGone = () => {};
|
|
989
|
+
const gone = new Promise((r) => { onGone = () => r('gone'); cres.once('close', onGone); });
|
|
990
|
+
const r = await Promise.race([open, gone]);
|
|
991
|
+
cres.off('close', onGone);
|
|
992
|
+
release();
|
|
993
|
+
if (r === 'gone') { discard(creq); return; }
|
|
994
|
+
if (r === 'deny') {
|
|
995
|
+
discard(creq);
|
|
996
|
+
denyRes(cres, 403, 'denied: model key');
|
|
997
|
+
return;
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
if (unknownKey) {
|
|
1001
|
+
tool = `http.${method}`;
|
|
1002
|
+
if (unknownKey.hash) {
|
|
1003
|
+
const hash = unknownKey.hash;
|
|
1004
|
+
/** @type {(r: 'allow'|'deny'|'none') => void} */
|
|
1005
|
+
let resolveAsk = () => {};
|
|
1006
|
+
keyAsks.set(hash, new Promise((r) => { resolveAsk = r; }));
|
|
1007
|
+
settleKey = (r) => { settleKey = null; keyAsks.delete(hash); resolveAsk(r); };
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
752
1011
|
if (hasBody) {
|
|
753
1012
|
free = await takeWorkSlot(agent, cres);
|
|
754
1013
|
} else creq.resume();
|
|
@@ -763,9 +1022,7 @@ export function createProxy(opts) {
|
|
|
763
1022
|
/** @type {RequestCtx} */
|
|
764
1023
|
const ctx = { agent, method, url: urlStr, headers: { ...creq.headers }, creq, cres, tee,
|
|
765
1024
|
hasBody, chunks: [], over: false, freeWork, asked: false, status: null, heldId: null,
|
|
766
|
-
endAsk: null, decodedHead: null, effect: null };
|
|
767
|
-
// A model call is never card-scanned (user decision, Nov 2); the floor keeps every other request.
|
|
768
|
-
const tool = toolFor(matcher, tools, method, urlStr, modelEndpoints);
|
|
1025
|
+
endAsk: null, decodedHead: null, effect: null, keyLast4: unknownKey?.last4 ?? '', modelKey: unknownKey ? (unknownKey.hash ? 'other' : 'none') : '', askRule: null, answered: false, timedOut: false };
|
|
769
1026
|
let cardLike = false;
|
|
770
1027
|
if (hasBody) {
|
|
771
1028
|
if (await readWorkBody(ctx)) return;
|
|
@@ -780,10 +1037,18 @@ export function createProxy(opts) {
|
|
|
780
1037
|
// The body never goes in the action: bareguard writes the action to its audit file.
|
|
781
1038
|
const action = { type: 'net', tool, url: urlStr, method, agent,
|
|
782
1039
|
cardLike, paymentPath: paymentPath(urlStr), rid,
|
|
1040
|
+
...(unknownKey ? { modelKey: 'other' } : {}),
|
|
783
1041
|
...(floorHit ? { floor: floorHit.kind, floorEntry: floorHit.entry } : {}) };
|
|
784
1042
|
inflightCtx.set(rid, ctx);
|
|
785
1043
|
const g = await gateOf(agent);
|
|
786
1044
|
const d = await decideAction(g, action);
|
|
1045
|
+
// M12: a human's answer about an unknown key (not a card or floor ask) is the key's answer.
|
|
1046
|
+
if (settleKey) {
|
|
1047
|
+
const keyAsk = ctx.asked && !String(ctx.askRule).startsWith('flags.');
|
|
1048
|
+
if (keyAsk && d.outcome === 'allow' && unknownKey?.hash) rememberKey(unknownKey.hash);
|
|
1049
|
+
// Only a person's answer or the hold timeout denies the waiters; a cancel, a close or a failure lets the next one ask.
|
|
1050
|
+
settleKey(!keyAsk ? 'none' : d.outcome === 'allow' ? 'allow' : ctx.answered ? 'deny' : 'none');
|
|
1051
|
+
}
|
|
787
1052
|
if (d.outcome === 'allow') {
|
|
788
1053
|
const common = { agent, method, url: urlStr, headers: withSecrets(ctx.headers), cres,
|
|
789
1054
|
...(d.aid ? { rec: { gate: g, action, aid: d.aid } } : {}) };
|
|
@@ -810,6 +1075,7 @@ export function createProxy(opts) {
|
|
|
810
1075
|
denyRes(cres, ctx.status ?? 403, why);
|
|
811
1076
|
}
|
|
812
1077
|
} finally {
|
|
1078
|
+
settleKey?.('none');
|
|
813
1079
|
inflightCtx.delete(rid);
|
|
814
1080
|
freeWork();
|
|
815
1081
|
}
|
|
@@ -933,6 +1199,14 @@ export function createProxy(opts) {
|
|
|
933
1199
|
server.on('clientError', (err, sock) => {
|
|
934
1200
|
try { sock.destroy(); } catch {}
|
|
935
1201
|
});
|
|
1202
|
+
// A protocol upgrade (WebSocket, h2c) and a CONNECT inside a tunnel are refused at once, in
|
|
1203
|
+
// every mode and for every host: nothing is resolved, gated or dialed. Without these
|
|
1204
|
+
// listeners node would forward the upgrade as a GET, or close the socket with no reason.
|
|
1205
|
+
server.on('upgrade', (creq, sock) => {
|
|
1206
|
+
const t = creq.url || '';
|
|
1207
|
+
denyRaw(sock, 403, 'denied: upgrade', targetUrl(creq)?.toString() ?? t);
|
|
1208
|
+
});
|
|
1209
|
+
server.on('connect', (creq, sock) => { denyRaw(sock, 403, 'denied: connect', creq.url || ''); });
|
|
936
1210
|
|
|
937
1211
|
// Dispatch: one CONNECT line, or plain HTTP straight into the same server.
|
|
938
1212
|
function admit(sock, agent) {
|
|
@@ -984,11 +1258,21 @@ export function createProxy(opts) {
|
|
|
984
1258
|
}
|
|
985
1259
|
// Deny the tunnel itself: no cert is minted for a walled destination,
|
|
986
1260
|
// and the inner request is checked again on arrival anyway.
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
1261
|
+
// M14: the host decision first. A host nobody decided opens its tunnel with no DNS: the first
|
|
1262
|
+
// request inside it asks (`handleRequest`), and `forward` resolves only after the allow.
|
|
1263
|
+
const hd = hostDecision(host);
|
|
1264
|
+
if (hd.d === 'deny') {
|
|
1265
|
+
hostRefusal(agentOf(sock), hd);
|
|
1266
|
+
denyRaw(sock, 403, /** @type {string} */ (hd.reason));
|
|
990
1267
|
return;
|
|
991
1268
|
}
|
|
1269
|
+
if (hd.d === 'allow') {
|
|
1270
|
+
const verdict = await checkUpstream(host, gate, portNum);
|
|
1271
|
+
if (!verdict.ok) {
|
|
1272
|
+
denyRaw(sock, 403, verdict.reason);
|
|
1273
|
+
return;
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
992
1276
|
if (closed || sock.destroyed) return;
|
|
993
1277
|
try { sock.write('HTTP/1.1 200 Connection established\r\n\r\n'); }
|
|
994
1278
|
catch { return; }
|
|
@@ -1156,6 +1440,8 @@ export function createProxy(opts) {
|
|
|
1156
1440
|
addAgent,
|
|
1157
1441
|
removeAgent,
|
|
1158
1442
|
pending: () => (holds ? holds.pending() : []),
|
|
1443
|
+
/** M14: hosts a person allowed this run, and hosts refused by `unknown: 'deny'`; each sorted and unique. @returns {{ allowed: string[], refused: string[] }} */
|
|
1444
|
+
hostsReport: () => ({ allowed: [...runHosts].filter(([, d]) => d === 'allow').map(([h]) => h).sort(), refused: [...refusedHosts].sort() }),
|
|
1159
1445
|
get caFile() { return path.join(certDir, 'ca.pem'); },
|
|
1160
1446
|
};
|
|
1161
1447
|
}
|
package/src/run.js
CHANGED
|
@@ -66,6 +66,7 @@ import { loadSecrets } from './secrets.js';
|
|
|
66
66
|
* @property {{ matcher: any, tools: Record<string, any>, dirs?: string[] }} [labels] the loaded label files (`loadLabels`); their folders are masked from the sandbox
|
|
67
67
|
* @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)
|
|
68
68
|
* @property {{ pay?: string[], send?: string[] }} [floor] the config `floor` key (M11): hosts, `*.domain` or `"METHOD host/path"` entries that ask in every mode, `trust` included (see `createProxy`)
|
|
69
|
+
* @property {{ allow?: string[], deny?: string[], unknown?: 'ask'|'deny' }} [hosts] the config `hosts` key (M14): `deny` hosts are refused before DNS in every mode; `allow` hosts never get the first-contact ask; any other host asks once (`unknown` `ask`, the default) or is refused (`deny`). `trust` lets other hosts through, a `deny` host still refused (see `createProxy`)
|
|
69
70
|
* @property {object} [unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`): everything under it weakens the sandbox wall
|
|
70
71
|
* @property {NodeJS.WritableStream} [stdout] where the agent's stdout goes (default process.stdout)
|
|
71
72
|
* @property {NodeJS.WritableStream} [stderr] where the agent's stderr goes (default process.stderr)
|
|
@@ -91,6 +92,7 @@ import { loadSecrets } from './secrets.js';
|
|
|
91
92
|
* @param {{ matcher: any, tools: Record<string, any>, dirs?: string[] }|null} [opts.labels] the loaded label files (`loadLabels`); their folders are masked from the sandbox
|
|
92
93
|
* @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)
|
|
93
94
|
* @param {{ pay?: string[], send?: string[] }|null} [opts.floor] the config `floor` key (M11): hosts, `*.domain` or `"METHOD host/path"` entries that ask in every mode, `trust` included (see `createProxy`)
|
|
95
|
+
* @param {{ allow?: string[], deny?: string[], unknown?: 'ask'|'deny' }|null} [opts.hosts] the config `hosts` key (M14); see {@link RunOptions}
|
|
94
96
|
* @param {object|null} [opts.unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`)
|
|
95
97
|
* @param {NodeJS.WritableStream|null} [opts.stdout] where the agent's stdout goes (default process.stdout)
|
|
96
98
|
* @param {NodeJS.WritableStream|null} [opts.stderr] where the agent's stderr goes (default process.stderr)
|
|
@@ -98,7 +100,7 @@ import { loadSecrets } from './secrets.js';
|
|
|
98
100
|
* @param {{ pass?: string[], set?: Record<string, string> }|null} [opts.env] the sandbox's environment (M5), the config `env` shape; see {@link RunOptions}
|
|
99
101
|
* @param {boolean} [opts.overlay] when true, mount a per-run overlay upper over the project instead of binding it read-only; the result's `diff` lists the run's changes for commit/rollback
|
|
100
102
|
* @param {string[]} [opts.overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
|
|
101
|
-
* @returns {Promise<{ exit: number, asks: AskRecord[], audit: string, diff: import('./overlay.js').OverlayChange[], runtime: string }>} the agent process exit code, the collected ask records, the JSONL audit log path, the run's overlay diff (M4),
|
|
103
|
+
* @returns {Promise<{ exit: number, asks: AskRecord[], audit: string, diff: import('./overlay.js').OverlayChange[], runtime: string, hosts: { allowed: string[], refused: string[] } }>} the agent process exit code, the collected ask records, the JSONL audit log path, the run's overlay diff (M4), the runtime dir addressing it, and the hosts a person allowed or `unknown: 'deny'` refused (M14)
|
|
102
104
|
* @when Reach for this to HARNESS-ONLY run one sandboxed agent start-to-finish in a single call: it starts the proxy, sandboxes the command, answers holds, and returns the exit code with the ask and audit trail (plus the overlay diff once M4 exists).
|
|
103
105
|
* @fails Rejects on a missing/unreadable `proj`, an empty `command`, a bad `mode`, a misshapen `onAsk`, a `secrets` entry with no value (a `fromEnv` variable missing from this process's environment; the message names the secret, never a value), a proxy that never becomes ready, a `launch` that throws (uncommitted overlay changes, a runtime inside the project — the proxy is closed first), or an overlay diff that cannot be read. The agent's own nonzero exit is returned as `exit`, never thrown.
|
|
104
106
|
* @example
|
|
@@ -107,7 +109,7 @@ import { loadSecrets } from './secrets.js';
|
|
|
107
109
|
*/
|
|
108
110
|
export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
109
111
|
onEvent = null, runtime = null, agent = 'agent', timeoutMs, heldBodyMaxBytes,
|
|
110
|
-
allowLocal = [], floor = null, labels = null, unsafeTestOnly = null, stdout = null, stderr = null,
|
|
112
|
+
allowLocal = [], floor = null, hosts = null, labels = null, unsafeTestOnly = null, stdout = null, stderr = null,
|
|
111
113
|
overlay = false, overlayIgnore, secrets = null, env = null }) {
|
|
112
114
|
if (typeof proj !== 'string' || !proj) throw new Error('run: proj must be a non-empty string');
|
|
113
115
|
if (!fs.existsSync(proj)) throw new Error(`run: proj does not exist: ${proj}`);
|
|
@@ -145,7 +147,9 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
|
145
147
|
: recordEvent;
|
|
146
148
|
|
|
147
149
|
const proxy = createProxy({
|
|
148
|
-
runtime: rt, logFile: audit, allowLocal, ...(floor ? { floor } : {}),
|
|
150
|
+
runtime: rt, logFile: audit, allowLocal, ...(floor ? { floor } : {}),
|
|
151
|
+
hosts: { allow: hosts?.allow, deny: hosts?.deny, unknown: mode === 'trust' ? 'allow' : (hosts?.unknown ?? 'ask') },
|
|
152
|
+
unsafeTestOnly, secrets: loaded,
|
|
149
153
|
...(labels ? { labels } : {}),
|
|
150
154
|
gateFor: (name, { humanChannel, tools }) => gateFor({ agent: name, mode, auditPath: audit, humanChannel, tools }),
|
|
151
155
|
hold: { onAsk, timeoutMs, maxBody: heldBodyMaxBytes, onEvent: holdOnEvent },
|
|
@@ -164,6 +168,7 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
|
164
168
|
// sockets keep this process alive forever.
|
|
165
169
|
/** @type {number} */
|
|
166
170
|
let exit;
|
|
171
|
+
let hostsSeen = { allowed: /** @type {string[]} */ ([]), refused: /** @type {string[]} */ ([]) };
|
|
167
172
|
try {
|
|
168
173
|
sock = proxy.addAgent(agent);
|
|
169
174
|
const child = launch({
|
|
@@ -184,6 +189,7 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
|
184
189
|
// The sandbox is gone: end the agent's holds as client gone now, not
|
|
185
190
|
// as 'proxy closing' if close() beats the sockets' async 'close'.
|
|
186
191
|
if (sock) proxy.removeAgent(agent);
|
|
192
|
+
hostsSeen = proxy.hostsReport();
|
|
187
193
|
await proxy.close();
|
|
188
194
|
}
|
|
189
195
|
// M2.5 item 4: the result carries the M4 diff. Without overlay there is no
|
|
@@ -199,5 +205,5 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
|
199
205
|
throw new Error(`run: overlay diff failed after exit ${exit}: ${err.message}`);
|
|
200
206
|
}
|
|
201
207
|
}
|
|
202
|
-
return { exit, asks: [...seen.values()], audit, diff, runtime: rt };
|
|
208
|
+
return { exit, asks: [...seen.values()], audit, diff, runtime: rt, hosts: hostsSeen };
|
|
203
209
|
}
|