barebox 0.14.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 CHANGED
@@ -4,6 +4,21 @@ All notable changes to this project will be documented in this file.
4
4
 
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
6
6
 
7
+ ## [0.15.0] - 2026-12-01
8
+
9
+ ### Added
10
+
11
+ - `hosts` config key (`allow`, `deny`, `unknown`): a `deny` host is refused in every mode before any DNS lookup; an `allow` host never gets the first-contact question; any other host asks once on first contact in `ask` and `auto` (allow for this run, or deny) and passes in `trust`. With no terminal (CI, `--json`, piped) `sbx run` refuses such a host at once with `403 denied: host not in hosts.allow`. Answers last for the run only: nothing is stored, and a typed deny is kept while a hold-timeout deny is not. `sbx run` prints a `hosts:` summary line at the start and, at the end, the hosts you allowed (to paste into `hosts.allow`) and the hosts refused; `--json` gives one `hosts` event. The question shows the host, the method and the URL (userinfo and card numbers masked) cut to 200 characters with the full length. Model endpoint hosts, hosts bound to a secret and `localLlm` hosts are exempt. When a first-contact question ends by the hold timeout, every request waiting on that host is denied at once (`403 denied: hold timeout`) and nothing is remembered, so the next request asks again. `run({ hosts })` and `createProxy({ hosts })` take the same shape; `run()` returns `hosts: { allowed, refused }`.
12
+
13
+ ### Changed
14
+
15
+ - `run()` now asks on first contact with a new host by default (`hosts.unknown` ask); `createProxy` still lets every host pass unless you pass `hosts`.
16
+
17
+ ### Security
18
+
19
+ - The first request to a host you never chose no longer leaves unasked in `ask` and `auto`, and its name is not resolved before the decision (a tunnel to it opens with no DNS and asks on its first request). Data sent to a host you allowed, and every host in `trust`, is still unchecked.
20
+ - Every refused request's audit `deny` line names its method and URL, refusals before the gate included (a bad target, a host deny, the wall, a hold timeout, a full hold queue). In barebox's own audit lines the URL has userinfo masked whole and card numbers masked to their last 4 digits. bareguard's gate decision lines still keep the URL as sent.
21
+
7
22
  ## [0.14.0] - 2026-11-30
8
23
 
9
24
  ### Security
package/README.md CHANGED
@@ -70,7 +70,7 @@ Then a payment stops like this, with the recipient, amount and currency pulled f
70
70
  Allow? [y/N] (hold h1)
71
71
  ```
72
72
 
73
- `y` allows it, anything else denies it (403, nothing leaves). An answer counts for that one request; nothing is saved. One held request per agent at a time; up to 16 more wait in line, plus up to 16 model calls waiting behind one new-key question; past either, `429`.
73
+ `y` allows it, anything else denies it (403, nothing leaves). An answer counts for that one request; nothing is saved. The exceptions last for the run only: a model key you allow, and a host you allow or deny on first contact. One held request per agent at a time; up to 16 more wait in line, plus up to 16 model calls waiting behind one new-key question; past either, `429`.
74
74
 
75
75
  ## Blocked by default
76
76
 
@@ -80,12 +80,13 @@ Then a payment stops like this, with the recipient, amount and currency pulled f
80
80
  - **Private and local addresses,** checked after DNS on every resolved IP.
81
81
  - **Real API keys,** swapped in only after a yes, only over HTTPS, only to the key's own hosts.
82
82
  - **The agent answering its own asks,** and reading the config file.
83
+ - **A host you never chose:** the first request to it asks (`ask` and `auto`), before its name is resolved; `hosts.deny` refuses a host in every mode. With no terminal an unknown host is refused at once.
83
84
 
84
85
  ## Not blocked yet
85
86
 
86
87
  barebox is a guardrail against mistakes and prompt-injected agents, not a VM. Known gaps (details in [the guide](https://github.com/hamr0/barebox/blob/main/docs/wiki/guide.md#what-it-does-not-block)):
87
88
 
88
- - data in a `GET` URL, and data hidden in a hostname (DNS resolves before the gate);
89
+ - data in a `GET` URL, and data hidden in a hostname, to a host you allowed or in `trust` (DNS resolves before the gate there);
89
90
  - bodies over 64 KB are not scanned for card numbers;
90
91
  - `~/.claude` stays readable.
91
92
 
@@ -32,6 +32,8 @@ import { join } from "node:path";
32
32
  // then add the agent to it.
33
33
  const runtime = mkdtempSync(join(tmpdir(), "sbx-"));
34
34
  const proj = mkdtempSync(join(tmpdir(), "proj-"));
35
+ // No `hosts` here, so every host passes with no first-contact ask. For asks pass `hosts: { unknown: "ask" }`
36
+ // and a `gateFor`; `run()` and `sbx` ask by default.
35
37
  const proxy = createProxy({ runtime, port: 0, logFile: join(runtime, "mitm.log") });
36
38
  await proxy.ready;
37
39
  const child = launch({ runtime, agent: "fx", proj, command: ["bash", "-c", "echo hi"], socket: proxy.addAgent("fx"), caFile: proxy.caFile });
@@ -48,6 +50,8 @@ import { join } from "node:path";
48
50
  // The TCP port is opt-in for tests (bound to 127.0.0.1); agents connect
49
51
  // over their own unix socket: proxy.addAgent("fx") -> <runtime>/socks/fx.sock
50
52
  const runtime = mkdtempSync(join(tmpdir(), "sbx-"));
53
+ // No `hosts` here, so every host passes with no first-contact ask. For asks pass `hosts: { unknown: "ask" }`
54
+ // and a `gateFor`; `run()` and `sbx` ask by default.
51
55
  const proxy = createProxy({ runtime, port: 0, logFile: join(runtime, "mitm.log") });
52
56
  await proxy.ready;
53
57
  await proxy.close();
@@ -109,11 +113,12 @@ exact `host:port` pairs, such as a local model server, past the wall.
109
113
 
110
114
  ```js no-run
111
115
  import { run } from "barebox";
112
- const { exit, asks, audit, diff, runtime } = await run({
116
+ const { exit, asks, audit, diff, runtime, hosts } = await run({
113
117
  proj: "/path/to/project",
114
118
  command: ["bash", "-c", "echo hi"],
115
119
  mode: "auto",
116
120
  overlay: true, // writes land on the undo layer; `diff` lists them
121
+ // hosts: { allow: ["registry.npmjs.org"] }, // `hosts` in the result: { allowed, refused }
117
122
  onAsk: async (ask) => ({ decision: "deny", reason: "not today" }), // omit for the file checkpoint
118
123
  });
119
124
  ```
@@ -135,7 +140,7 @@ Its exit code mirrors the agent's.
135
140
  (positive integer) and `localLlm` (array of `"host:port"`). A flag beats the file, the file beats the default; an
136
141
  unknown key, bad value or bad JSON exits 2 naming the file and key. The file
137
142
  is hidden inside the sandbox wherever it resolves. The library does not read it.
138
- Two more keys, `labels` and `tenants`, are described under "Labels and model endpoints". `floor` (`{ pay?: string[], send?: string[] }`) lists your own payment and send domains: an entry is a host, `*.domain` (subdomains only) or `"METHOD host/path"`; any write to a listed host, or the one listed endpoint, asks in every mode, `trust` included, and the question shows the recipient, amount and currency fields found in the body (labelled by path), or says why none was read. Each of the three lists in the effect holds at most 6 fields, and 6 means "more than 5": a list of more than 5 is shown as "more than 5 fields", none listed. Endpoint entries match the request path case-insensitively, with `%XX` of unreserved characters decoded and `;params` dropped; `sbx pending` shows the floor entry and the effect lines. There are no built-in entries; an absent `floor` lists nothing. Two more, `env` and `secrets`, are described under "Keys the agent never holds".
143
+ `hosts` (`{ allow?: string[], deny?: string[], unknown?: "ask"|"deny" }`; entries are a lower-case host or `*.domain`) decides which hosts the agent may reach: a `deny` host is refused in every mode before any DNS lookup, an `allow` host never gets the first-contact question, and any other host asks once on first contact in `ask` and `auto` (allow for this run, or deny; `trust` lets it through). `unknown: "deny"` refuses such hosts at once, which `sbx run` does by default with no terminal. Model endpoints, secret hosts and `localLlm` hosts never ask. In the library, `run({ hosts })` takes the same shape and its result carries `hosts: { allowed, refused }`; `createProxy({ hosts })` also takes `unknown: "allow"`, its default. `sbx run` prints a `hosts:` summary line at the start, and at the end the hosts you allowed as a line to paste into `hosts.allow`. Two more keys, `labels` and `tenants`, are described under "Labels and model endpoints". `floor` (`{ pay?: string[], send?: string[] }`) lists your own payment and send domains: an entry is a host, `*.domain` (subdomains only) or `"METHOD host/path"`; any write to a listed host, or the one listed endpoint, asks in every mode, `trust` included, and the question shows the recipient, amount and currency fields found in the body (labelled by path), or says why none was read. Each of the three lists in the effect holds at most 6 fields, and 6 means "more than 5": a list of more than 5 is shown as "more than 5 fields", none listed. Endpoint entries match the request path case-insensitively, with `%XX` of unreserved characters decoded and `;params` dropped; `sbx pending` shows the floor entry and the effect lines. There are no built-in entries; an absent `floor` lists nothing. Two more, `env` and `secrets`, are described under "Keys the agent never holds".
139
144
 
140
145
  ## Modes and the gate
141
146
 
@@ -275,6 +280,11 @@ it between runs (no proxy running) to start a new one.
275
280
  its outcome share `meta.id`; a request with a body gets one `body` line,
276
281
  `meta: { agent, rid, bodyBytes, bodySha256 }`, joined to its gate line by
277
282
  `action.rid`.
283
+ - Every refused request has a `deny` line with `meta: { agent, code, note, method, url }`,
284
+ refusals before the gate included (a bad target, a host deny, the wall, a hold
285
+ timeout, a full hold queue). Without a `Host` header, `url` is the raw target.
286
+ - In barebox's own lines, `url` (in `meta` and in `where`) has userinfo masked whole (`http://***@host/...`) and card
287
+ numbers masked to their last 4 digits. bareguard's gate lines keep the URL as sent.
278
288
  - Lines for an agent whose gate is not built, and every line when `gateFor` is
279
289
  omitted, are written by a runtime-level `sbx` gate (`meta.agent` names the
280
290
  agent).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barebox",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "description": "Lightweight local sandbox for AI agents: every write undoable, nothing leaves the machine without passing the doorman.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
package/primitives.json CHANGED
@@ -60,7 +60,7 @@
60
60
  "category": "run",
61
61
  "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).",
62
62
  "import": "import { run } from 'barebox'",
63
- "signature": "run(opts: object) => Promise<{ exit: number, asks: AskRecord[], audit: string, diff: OverlayChange[], runtime: string }>",
63
+ "signature": "run(opts: object) => Promise<{ exit: number, asks: AskRecord[], audit: string, diff: OverlayChange[], runtime: string, hosts: { allowed: string[], refused: string[] } }>",
64
64
  "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.",
65
65
  "example": "import { run } from \"barebox\";\nconst { exit, asks, audit } = await run({ proj: \"/tmp/proj\", command: [\"bash\", \"-c\", \"echo hi\"] });"
66
66
  }
package/src/cli.js CHANGED
@@ -38,7 +38,7 @@ import { resolveConfig } from './config.js';
38
38
  import { loadLabels } from './labels.js';
39
39
  import { MODES } from './policy.js';
40
40
  import { run as sandboxRun } from './run.js';
41
- import { createTerminalPrompt, paint, ANSI, effectLines, floorTail, keyTail } from './prompt.js';
41
+ import { createTerminalPrompt, paint, ANSI, effectLines, floorTail, keyTail, askUrl } from './prompt.js';
42
42
  import { DEFAULT_POLL_MS, writeTmpFile } from './holds.js';
43
43
  import { diffOverlay, commitOverlay, rollbackOverlay } from './overlay.js';
44
44
  import { assertAgentName, createRuntime, namedRuntime, hostNode, runtimePaths, runtimeLive, safe, shellQuote } from './runtime.js';
@@ -218,7 +218,7 @@ async function run(args) {
218
218
  usage();
219
219
  }
220
220
  if (values.mode !== undefined && !MODES.includes(values.mode)) usage();
221
- /** @type {{ mode: string, holdTimeoutSec?: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, floor?: { pay?: string[], send?: string[] }, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} */
221
+ /** @type {{ mode: string, holdTimeoutSec?: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, floor?: { pay?: string[], send?: string[] }, hosts?: { allow?: string[], deny?: string[], unknown?: 'ask'|'deny' }, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} */
222
222
  let cfg;
223
223
  try {
224
224
  cfg = resolveConfig({ mode: values.mode, hold: values.hold });
@@ -271,7 +271,7 @@ async function run(args) {
271
271
  if (prompt?.ask(h)) { prompted.add(h.id); return; }
272
272
  const c = clean(h, ['id', 'agent', 'method', 'url', 'rule', 'bodyPreview']);
273
273
  if (json) out(JSON.stringify({ ev: 'ask', ...c }));
274
- else out(`ask ${c.id} ${c.agent} ${c.method} ${c.url} rule=${c.rule}${floorTail(h)}${keyTail(h)}`);
274
+ else out(`ask ${c.id} ${c.agent} ${c.method} ${askUrl(h)} rule=${c.rule}${floorTail(h)}${keyTail(h)}`);
275
275
  };
276
276
  const emitDecided = (e) => {
277
277
  if (!json && prompted.delete(e.id)) return;
@@ -286,7 +286,12 @@ async function run(args) {
286
286
  } else err(name !== undefined
287
287
  ? `sandbox ${name} (answer from another terminal: sbx approve --name ${name} <id>)`
288
288
  : `runtime ${runtime} (answer with: SBX_RUNTIME=${shellQuote(runtime)} sbx approve <id>)`);
289
- /** @type {{ exit: number, diff: { path: string }[] } | null} */
289
+ // M14: hosts on neither list ask when a person is here, else are refused; `trust` lets them through.
290
+ const hostsUnknown = cfg.hosts?.unknown ?? (interactive ? 'ask' : 'deny');
291
+ err(`hosts: ${cfg.hosts?.allow?.length ?? 0} allowed, ${cfg.hosts?.deny?.length ?? 0} denied in config; other hosts ${
292
+ mode === 'trust' ? 'pass (trust)' : hostsUnknown === 'ask' ? 'ask on first contact'
293
+ : cfg.hosts?.unknown ? 'are refused' : 'are refused (no terminal)'}`);
294
+ /** @type {{ exit: number, diff: { path: string }[], hosts: { allowed: string[], refused: string[] } } | null} */
290
295
  let result = null;
291
296
  try {
292
297
  // SBX_OVERLAY_IGNORE extends the M4 ignore list (Q3) as comma names.
@@ -295,7 +300,7 @@ async function run(args) {
295
300
  result = await sandboxRun({
296
301
  runtime, proj: process.cwd(), command, mode, timeoutMs,
297
302
  ...(name !== undefined ? { agent: name } : {}),
298
- allowLocal: cfg.localLlm, floor: cfg.floor, labels, secrets: cfg.secrets, env: cfg.env,
303
+ allowLocal: cfg.localLlm, floor: cfg.floor, hosts: { ...cfg.hosts, unknown: hostsUnknown }, labels, secrets: cfg.secrets, env: cfg.env,
299
304
  ...(cfg.heldBodyMaxMB ? { heldBodyMaxBytes: cfg.heldBodyMaxMB * 1048576 } : {}),
300
305
  unsafeTestOnly: { allowLoopback: process.env.SBX_UNSAFE_TEST_ALLOW_LOOPBACK === '1' },
301
306
  overlay,
@@ -317,6 +322,13 @@ async function run(args) {
317
322
  prompt?.close();
318
323
  if (json) out(JSON.stringify({ ev: 'done', exit: result.exit }));
319
324
  else out(`done exit ${result.exit}`);
325
+ const { allowed, refused } = result.hosts;
326
+ if (json) {
327
+ if (allowed.length || refused.length) out(JSON.stringify({ ev: 'hosts', allowed, refused }));
328
+ } else {
329
+ if (allowed.length) out(`hosts allowed this run (add to hosts.allow): ${JSON.stringify(allowed)}`);
330
+ if (refused.length) out(`hosts refused (not in hosts.allow): ${JSON.stringify(refused)}`);
331
+ }
320
332
  if (overlay) {
321
333
  const n = result.diff.length;
322
334
  err(n
@@ -426,7 +438,7 @@ async function pending(rest) {
426
438
  // Agent-controlled bytes (URL, rule, body preview): sanitized before
427
439
  // they reach the approver's terminal (see `safe`).
428
440
  const body = safe(h.bodyPreview).replace(/\s+/g, ' ').slice(0, 200);
429
- out(`${safe(h.id)} ${safe(h.agent)} ${safe(h.method)} ${safe(h.url)} (${waiting}s) rule=${safe(h.rule)}${floorTail(h)}${keyTail(h)} body=${body}`);
441
+ out(`${safe(h.id)} ${safe(h.agent)} ${safe(h.method)} ${askUrl(h)} (${waiting}s) rule=${safe(h.rule)}${floorTail(h)}${keyTail(h)} body=${body}`);
430
442
  for (const line of effectLines(h.effect, false)) out(line);
431
443
  }
432
444
  process.exit(0);
package/src/config.js CHANGED
@@ -7,6 +7,7 @@ import os from 'node:os';
7
7
  import path from 'node:path';
8
8
  import { MODES } from './policy.js';
9
9
  import { floorList } from './lists.js';
10
+ import { hostMatcher } from 'bareguard';
10
11
 
11
12
  const DEFAULTS = { mode: 'auto', localLlm: [], labels: [], tenants: {} };
12
13
 
@@ -80,6 +81,23 @@ const checkFloor = (/** @type {any} */ v) => {
80
81
  return null;
81
82
  };
82
83
 
84
+ /** @param {unknown} v @returns {string|null} the error for a `hosts` value, or null */
85
+ const checkHosts = (/** @type {any} */ v) => {
86
+ if (!isObj(v)) return 'must be an object of { allow?, deny?, unknown? }';
87
+ for (const [k, list] of Object.entries(v)) {
88
+ if (k === 'unknown') {
89
+ if (list !== 'ask' && list !== 'deny') return 'hosts.unknown must be "ask" or "deny"';
90
+ } else if (k === 'allow' || k === 'deny') {
91
+ if (!Array.isArray(list)) return `hosts.${k} must be an array`;
92
+ for (const [i, e] of list.entries()) {
93
+ if (typeof e !== 'string') return `hosts.${k}[${i}] must be a string`;
94
+ try { hostMatcher([e]); } catch (err) { return `hosts.${k}[${i}]: ${err instanceof Error ? err.message : String(err)}`; }
95
+ }
96
+ } else return `has unknown field "${k}"`;
97
+ }
98
+ return null;
99
+ };
100
+
83
101
  /** Validators by key; each returns an error string or null. */
84
102
  const KEYS = {
85
103
  mode: (v) => (MODES.includes(v) ? null : `must be one of ${MODES.join(', ')}`),
@@ -94,6 +112,7 @@ const KEYS = {
94
112
  && Object.values(v).every((a) => Array.isArray(a) && a.length > 0 && a.every(isHttpUrl))
95
113
  ? null : 'must be an object of vendor -> non-empty array of http(s) URLs'),
96
114
  floor: checkFloor,
115
+ hosts: checkHosts,
97
116
  env: checkEnv,
98
117
  secrets: checkSecrets,
99
118
  };
@@ -113,7 +132,7 @@ export function configPath(env = process.env) {
113
132
  * Read the config file over the defaults. No file means defaults.
114
133
  *
115
134
  * @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
116
- * @returns {{ mode: string, holdTimeoutSec?: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, floor?: { pay?: string[], send?: string[] }, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
135
+ * @returns {{ mode: string, holdTimeoutSec?: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, floor?: { pay?: string[], send?: string[] }, hosts?: { allow?: string[], deny?: string[], unknown?: 'ask'|'deny' }, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
117
136
  * @throws {Error} naming the file (and the key) on invalid JSON, an unknown key or a bad value
118
137
  */
119
138
  export function loadConfig(env = process.env) {
@@ -155,7 +174,7 @@ export function loadConfig(env = process.env) {
155
174
  * @param {string} [flags.mode] `--mode`
156
175
  * @param {string} [flags.hold] `--hold` (`"never"` or a positive integer of seconds, as typed)
157
176
  * @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
158
- * @returns {{ mode: string, holdTimeoutSec?: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, floor?: { pay?: string[], send?: string[] }, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
177
+ * @returns {{ mode: string, holdTimeoutSec?: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, floor?: { pay?: string[], send?: string[] }, hosts?: { allow?: string[], deny?: string[], unknown?: 'ask'|'deny' }, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
159
178
  * @throws {Error} as {@link loadConfig}
160
179
  */
161
180
  export function resolveConfig(flags = {}, env = process.env) {
package/src/holds.js CHANGED
@@ -250,8 +250,8 @@ export function normalizeDecision(input, { approveAlias = false } = {}) {
250
250
  * @param {number} [opts.pollMs] answer poll interval in ms for the default file checkpoint (default 250, PRD Q9)
251
251
  * @param {OnEvent|null} [opts.onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon
252
252
  * @param {(entry: object) => void} opts.onApprove forward the parked request upstream
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
253
+ * @param {(entry: object, reason: string, answered: boolean, timedOut: 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); `timedOut`: the hold timeout ended it (so `answered && !timedOut` is a person's answer)
254
+ * @returns {{ add: (entry: object) => string|null, dropBody: (id: string) => void, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string, answered?: boolean, timedOut?: 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
255
255
  */
256
256
  export function createHolds({ log, timeoutMs = 120000,
257
257
  maxBody = DEFAULT_HOLD_MAX_BODY, runtime = null, onAsk = null, pollMs = DEFAULT_POLL_MS,
@@ -325,7 +325,7 @@ export function createHolds({ log, timeoutMs = 120000,
325
325
  const slots = new Map();
326
326
  /** Requests waiting behind another request's open model-key ask, by agent. @type {Map<string, number>} */
327
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 }>} */
328
+ /** Internal reserve state by returned handle identity. @type {WeakMap<object, { agent: string, onReady: () => void, onExpire: (reason: string, answered?: boolean, timedOut?: boolean) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean, id: string }>} */
329
329
  const handleState = new WeakMap();
330
330
 
331
331
  /**
@@ -353,7 +353,7 @@ export function createHolds({ log, timeoutMs = 120000,
353
353
  if (!s.holder && s.line.length === 0) slots.delete(agent);
354
354
  }
355
355
  }
356
- st.onExpire(reason, true);
356
+ st.onExpire(reason, true, true);
357
357
  }
358
358
 
359
359
  /**
@@ -430,7 +430,7 @@ export function createHolds({ log, timeoutMs = 120000,
430
430
  try { fs.unlinkSync(paths.heldFile(id)); } catch {}
431
431
  }
432
432
 
433
- function settle(id, approved, reason, answered = false) {
433
+ function settle(id, approved, reason, answered = false, timedOut = false) {
434
434
  const h = queue.get(id);
435
435
  if (!h) return `unknown ${id}`;
436
436
  queue.delete(id);
@@ -444,7 +444,7 @@ export function createHolds({ log, timeoutMs = 120000,
444
444
  } else {
445
445
  dropBody(id);
446
446
  log({ ev: 'decide', id, agent: h.agent, decision, reason });
447
- onDeny(h, reason, answered);
447
+ onDeny(h, reason, answered, timedOut);
448
448
  }
449
449
  onEvent?.({ type: 'decided', id, decision, reason: reason || undefined });
450
450
  return approved ? `approved ${id}` : `denied ${id}`;
@@ -565,7 +565,7 @@ export function createHolds({ log, timeoutMs = 120000,
565
565
  id, agent, method, url, preview, bodyBytes, effect, floor, keyLast4, modelKey, sock, note, letter, finish, t0,
566
566
  slot: null,
567
567
  timer: ms === null ? null
568
- : setTimeout(() => settle(id, false, 'hold timeout', true), Math.max(0, ms - (Date.now() - t0))),
568
+ : setTimeout(() => settle(id, false, 'hold timeout', true, true), Math.max(0, ms - (Date.now() - t0))),
569
569
  };
570
570
  // Unref: a parked `never` hold must not keep the process alive by itself.
571
571
  if (entry.timer?.unref) entry.timer.unref();
@@ -586,7 +586,7 @@ export function createHolds({ log, timeoutMs = 120000,
586
586
  /**
587
587
  * Ask for this agent's hold slot before reading a held request's body.
588
588
  * @param {string} agent
589
- * @param {{ onReady: () => void, onExpire: (reason: string, answered?: boolean) => void }} cbs
589
+ * @param {{ onReady: () => void, onExpire: (reason: string, answered?: boolean, timedOut?: boolean) => void }} cbs
590
590
  * The handle's `id` is the id its hold will have (empty when `full`), so
591
591
  * the body file can be named before the hold parks.
592
592
  * @returns {{ state: 'now'|'queued'|'full', id: string, arrivedAt: number, cancel: () => void }}
@@ -597,7 +597,7 @@ export function createHolds({ log, timeoutMs = 120000,
597
597
  // receives that same object as `slot`, so holder comparisons use it.
598
598
  // The one deadline timer lives here, armed below for 'now' and
599
599
  // 'queued' alike; expiry runs through `expireReservation` only.
600
- /** @type {{ agent: string, onReady: () => void, onExpire: (reason: string, answered?: boolean) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean, id: string }} */
600
+ /** @type {{ agent: string, onReady: () => void, onExpire: (reason: string, answered?: boolean, timedOut?: boolean) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean, id: string }} */
601
601
  const st = { agent, onReady, onExpire, timer: null, consumed: false, done: false, id: '' };
602
602
  const s0 = slots.get(agent);
603
603
  /** @type {'now'|'queued'|'full'} */
@@ -655,7 +655,7 @@ export function createHolds({ log, timeoutMs = 120000,
655
655
  removeAskFile(id);
656
656
  dropBody(id);
657
657
  log({ ev: 'hold-abandoned', id, agent: h.agent, method: h.method, url: h.url });
658
- onDeny(h, 'client gone', false);
658
+ onDeny(h, 'client gone', false, false);
659
659
  onEvent?.({ type: 'decided', id, decision: 'deny', reason: 'client gone' });
660
660
  },
661
661
 
package/src/lists.js CHANGED
@@ -16,7 +16,7 @@ const METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'];
16
16
  * @param {string} host a hostname
17
17
  * @returns {string} the host without one trailing dot
18
18
  */
19
- const stripDot = (host) => (host.endsWith('.') ? host.slice(0, -1) : host);
19
+ export const stripDot = (host) => (host.endsWith('.') ? host.slice(0, -1) : host);
20
20
 
21
21
  /**
22
22
  * The one place a request URL is normalised: one trailing dot is stripped from the
package/src/policy.js CHANGED
@@ -34,6 +34,8 @@ const TOOLS = {
34
34
  'http.PUT': 'x',
35
35
  'http.PATCH': 'x',
36
36
  'http.DELETE': 'x',
37
+ // M14: the first-contact host ask is a flag ask (`newHost`), never a letter ask.
38
+ 'net.host': 'r',
37
39
  };
38
40
 
39
41
  /** Built-in model-call endpoints (`POST`, `r`), as endpoint-list entries. */
@@ -44,6 +46,8 @@ const MODEL_PATHS = [
44
46
  'POST api.openai.com/v1/responses',
45
47
  'POST api.openai.com/v1/embeddings',
46
48
  ];
49
+ /** Hosts of the built-in model endpoints: never a first-contact host ask (M14). */
50
+ export const MODEL_HOSTS = new Set(MODEL_PATHS.map((e) => e.slice(e.indexOf(' ') + 1).split('/')[0]));
47
51
  /** The endpoints of one local model server (`host:port`), as list entries. */
48
52
  const LOCAL_LLM_PATHS = ['/api/chat', '/api/generate', '/api/embed',
49
53
  '/v1/chat/completions', '/v1/completions'];
@@ -140,7 +144,7 @@ export function toolFor(matcher, tools, method, url, models) {
140
144
  }
141
145
 
142
146
  /** @type {Record<string, Record<string, 'ask' | 'deny'>>} */
143
- const FLAGS = { cardLike: { true: 'ask' }, paymentPath: { true: 'ask' }, floor: { pay: 'ask', send: 'ask' } };
147
+ const FLAGS = { cardLike: { true: 'ask' }, newHost: { true: 'ask' }, paymentPath: { true: 'ask' }, floor: { pay: 'ask', send: 'ask' } };
144
148
 
145
149
  /** Payment-destination path fragments: the URL-visible half of the floor (PRD section 2). */
146
150
  const PAYMENT_PATHS = ['/checkout', '/payment', '/orders', '/purchase'];
package/src/prompt.js CHANGED
@@ -8,6 +8,7 @@
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 { maskCards } from './cardscan.js';
11
12
  import { isEndpoint } from './lists.js';
12
13
  import { LIST_MAX } from './effect.js';
13
14
 
@@ -54,6 +55,26 @@ export function effectLines(effect, color) {
54
55
  });
55
56
  }
56
57
 
58
+ /** The most characters of a new host's URL path and query a question shows. */
59
+ const URL_CHARS = 200;
60
+
61
+ /**
62
+ * The URL of an ask, sanitized. For a first-contact host ask (`flags.newHost`) everything after the
63
+ * scheme (userinfo, host, path and query) has card numbers masked, then is cut to 200 characters and the
64
+ * full length is added, so a long URL is visible but bounded. The question's header line shows the true host.
65
+ *
66
+ * @param {AskRecord} ask the parked request
67
+ * @returns {string} the URL text, safe for a terminal
68
+ */
69
+ export function askUrl(ask) {
70
+ if (safe(ask.rule) !== 'flags.newHost') return safe(ask.url);
71
+ const url = String(ask.url ?? '');
72
+ const head = /^[a-z][a-z0-9+.-]*:\/\//i.exec(url)?.[0] ?? '';
73
+ // Mask card numbers before the cut, so a number the cut would split is still masked.
74
+ const rest = maskCards(url.slice(head.length));
75
+ return safe(rest.length > URL_CHARS ? `${head}${rest.slice(0, URL_CHARS)}… (${url.length} chars)` : `${head}${rest}`);
76
+ }
77
+
57
78
  /**
58
79
  * The ` floor=<kind> entry=<entry>` tail of a one-line ask (`sbx pending`, the non-terminal `ask` line); empty without a floor hit.
59
80
  *
@@ -96,6 +117,7 @@ export function questionLines(ask, now = Date.now(), color = false) {
96
117
  const rule = safe(ask.rule);
97
118
  const why = rule === 'flags.floor' && ask.floor
98
119
  ? `${ask.floor.kind === 'send' ? 'a send' : 'a payment'} to ${isEndpoint(ask.floor.entry) ? 'an endpoint' : 'a domain'} you listed (${safe(ask.floor.entry)})`
120
+ : rule === 'flags.newHost' ? 'a host new in this run (allow means for this run only)'
99
121
  : rule === 'flags.cardLike' ? 'it contains what looks like a card number'
100
122
  : rule === 'flags.paymentPath' ? 'the address looks like a payment'
101
123
  : ask.keyLast4 ? `a model call with a key that is not this run's (…${safe(ask.keyLast4)})`
@@ -112,7 +134,7 @@ export function questionLines(ask, now = Date.now(), color = false) {
112
134
  const lines = [
113
135
  head,
114
136
  ` ${paint(color, bold, 'Why:')} ${why}`,
115
- ` ${paint(color, bold, 'URL:')} ${paint(color, cyan, `${method} ${safe(ask.url)}`)}`,
137
+ ` ${paint(color, bold, 'URL:')} ${paint(color, cyan, `${method} ${askUrl(ask)}`)}`,
116
138
  ];
117
139
  lines.push(...effectLines(ask.effect, color));
118
140
  const body = safe(ask.bodyPreview).slice(0, BODY_CHARS);
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']);
@@ -60,6 +75,7 @@ const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
60
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
61
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
62
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.
63
79
  * @property {HoldOptions} [hold] hold queue config (deadline, caps, ask seam)
64
80
  * @property {number} [upstreamTimeoutMs] give up on an upstream response after this (default 120000)
65
81
  * @property {object} [unsafeTestOnly] TEST-ONLY escape hatch: everything under
@@ -71,7 +87,7 @@ const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
71
87
  * DNS stub: replaces the wall's resolver so rebinding is testable. Production omits it.
72
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.
73
89
  * @property {number} [clientIdleMs] kill a client tunnel idle this long; never fires mid-request (default 60000)
74
- * @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)
75
91
  */
76
92
 
77
93
  /**
@@ -116,7 +132,7 @@ const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
116
132
  */
117
133
 
118
134
  /**
119
- * 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
120
136
  * flags park for a human decision instead of forwarding.
121
137
  *
122
138
  * @param {ProxyOptions} opts
@@ -134,7 +150,7 @@ export function createProxy(opts) {
134
150
  upstreamCa = null, hold = null, gateFor = null, allowLocal = [], floor = null, labels = null,
135
151
  upstreamTimeoutMs = 120000, clientIdleMs = 60000,
136
152
  unsafeTestOnly = null, secrets = [],
137
- redact = (e) => e } = opts ?? {};
153
+ redact = (e) => e, hosts = {} } = opts ?? {};
138
154
  const { allowLoopback = false, resolveUpstream = null } = unsafeTestOnly ?? {};
139
155
  const gate = {
140
156
  allowLoopback, resolveUpstream: resolveUpstream ?? undefined,
@@ -150,6 +166,13 @@ export function createProxy(opts) {
150
166
  const builtinModels = modelTools(labels?.tools, []);
151
167
  const modelEndpoints = modelList([...allowLocal]);
152
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+$/, ''))]);
153
176
  if (!logFile) throw new Error('createProxy: logFile is required');
154
177
  if (typeof runtime !== 'string' || !runtime) throw new Error('createProxy: runtime is required');
155
178
  // One live proxy per runtime, enforced here: claimed before the hold
@@ -226,8 +249,10 @@ export function createProxy(opts) {
226
249
  meta['reason'] = cut(meta['reason'], 200);
227
250
  return meta;
228
251
  };
229
- /** @param {Record<string, unknown>} o */
230
- async function writeLog(o) {
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;
231
256
  const agent = typeof o['agent'] === 'string' ? o['agent'] : null;
232
257
  // Never build a gate from here: a built one, else the sbx gate.
233
258
  const entry = agent ? gates.get(agent) : undefined;
@@ -277,7 +302,9 @@ export function createProxy(opts) {
277
302
  // The one writer of a proxied HTTP error: logs it, answers it.
278
303
  function denyRes(cres, code, note) {
279
304
  const sock = cres.socket;
280
- log({ ev: 'deny', agent: agentOf(sock), code, note });
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 } : {}) });
281
308
  try {
282
309
  if (!cres.headersSent && !sock.destroyed) {
283
310
  cres.writeHead(code, { 'content-type': 'text/plain', connection: 'close' });
@@ -444,7 +471,7 @@ export function createProxy(opts) {
444
471
  // A parked request's pending ask ends here: handleRequest, awaiting
445
472
  // its gate, then forwards or refuses.
446
473
  onApprove: (h) => h.finish({ decision: 'allow' }),
447
- onDeny: (h, reason, answered) => h.finish({ decision: 'deny', reason, answered }),
474
+ onDeny: (h, reason, answered, timedOut) => h.finish({ decision: 'deny', reason, answered, timedOut }),
448
475
  }) : null;
449
476
  } catch (e) {
450
477
  releaseClaim();
@@ -500,6 +527,82 @@ export function createProxy(opts) {
500
527
  */
501
528
  const keyAsks = new Map();
502
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
+
503
606
  /**
504
607
  * The model key of a header: `x-api-key`, or `Authorization` without a leading `Bearer `.
505
608
  * @param {Record<string, string | string[] | undefined>} headers @param {string} name @returns {string}
@@ -564,6 +667,7 @@ export function createProxy(opts) {
564
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
565
668
  * @property {string|null} askRule the rule the human channel was asked about (null: not asked)
566
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)
567
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
568
672
  */
569
673
 
@@ -603,20 +707,21 @@ export function createProxy(opts) {
603
707
  let dead = false;
604
708
  /** @type {import('node:fs').WriteStream|null} */
605
709
  let ws = null;
606
- /** @param {{ decision: 'allow' | 'deny', reason?: string, answered?: boolean }} d */
710
+ /** @param {{ decision: 'allow' | 'deny', reason?: string, answered?: boolean, timedOut?: boolean }} d */
607
711
  const finish = (d) => {
608
712
  if (settled) return;
609
713
  settled = true;
610
714
  ctx.endAsk = null;
611
- const { answered, ...rest } = d; // the one place `answered` is set: present only when true
715
+ const { answered, timedOut, ...rest } = d; // the one place `answered` and `timedOut` are set: present only when true
612
716
  ctx.answered = answered === true;
717
+ ctx.timedOut = timedOut === true;
613
718
  resolve(ctx.answered ? d : rest);
614
719
  };
615
- /** @param {string} reason @param {number} [status] @param {boolean} [answered] the hold timeout ended it */
616
- const refuse = (reason, status, answered) => {
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) => {
617
722
  if (settled) return; // a late failure must not rewrite the settled deny's status
618
723
  if (status) ctx.status = status;
619
- finish({ decision: 'deny', reason, answered });
724
+ finish({ decision: 'deny', reason, answered, timedOut });
620
725
  };
621
726
  const abort = () => {
622
727
  if (dead) return;
@@ -635,7 +740,7 @@ export function createProxy(opts) {
635
740
  if (!sock || sock.destroyed) { refuse('client gone'); return; }
636
741
  const slot = queue.reserve(agent, {
637
742
  onReady: () => stream(),
638
- onExpire: (why, answered) => { abort(); refuse(why, undefined, answered); },
743
+ onExpire: (why, answered, timedOut) => { abort(); refuse(why, undefined, answered, timedOut); },
639
744
  });
640
745
  if (slot.state === 'full') { ctx.freeWork(); refuse('hold queue full', 429); return; }
641
746
  ctx.endAsk = (why) => fail(why);
@@ -720,26 +825,11 @@ export function createProxy(opts) {
720
825
  async function handleRequest(creq, cres) {
721
826
  const sock = creq.socket;
722
827
  const agent = agentOf(sock);
723
- const secure = sock[SECURE] === true;
724
- const target = creq.url || '';
725
- let url;
726
- try {
727
- if (/^https?:\/\//i.test(target)) url = new URL(target);
728
- else {
729
- const host = creq.headers.host;
730
- if (!host) throw new Error('no host');
731
- url = new URL(`${secure ? 'https' : 'http'}://${host}${target}`);
732
- }
733
- } catch { denyRes(cres, 400, 'bad request target'); return; }
828
+ const url = targetUrl(creq);
829
+ if (!url) { denyRes(cres, 400, 'bad request target'); return; }
734
830
  const method = creq.method;
735
831
  if (!method) { denyRes(cres, 400, 'bad request method'); return; }
736
832
  const urlStr = url.toString();
737
- const verdict = await checkUpstream(url.hostname, gate, portOf(url));
738
- if (!verdict.ok) {
739
- try { creq.resume(); } catch {}
740
- denyRes(cres, 403, verdict.reason);
741
- return;
742
- }
743
833
  // The request's one id: the audit lines of its secret swap, its body and
744
834
  // its gate decision all carry it.
745
835
  const rid = `r${++ridN}`;
@@ -772,6 +862,69 @@ export function createProxy(opts) {
772
862
  denyRes(cres, 403, 'denied: secret.url');
773
863
  return;
774
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
+ }
775
928
  /** The headers to forward: the real values in, one audit line per swap. @param {Record<string, string | string[] | undefined>} headers */
776
929
  const withSecrets = (headers) => {
777
930
  if (!found.length) return headers;
@@ -785,7 +938,6 @@ export function createProxy(opts) {
785
938
  // flowing mode and starve whoever reads it next. The tee sees every body
786
939
  // byte once, whatever path reads it, and feeds the ask (a masked
787
940
  // 4 KB preview) and the audit's `body` fact (byte count and SHA-256).
788
- creq.pause();
789
941
  const tee = makeTee();
790
942
  creq.on('data', (c) => tee.push(c));
791
943
  // `end` fires once the whole body was read, whichever path read it (also
@@ -870,7 +1022,7 @@ export function createProxy(opts) {
870
1022
  /** @type {RequestCtx} */
871
1023
  const ctx = { agent, method, url: urlStr, headers: { ...creq.headers }, creq, cres, tee,
872
1024
  hasBody, chunks: [], over: false, freeWork, asked: false, status: null, heldId: null,
873
- endAsk: null, decodedHead: null, effect: null, keyLast4: unknownKey?.last4 ?? '', modelKey: unknownKey ? (unknownKey.hash ? 'other' : 'none') : '', askRule: null, answered: false };
1025
+ endAsk: null, decodedHead: null, effect: null, keyLast4: unknownKey?.last4 ?? '', modelKey: unknownKey ? (unknownKey.hash ? 'other' : 'none') : '', askRule: null, answered: false, timedOut: false };
874
1026
  let cardLike = false;
875
1027
  if (hasBody) {
876
1028
  if (await readWorkBody(ctx)) return;
@@ -1052,8 +1204,7 @@ export function createProxy(opts) {
1052
1204
  // listeners node would forward the upgrade as a GET, or close the socket with no reason.
1053
1205
  server.on('upgrade', (creq, sock) => {
1054
1206
  const t = creq.url || '';
1055
- const host = creq.headers.host ?? '';
1056
- denyRaw(sock, 403, 'denied: upgrade', /^https?:\/\//i.test(t) ? t : `${sock[SECURE] === true ? 'https' : 'http'}://${host}${t}`);
1207
+ denyRaw(sock, 403, 'denied: upgrade', targetUrl(creq)?.toString() ?? t);
1057
1208
  });
1058
1209
  server.on('connect', (creq, sock) => { denyRaw(sock, 403, 'denied: connect', creq.url || ''); });
1059
1210
 
@@ -1107,11 +1258,21 @@ export function createProxy(opts) {
1107
1258
  }
1108
1259
  // Deny the tunnel itself: no cert is minted for a walled destination,
1109
1260
  // and the inner request is checked again on arrival anyway.
1110
- const verdict = await checkUpstream(host, gate, portNum);
1111
- if (!verdict.ok) {
1112
- denyRaw(sock, 403, verdict.reason);
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));
1113
1267
  return;
1114
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
+ }
1115
1276
  if (closed || sock.destroyed) return;
1116
1277
  try { sock.write('HTTP/1.1 200 Connection established\r\n\r\n'); }
1117
1278
  catch { return; }
@@ -1279,6 +1440,8 @@ export function createProxy(opts) {
1279
1440
  addAgent,
1280
1441
  removeAgent,
1281
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() }),
1282
1445
  get caFile() { return path.join(certDir, 'ca.pem'); },
1283
1446
  };
1284
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), and the runtime dir addressing it
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 } : {}), unsafeTestOnly, secrets: loaded,
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
  }
package/types/config.d.ts CHANGED
@@ -9,7 +9,7 @@ export function configPath(env?: NodeJS.ProcessEnv): string;
9
9
  * Read the config file over the defaults. No file means defaults.
10
10
  *
11
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, floor?: { pay?: string[], send?: string[] }, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
12
+ * @returns {{ mode: string, holdTimeoutSec?: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, floor?: { pay?: string[], send?: string[] }, hosts?: { allow?: string[], deny?: string[], unknown?: 'ask'|'deny' }, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
13
13
  * @throws {Error} naming the file (and the key) on invalid JSON, an unknown key or a bad value
14
14
  */
15
15
  export function loadConfig(env?: NodeJS.ProcessEnv): {
@@ -23,6 +23,11 @@ export function loadConfig(env?: NodeJS.ProcessEnv): {
23
23
  pay?: string[];
24
24
  send?: string[];
25
25
  };
26
+ hosts?: {
27
+ allow?: string[];
28
+ deny?: string[];
29
+ unknown?: "ask" | "deny";
30
+ };
26
31
  env?: {
27
32
  pass?: string[];
28
33
  set?: Record<string, string>;
@@ -40,7 +45,7 @@ export function loadConfig(env?: NodeJS.ProcessEnv): {
40
45
  * @param {string} [flags.mode] `--mode`
41
46
  * @param {string} [flags.hold] `--hold` (`"never"` or a positive integer of seconds, as typed)
42
47
  * @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
43
- * @returns {{ mode: string, holdTimeoutSec?: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, floor?: { pay?: string[], send?: string[] }, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
48
+ * @returns {{ mode: string, holdTimeoutSec?: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, floor?: { pay?: string[], send?: string[] }, hosts?: { allow?: string[], deny?: string[], unknown?: 'ask'|'deny' }, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
44
49
  * @throws {Error} as {@link loadConfig}
45
50
  */
46
51
  export function resolveConfig(flags?: {
@@ -57,6 +62,11 @@ export function resolveConfig(flags?: {
57
62
  pay?: string[];
58
63
  send?: string[];
59
64
  };
65
+ hosts?: {
66
+ allow?: string[];
67
+ deny?: string[];
68
+ unknown?: "ask" | "deny";
69
+ };
60
70
  env?: {
61
71
  pass?: string[];
62
72
  set?: Record<string, string>;
package/types/holds.d.ts CHANGED
@@ -110,8 +110,8 @@ export function normalizeDecision(input: {
110
110
  * @param {number} [opts.pollMs] answer poll interval in ms for the default file checkpoint (default 250, PRD Q9)
111
111
  * @param {OnEvent|null} [opts.onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon
112
112
  * @param {(entry: object) => void} opts.onApprove forward the parked request upstream
113
- * @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)
114
- * @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
113
+ * @param {(entry: object, reason: string, answered: boolean, timedOut: 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); `timedOut`: the hold timeout ended it (so `answered && !timedOut` is a person's answer)
114
+ * @returns {{ add: (entry: object) => string|null, dropBody: (id: string) => void, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string, answered?: boolean, timedOut?: 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
115
115
  */
116
116
  export function createHolds({ log, timeoutMs, maxBody, runtime, onAsk, pollMs, onEvent, onApprove, onDeny }: {
117
117
  log: (o: Record<string, unknown>) => void;
@@ -122,13 +122,13 @@ export function createHolds({ log, timeoutMs, maxBody, runtime, onAsk, pollMs, o
122
122
  pollMs?: number | undefined;
123
123
  onEvent?: OnEvent | null | undefined;
124
124
  onApprove: (entry: object) => void;
125
- onDeny: (entry: object, reason: string, answered: boolean) => void;
125
+ onDeny: (entry: object, reason: string, answered: boolean, timedOut: boolean) => void;
126
126
  }): {
127
127
  add: (entry: object) => string | null;
128
128
  dropBody: (id: string) => void;
129
129
  reserve: (agent: string, cbs: {
130
130
  onReady: () => void;
131
- onExpire: (reason: string, answered?: boolean) => void;
131
+ onExpire: (reason: string, answered?: boolean, timedOut?: boolean) => void;
132
132
  }) => {
133
133
  state: "now" | "queued" | "full";
134
134
  id: string;
package/types/lists.d.ts CHANGED
@@ -35,5 +35,6 @@ export function floorList({ pay, send }?: {
35
35
  entry: string;
36
36
  } | null;
37
37
  };
38
+ export function stripDot(host: string): string;
38
39
  export function isEndpoint(e: unknown): boolean;
39
40
  import { matcherFrom } from 'rwxmap/match';
package/types/policy.d.ts CHANGED
@@ -78,6 +78,8 @@ export function gateFor({ agent, mode, auditPath, humanChannel, tools }: {
78
78
  }): Promise<Gate>;
79
79
  /** The mode names, in the order the CLI and config list them. */
80
80
  export const MODES: string[];
81
+ /** Hosts of the built-in model endpoints: never a first-contact host ask (M14). */
82
+ export const MODEL_HOSTS: Set<string>;
81
83
  /** The matcher used when no label files are loaded: every request is request-only. */
82
84
  export const emptyMatcher: {
83
85
  match: (method: string, url: string) => import("rwxmap/match").MatchResult;
package/types/prompt.d.ts CHANGED
@@ -8,6 +8,15 @@
8
8
  * @returns {string[]} zero or more lines
9
9
  */
10
10
  export function effectLines(effect: AskRecord["effect"], color: boolean): string[];
11
+ /**
12
+ * The URL of an ask, sanitized. For a first-contact host ask (`flags.newHost`) everything after the
13
+ * scheme (userinfo, host, path and query) has card numbers masked, then is cut to 200 characters and the
14
+ * full length is added, so a long URL is visible but bounded. The question's header line shows the true host.
15
+ *
16
+ * @param {AskRecord} ask the parked request
17
+ * @returns {string} the URL text, safe for a terminal
18
+ */
19
+ export function askUrl(ask: AskRecord): string;
11
20
  /**
12
21
  * The ` floor=<kind> entry=<entry>` tail of a one-line ask (`sbx pending`, the non-terminal `ask` line); empty without a floor hit.
13
22
  *
package/types/proxy.d.ts CHANGED
@@ -10,6 +10,7 @@
10
10
  * @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
11
11
  * @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
12
12
  * @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.
13
+ * @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.
13
14
  * @property {HoldOptions} [hold] hold queue config (deadline, caps, ask seam)
14
15
  * @property {number} [upstreamTimeoutMs] give up on an upstream response after this (default 120000)
15
16
  * @property {object} [unsafeTestOnly] TEST-ONLY escape hatch: everything under
@@ -21,7 +22,7 @@
21
22
  * DNS stub: replaces the wall's resolver so rebinding is testable. Production omits it.
22
23
  * @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.
23
24
  * @property {number} [clientIdleMs] kill a client tunnel idle this long; never fires mid-request (default 60000)
24
- * @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)
25
+ * @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)
25
26
  */
26
27
  /**
27
28
  * Anything with bareguard's `check`: a `Gate`, or a plain object for tests. An
@@ -61,7 +62,7 @@
61
62
  * @typedef {ReturnType<typeof createProxy>} Proxy
62
63
  */
63
64
  /**
64
- * 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
65
+ * 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
65
66
  * flags park for a human decision instead of forwarding.
66
67
  *
67
68
  * @param {ProxyOptions} opts
@@ -82,6 +83,11 @@ export function createProxy(opts: ProxyOptions): {
82
83
  addAgent: (name: any) => string;
83
84
  removeAgent: (name: any) => void;
84
85
  pending: () => import("./holds.js").HeldRequest[];
86
+ /** M14: hosts a person allowed this run, and hosts refused by `unknown: 'deny'`; each sorted and unique. @returns {{ allowed: string[], refused: string[] }} */
87
+ hostsReport: () => {
88
+ allowed: string[];
89
+ refused: string[];
90
+ };
85
91
  readonly caFile: string;
86
92
  };
87
93
  /**
@@ -137,6 +143,14 @@ export type ProxyOptions = {
137
143
  pay?: string[];
138
144
  send?: string[];
139
145
  } | undefined;
146
+ /**
147
+ * 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.
148
+ */
149
+ hosts?: {
150
+ allow?: string[];
151
+ deny?: string[];
152
+ unknown?: "ask" | "deny" | "allow";
153
+ } | undefined;
140
154
  /**
141
155
  * hold queue config (deadline, caps, ask seam)
142
156
  */
@@ -170,7 +184,7 @@ export type ProxyOptions = {
170
184
  */
171
185
  clientIdleMs?: number | undefined;
172
186
  /**
173
- * log redaction hook, applied after built-in secret scrubbing; its result becomes the `meta` of an `annotate` line (default: identity)
187
+ * 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)
174
188
  */
175
189
  redact?: ((entry: Record<string, unknown>) => Record<string, unknown>) | undefined;
176
190
  };
package/types/run.d.ts CHANGED
@@ -30,6 +30,7 @@
30
30
  * @property {{ matcher: any, tools: Record<string, any>, dirs?: string[] }} [labels] the loaded label files (`loadLabels`); their folders are masked from the sandbox
31
31
  * @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)
32
32
  * @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`)
33
+ * @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`)
33
34
  * @property {object} [unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`): everything under it weakens the sandbox wall
34
35
  * @property {NodeJS.WritableStream} [stdout] where the agent's stdout goes (default process.stdout)
35
36
  * @property {NodeJS.WritableStream} [stderr] where the agent's stderr goes (default process.stderr)
@@ -54,6 +55,7 @@
54
55
  * @param {{ matcher: any, tools: Record<string, any>, dirs?: string[] }|null} [opts.labels] the loaded label files (`loadLabels`); their folders are masked from the sandbox
55
56
  * @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)
56
57
  * @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`)
58
+ * @param {{ allow?: string[], deny?: string[], unknown?: 'ask'|'deny' }|null} [opts.hosts] the config `hosts` key (M14); see {@link RunOptions}
57
59
  * @param {object|null} [opts.unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`)
58
60
  * @param {NodeJS.WritableStream|null} [opts.stdout] where the agent's stdout goes (default process.stdout)
59
61
  * @param {NodeJS.WritableStream|null} [opts.stderr] where the agent's stderr goes (default process.stderr)
@@ -61,14 +63,14 @@
61
63
  * @param {{ pass?: string[], set?: Record<string, string> }|null} [opts.env] the sandbox's environment (M5), the config `env` shape; see {@link RunOptions}
62
64
  * @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
63
65
  * @param {string[]} [opts.overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
64
- * @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), and the runtime dir addressing it
66
+ * @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)
65
67
  * @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).
66
68
  * @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.
67
69
  * @example
68
70
  * import { run } from "barebox";
69
71
  * const { exit, asks, audit } = await run({ proj: "/tmp/proj", command: ["bash", "-c", "echo hi"] });
70
72
  */
71
- export function run({ proj, command, mode, onAsk, onEvent, runtime, agent, timeoutMs, heldBodyMaxBytes, allowLocal, floor, labels, unsafeTestOnly, stdout, stderr, overlay, overlayIgnore, secrets, env }: {
73
+ export function run({ proj, command, mode, onAsk, onEvent, runtime, agent, timeoutMs, heldBodyMaxBytes, allowLocal, floor, hosts, labels, unsafeTestOnly, stdout, stderr, overlay, overlayIgnore, secrets, env }: {
72
74
  proj: string;
73
75
  command: string[];
74
76
  mode?: string | undefined;
@@ -88,6 +90,11 @@ export function run({ proj, command, mode, onAsk, onEvent, runtime, agent, timeo
88
90
  pay?: string[];
89
91
  send?: string[];
90
92
  } | null | undefined;
93
+ hosts?: {
94
+ allow?: string[];
95
+ deny?: string[];
96
+ unknown?: "ask" | "deny";
97
+ } | null | undefined;
91
98
  unsafeTestOnly?: object | null;
92
99
  stdout?: NodeJS.WritableStream | null | undefined;
93
100
  stderr?: NodeJS.WritableStream | null | undefined;
@@ -108,6 +115,10 @@ export function run({ proj, command, mode, onAsk, onEvent, runtime, agent, timeo
108
115
  audit: string;
109
116
  diff: import("./overlay.js").OverlayChange[];
110
117
  runtime: string;
118
+ hosts: {
119
+ allowed: string[];
120
+ refused: string[];
121
+ };
111
122
  }>;
112
123
  /**
113
124
  * A collected ask record: the parked ask plus how it was decided.
@@ -217,6 +228,14 @@ export type RunOptions = {
217
228
  pay?: string[];
218
229
  send?: string[];
219
230
  } | undefined;
231
+ /**
232
+ * 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`)
233
+ */
234
+ hosts?: {
235
+ allow?: string[];
236
+ deny?: string[];
237
+ unknown?: "ask" | "deny";
238
+ } | undefined;
220
239
  /**
221
240
  * TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`): everything under it weakens the sandbox wall
222
241
  */