barebox 0.14.0 → 0.16.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 +25 -0
- package/README.md +4 -3
- package/barebox.context.md +16 -3
- package/package.json +1 -1
- package/primitives.json +1 -1
- package/src/cli.js +27 -12
- package/src/config.js +85 -9
- package/src/holds.js +10 -10
- package/src/lists.js +1 -1
- package/src/policy.js +5 -1
- package/src/prompt.js +27 -4
- package/src/proxy.js +210 -46
- package/src/run.js +10 -4
- package/types/config.d.ts +22 -23
- package/types/holds.d.ts +4 -4
- package/types/lists.d.ts +1 -0
- package/types/policy.d.ts +2 -0
- package/types/prompt.d.ts +11 -1
- package/types/proxy.d.ts +17 -3
- package/types/run.d.ts +21 -2
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,31 @@ 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.16.0] - 2026-12-01
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- `profiles` config key (`{ "<name>": { mode?, hosts?, secrets? } }`) and `sbx run --profile <name>`: one config file gives each sandbox or group its own policy, so two runs can sit side by side with different rules. A profile's `mode`, `hosts.allow`, `hosts.unknown` and whole `secrets` map replace the top level's; `hosts.deny` is the union, so a profile can add a denied host but never remove one; `--mode` beats the profile's mode; `floor` stays top-level and applies to every profile. Errors are loud: an unknown `--profile` exits 2 and lists the defined ones, and a bad profile stops every run, even one that picks another. `sbx run` prints `profile <name> (mode <mode>)` at the start, and an ask names the profile (a `profile=<name>` tail, a `profile` field with `--json`, `(profile <name>)` in the terminal question). A `fromEnv` secret is now checked only when the run's effective secrets use it.
|
|
12
|
+
|
|
13
|
+
### Fixed
|
|
14
|
+
|
|
15
|
+
- A request refused at the CONNECT step, mostly an HTTPS host refused before any path is sent, now has `method: "CONNECT"` and its `host:port` target on its audit `deny` line. 0.15.0 said every refused request's deny line names its method and URL, but these lines named neither; only the `host` line next to them named the host. Upgrade and inner `CONNECT` refusals now name their method too.
|
|
16
|
+
|
|
17
|
+
## [0.15.0] - 2026-12-01
|
|
18
|
+
|
|
19
|
+
### Added
|
|
20
|
+
|
|
21
|
+
- `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 }`.
|
|
22
|
+
|
|
23
|
+
### Changed
|
|
24
|
+
|
|
25
|
+
- `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`.
|
|
26
|
+
|
|
27
|
+
### Security
|
|
28
|
+
|
|
29
|
+
- 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.
|
|
30
|
+
- 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.
|
|
31
|
+
|
|
7
32
|
## [0.14.0] - 2026-11-30
|
|
8
33
|
|
|
9
34
|
### Security
|
package/README.md
CHANGED
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
|
|
35
35
|
```
|
|
36
36
|
npm install -g barebox
|
|
37
|
-
sbx run -- claude
|
|
37
|
+
sbx run -- claude -p "your task" # auto mode: reads pass, sends ask (the agent gets no terminal, so -p)
|
|
38
38
|
sbx run --mode ask --overlay -- node agent.js
|
|
39
39
|
sbx diff && sbx commit # keep the file changes, or: sbx rollback
|
|
40
40
|
```
|
|
@@ -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
|
|
package/barebox.context.md
CHANGED
|
@@ -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,17 +113,18 @@ 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
|
```
|
|
120
125
|
|
|
121
126
|
```bash
|
|
122
|
-
sbx run [--name <n>] [--mode ask|auto|trust] [--hold <seconds|never>] [--json] [--overlay] -- <cmd> [...]
|
|
127
|
+
sbx run [--name <n>] [--mode ask|auto|trust] [--profile <name>] [--hold <seconds|never>] [--json] [--overlay] -- <cmd> [...]
|
|
123
128
|
```
|
|
124
129
|
|
|
125
130
|
`sbx run` uses the current directory as the project and `--name`'s runtime or
|
|
@@ -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". `profiles` (`{ "<name>": { mode?, hosts?, secrets? } }`, names as for `--name`) lets `sbx run --profile <name>` lay one set over the top level for that run: its `mode`, `hosts.allow`, `hosts.unknown` and whole `secrets` map replace the top level's, `hosts.deny` is the union (a profile can add a deny, never remove one), and `--mode` beats both; `floor` and every other key stay top-level. A bad profile stops every `sbx run`; an unknown `--profile` exits 2 and lists the defined ones. `sbx run` prints `profile <name> (mode <mode>)` before the `hosts:` line, and its ask lines carry the profile (` profile=<name>`, a `profile` field with `--json`). The library does not read profiles.
|
|
139
144
|
|
|
140
145
|
## Modes and the gate
|
|
141
146
|
|
|
@@ -275,6 +280,14 @@ 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. A
|
|
286
|
+
refusal at the CONNECT step (an HTTPS host refused before any path is sent) has
|
|
287
|
+
`method: "CONNECT"` and `url` set to the `host:port` target. A request head over 64 KB is
|
|
288
|
+
refused before its first line is read, so its line has no method or url.
|
|
289
|
+
- In barebox's own lines, `url` (in `meta` and in `where`) has userinfo masked whole (`http://***@host/...`) and card
|
|
290
|
+
numbers masked to their last 4 digits. bareguard's gate lines keep the URL as sent.
|
|
278
291
|
- Lines for an agent whose gate is not built, and every line when `gateFor` is
|
|
279
292
|
omitted, are written by a runtime-level `sbx` gate (`meta.agent` names the
|
|
280
293
|
agent).
|
package/package.json
CHANGED
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
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
// `--name <n>` names the sandbox (agent name + runtime dir, runtime.js namedRuntime) and every
|
|
14
14
|
// command takes `--name` instead of SBX_RUNTIME (both together: exit 2).
|
|
15
15
|
//
|
|
16
|
-
// sbx run [--mode ask|auto|trust] [--hold <seconds|never>] [--name <n>] [--json] [--overlay] -- <cmd> [...]
|
|
16
|
+
// sbx run [--mode ask|auto|trust] [--profile <name>] [--hold <seconds|never>] [--name <n>] [--json] [--overlay] -- <cmd> [...]
|
|
17
17
|
// Runs one sandboxed agent start-to-finish in this process (project = cwd).
|
|
18
18
|
// The runtime is SBX_RUNTIME when set, else a short temp dir (printed to
|
|
19
19
|
// stderr so a second terminal can approve from it). With --json, stdout
|
|
@@ -38,14 +38,14 @@ 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';
|
|
45
45
|
|
|
46
46
|
// Seconds a held request waits when no one is at a terminal and neither --hold nor holdTimeoutSec is set.
|
|
47
47
|
const HOLD_NO_TERMINAL_SEC = 180;
|
|
48
|
-
const USAGE = 'usage: sbx [--help] | run [--mode ask|auto|trust] [--hold <seconds|never>] [--name <n>] [--json] [--overlay] -- <cmd> [...] | pending|diff|rollback [--name <n>] | approve <id> [--name <n>] | deny <id> [reason] [--name <n>] | commit [--name <n>] [--skip-conflicts] (--name replaces SBX_RUNTIME; --agent stays for diff/commit/rollback)';
|
|
48
|
+
const USAGE = 'usage: sbx [--help] | run [--mode ask|auto|trust] [--profile <name>] [--hold <seconds|never>] [--name <n>] [--json] [--overlay] -- <cmd> [...] | pending|diff|rollback [--name <n>] | approve <id> [--name <n>] | deny <id> [reason] [--name <n>] | commit [--name <n>] [--skip-conflicts] (--name replaces SBX_RUNTIME; --agent stays for diff/commit/rollback)';
|
|
49
49
|
|
|
50
50
|
/** Hold ids the CLI accepts: `h<n>` only. Anything else is a usage error, never a path. */
|
|
51
51
|
const HOLD_ID_RE = /^h\d+$/;
|
|
@@ -199,7 +199,7 @@ async function run(args) {
|
|
|
199
199
|
if (sep < 0) usage();
|
|
200
200
|
const flags = args.slice(0, sep);
|
|
201
201
|
const command = args.slice(sep + 1);
|
|
202
|
-
/** @type {{ name?: string, mode?: string, hold?: string, json?: boolean, overlay?: boolean }} */
|
|
202
|
+
/** @type {{ name?: string, mode?: string, profile?: string, hold?: string, json?: boolean, overlay?: boolean }} */
|
|
203
203
|
let values;
|
|
204
204
|
try {
|
|
205
205
|
({ values } = parseArgs({
|
|
@@ -207,6 +207,7 @@ async function run(args) {
|
|
|
207
207
|
options: {
|
|
208
208
|
name: { type: 'string' },
|
|
209
209
|
mode: { type: 'string' },
|
|
210
|
+
profile: { type: 'string' },
|
|
210
211
|
hold: { type: 'string' },
|
|
211
212
|
json: { type: 'boolean' },
|
|
212
213
|
overlay: { type: 'boolean' },
|
|
@@ -218,10 +219,10 @@ async function run(args) {
|
|
|
218
219
|
usage();
|
|
219
220
|
}
|
|
220
221
|
if (values.mode !== undefined && !MODES.includes(values.mode)) usage();
|
|
221
|
-
/** @type {
|
|
222
|
+
/** @type {import('./config.js').Settings} */
|
|
222
223
|
let cfg;
|
|
223
224
|
try {
|
|
224
|
-
cfg = resolveConfig({ mode: values.mode, hold: values.hold });
|
|
225
|
+
cfg = resolveConfig({ mode: values.mode, profile: values.profile, hold: values.hold });
|
|
225
226
|
} catch (e) {
|
|
226
227
|
err(e instanceof Error ? e.message : String(e));
|
|
227
228
|
process.exit(2);
|
|
@@ -267,11 +268,12 @@ async function run(args) {
|
|
|
267
268
|
})
|
|
268
269
|
: null;
|
|
269
270
|
const prompted = new Set(); // holds the prompt showed: their answer is shown there too
|
|
270
|
-
const emitAsk = (
|
|
271
|
+
const emitAsk = (rec) => {
|
|
272
|
+
const h = values.profile !== undefined ? { ...rec, profile: values.profile } : rec;
|
|
271
273
|
if (prompt?.ask(h)) { prompted.add(h.id); return; }
|
|
272
|
-
const c = clean(h, ['id', 'agent', 'method', 'url', 'rule', 'bodyPreview']);
|
|
274
|
+
const c = clean(h, ['id', 'agent', 'method', 'url', 'rule', 'bodyPreview', 'profile']);
|
|
273
275
|
if (json) out(JSON.stringify({ ev: 'ask', ...c }));
|
|
274
|
-
else out(`ask ${c.id} ${c.agent} ${c.method} ${
|
|
276
|
+
else out(`ask ${c.id} ${c.agent} ${c.method} ${askUrl(h)} rule=${c.rule}${floorTail(h)}${keyTail(h)}${c.profile !== undefined ? ` profile=${c.profile}` : ''}`);
|
|
275
277
|
};
|
|
276
278
|
const emitDecided = (e) => {
|
|
277
279
|
if (!json && prompted.delete(e.id)) return;
|
|
@@ -286,7 +288,13 @@ async function run(args) {
|
|
|
286
288
|
} else err(name !== undefined
|
|
287
289
|
? `sandbox ${name} (answer from another terminal: sbx approve --name ${name} <id>)`
|
|
288
290
|
: `runtime ${runtime} (answer with: SBX_RUNTIME=${shellQuote(runtime)} sbx approve <id>)`);
|
|
289
|
-
|
|
291
|
+
if (values.profile !== undefined) err(`profile ${safe(values.profile)} (mode ${mode})`);
|
|
292
|
+
// M14: hosts on neither list ask when a person is here, else are refused; `trust` lets them through.
|
|
293
|
+
const hostsUnknown = cfg.hosts?.unknown ?? (interactive ? 'ask' : 'deny');
|
|
294
|
+
err(`hosts: ${cfg.hosts?.allow?.length ?? 0} allowed, ${cfg.hosts?.deny?.length ?? 0} denied in config; other hosts ${
|
|
295
|
+
mode === 'trust' ? 'pass (trust)' : hostsUnknown === 'ask' ? 'ask on first contact'
|
|
296
|
+
: cfg.hosts?.unknown ? 'are refused' : 'are refused (no terminal)'}`);
|
|
297
|
+
/** @type {{ exit: number, diff: { path: string }[], hosts: { allowed: string[], refused: string[] } } | null} */
|
|
290
298
|
let result = null;
|
|
291
299
|
try {
|
|
292
300
|
// SBX_OVERLAY_IGNORE extends the M4 ignore list (Q3) as comma names.
|
|
@@ -295,7 +303,7 @@ async function run(args) {
|
|
|
295
303
|
result = await sandboxRun({
|
|
296
304
|
runtime, proj: process.cwd(), command, mode, timeoutMs,
|
|
297
305
|
...(name !== undefined ? { agent: name } : {}),
|
|
298
|
-
allowLocal: cfg.localLlm, floor: cfg.floor, labels, secrets: cfg.secrets, env: cfg.env,
|
|
306
|
+
allowLocal: cfg.localLlm, floor: cfg.floor, hosts: { ...cfg.hosts, unknown: hostsUnknown }, labels, secrets: cfg.secrets, env: cfg.env,
|
|
299
307
|
...(cfg.heldBodyMaxMB ? { heldBodyMaxBytes: cfg.heldBodyMaxMB * 1048576 } : {}),
|
|
300
308
|
unsafeTestOnly: { allowLoopback: process.env.SBX_UNSAFE_TEST_ALLOW_LOOPBACK === '1' },
|
|
301
309
|
overlay,
|
|
@@ -317,6 +325,13 @@ async function run(args) {
|
|
|
317
325
|
prompt?.close();
|
|
318
326
|
if (json) out(JSON.stringify({ ev: 'done', exit: result.exit }));
|
|
319
327
|
else out(`done exit ${result.exit}`);
|
|
328
|
+
const { allowed, refused } = result.hosts;
|
|
329
|
+
if (json) {
|
|
330
|
+
if (allowed.length || refused.length) out(JSON.stringify({ ev: 'hosts', allowed, refused }));
|
|
331
|
+
} else {
|
|
332
|
+
if (allowed.length) out(`hosts allowed this run (add to hosts.allow): ${JSON.stringify(allowed)}`);
|
|
333
|
+
if (refused.length) out(`hosts refused (not in hosts.allow): ${JSON.stringify(refused)}`);
|
|
334
|
+
}
|
|
320
335
|
if (overlay) {
|
|
321
336
|
const n = result.diff.length;
|
|
322
337
|
err(n
|
|
@@ -426,7 +441,7 @@ async function pending(rest) {
|
|
|
426
441
|
// Agent-controlled bytes (URL, rule, body preview): sanitized before
|
|
427
442
|
// they reach the approver's terminal (see `safe`).
|
|
428
443
|
const body = safe(h.bodyPreview).replace(/\s+/g, ' ').slice(0, 200);
|
|
429
|
-
out(`${safe(h.id)} ${safe(h.agent)} ${safe(h.method)} ${
|
|
444
|
+
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
445
|
for (const line of effectLines(h.effect, false)) out(line);
|
|
431
446
|
}
|
|
432
447
|
process.exit(0);
|
package/src/config.js
CHANGED
|
@@ -6,7 +6,9 @@ import fs from 'node:fs';
|
|
|
6
6
|
import os from 'node:os';
|
|
7
7
|
import path from 'node:path';
|
|
8
8
|
import { MODES } from './policy.js';
|
|
9
|
+
import { AGENT_RE } from './runtime.js';
|
|
9
10
|
import { floorList } from './lists.js';
|
|
11
|
+
import { hostMatcher } from 'bareguard';
|
|
10
12
|
|
|
11
13
|
const DEFAULTS = { mode: 'auto', localLlm: [], labels: [], tenants: {} };
|
|
12
14
|
|
|
@@ -80,6 +82,41 @@ const checkFloor = (/** @type {any} */ v) => {
|
|
|
80
82
|
return null;
|
|
81
83
|
};
|
|
82
84
|
|
|
85
|
+
/** @param {unknown} v @returns {string|null} the error for a `hosts` value, or null */
|
|
86
|
+
const checkHosts = (/** @type {any} */ v) => {
|
|
87
|
+
if (!isObj(v)) return 'must be an object of { allow?, deny?, unknown? }';
|
|
88
|
+
for (const [k, list] of Object.entries(v)) {
|
|
89
|
+
if (k === 'unknown') {
|
|
90
|
+
if (list !== 'ask' && list !== 'deny') return 'hosts.unknown must be "ask" or "deny"';
|
|
91
|
+
} else if (k === 'allow' || k === 'deny') {
|
|
92
|
+
if (!Array.isArray(list)) return `hosts.${k} must be an array`;
|
|
93
|
+
for (const [i, e] of list.entries()) {
|
|
94
|
+
if (typeof e !== 'string') return `hosts.${k}[${i}] must be a string`;
|
|
95
|
+
try { hostMatcher([e]); } catch (err) { return `hosts.${k}[${i}]: ${err instanceof Error ? err.message : String(err)}`; }
|
|
96
|
+
}
|
|
97
|
+
} else return `has unknown field "${k}"`;
|
|
98
|
+
}
|
|
99
|
+
return null;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
/** Keys a profile may set; each reuses the validator of the same top-level key. */
|
|
103
|
+
const PROFILE_KEYS = ['mode', 'hosts', 'secrets'];
|
|
104
|
+
|
|
105
|
+
/** `profiles`: name -> `{ mode?, hosts?, secrets? }`. @param {unknown} v @returns {string|null} */
|
|
106
|
+
const checkProfiles = (v) => {
|
|
107
|
+
if (!isObj(v)) return 'must be an object of name -> { mode?, hosts?, secrets? }';
|
|
108
|
+
for (const [name, p] of Object.entries(/** @type {Record<string, any>} */ (v))) {
|
|
109
|
+
if (!AGENT_RE.test(name)) return `profile name ${JSON.stringify(name)} must match ${AGENT_RE}`;
|
|
110
|
+
if (!isObj(p)) return `profile "${name}" must be an object`;
|
|
111
|
+
for (const [k, val] of Object.entries(p)) {
|
|
112
|
+
if (!PROFILE_KEYS.includes(k)) return `profile "${name}": key "${k}" is not allowed (only ${PROFILE_KEYS.join(', ')})`;
|
|
113
|
+
const bad = KEYS[/** @type {'mode'|'hosts'|'secrets'} */ (k)](val);
|
|
114
|
+
if (bad) return `profile "${name}": key "${k}" ${bad}`;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return null;
|
|
118
|
+
};
|
|
119
|
+
|
|
83
120
|
/** Validators by key; each returns an error string or null. */
|
|
84
121
|
const KEYS = {
|
|
85
122
|
mode: (v) => (MODES.includes(v) ? null : `must be one of ${MODES.join(', ')}`),
|
|
@@ -94,8 +131,10 @@ const KEYS = {
|
|
|
94
131
|
&& Object.values(v).every((a) => Array.isArray(a) && a.length > 0 && a.every(isHttpUrl))
|
|
95
132
|
? null : 'must be an object of vendor -> non-empty array of http(s) URLs'),
|
|
96
133
|
floor: checkFloor,
|
|
134
|
+
hosts: checkHosts,
|
|
97
135
|
env: checkEnv,
|
|
98
136
|
secrets: checkSecrets,
|
|
137
|
+
profiles: checkProfiles,
|
|
99
138
|
};
|
|
100
139
|
|
|
101
140
|
/**
|
|
@@ -109,11 +148,15 @@ export function configPath(env = process.env) {
|
|
|
109
148
|
return path.join(base, 'barebox', 'config.json');
|
|
110
149
|
}
|
|
111
150
|
|
|
151
|
+
/**
|
|
152
|
+
* @typedef {{ 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[] }> }} Settings the effective settings of one run (`heldBodyMaxMB` absent means the library default)
|
|
153
|
+
*/
|
|
154
|
+
|
|
112
155
|
/**
|
|
113
156
|
* Read the config file over the defaults. No file means defaults.
|
|
114
157
|
*
|
|
115
158
|
* @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
|
|
116
|
-
* @returns {
|
|
159
|
+
* @returns {Settings & { profiles?: Record<string, Partial<Pick<Settings, 'mode'|'hosts'|'secrets'>>> }} the file's settings over the defaults
|
|
117
160
|
* @throws {Error} naming the file (and the key) on invalid JSON, an unknown key or a bad value
|
|
118
161
|
*/
|
|
119
162
|
export function loadConfig(env = process.env) {
|
|
@@ -139,27 +182,60 @@ export function loadConfig(env = process.env) {
|
|
|
139
182
|
const bad = KEYS[/** @type {keyof typeof KEYS} */ (k)](v);
|
|
140
183
|
if (bad) throw new Error(`${file}: key "${k}" ${bad}`);
|
|
141
184
|
}
|
|
142
|
-
// A secret read from the host environment must be there at startup (the name, never a value).
|
|
143
|
-
for (const [name, s] of Object.entries(data.secrets ?? {})) {
|
|
144
|
-
if (s.fromEnv !== undefined && !env[s.fromEnv]) {
|
|
145
|
-
throw new Error(`${file}: secret ${name}: host variable ${s.fromEnv} is not set`);
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
185
|
return { ...DEFAULTS, ...data };
|
|
149
186
|
}
|
|
150
187
|
|
|
188
|
+
/**
|
|
189
|
+
* Lay one profile over the top-level settings: the profile's `mode`, `hosts.allow`,
|
|
190
|
+
* `hosts.unknown` and `secrets` replace the top level's when set; `hosts.deny` is
|
|
191
|
+
* the union, so a profile can add a deny but never remove one. Inputs are not changed.
|
|
192
|
+
*
|
|
193
|
+
* @param {ReturnType<typeof loadConfig>} top the file's settings without `profiles`
|
|
194
|
+
* @param {NonNullable<ReturnType<typeof loadConfig>['profiles']>[string]} p one validated profile
|
|
195
|
+
* @returns {Settings} the settings the run uses
|
|
196
|
+
*/
|
|
197
|
+
function withProfile(top, p) {
|
|
198
|
+
const out = { ...top };
|
|
199
|
+
if (p.mode !== undefined) out.mode = p.mode;
|
|
200
|
+
if (p.secrets !== undefined) out.secrets = p.secrets;
|
|
201
|
+
if (p.hosts !== undefined) {
|
|
202
|
+
out.hosts = { ...top.hosts, ...p.hosts };
|
|
203
|
+
const deny = [...new Set([...(top.hosts?.deny ?? []), ...(p.hosts.deny ?? [])])];
|
|
204
|
+
if (deny.length) out.hosts.deny = deny;
|
|
205
|
+
}
|
|
206
|
+
return out;
|
|
207
|
+
}
|
|
208
|
+
|
|
151
209
|
/**
|
|
152
210
|
* Settings for one `sbx run`: a CLI flag beats the file, the file beats the default.
|
|
211
|
+
* With `flags.profile`, that profile is laid over the top level first: `mode`,
|
|
212
|
+
* `hosts.allow`, `hosts.unknown` and `secrets` are replaced when the profile
|
|
213
|
+
* sets them, `hosts.deny` is the union. The result has no `profiles` key.
|
|
153
214
|
*
|
|
154
215
|
* @param {object} [flags] values given on the command line
|
|
155
216
|
* @param {string} [flags.mode] `--mode`
|
|
217
|
+
* @param {string} [flags.profile] `--profile`: a name under `profiles`
|
|
156
218
|
* @param {string} [flags.hold] `--hold` (`"never"` or a positive integer of seconds, as typed)
|
|
157
219
|
* @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
|
|
158
|
-
* @returns {
|
|
220
|
+
* @returns {Settings} effective settings, no `profiles` key
|
|
159
221
|
* @throws {Error} as {@link loadConfig}
|
|
160
222
|
*/
|
|
161
223
|
export function resolveConfig(flags = {}, env = process.env) {
|
|
162
|
-
const
|
|
224
|
+
const { profiles = {}, ...top } = loadConfig(env);
|
|
225
|
+
let cfg = top;
|
|
226
|
+
if (flags.profile !== undefined) {
|
|
227
|
+
if (!Object.hasOwn(profiles, flags.profile)) {
|
|
228
|
+
const names = Object.keys(profiles);
|
|
229
|
+
throw new Error(`unknown profile ${JSON.stringify(flags.profile)}; ${names.length ? `defined: ${names.join(', ')}` : 'no profiles are defined'}`);
|
|
230
|
+
}
|
|
231
|
+
cfg = withProfile(top, profiles[flags.profile]);
|
|
232
|
+
}
|
|
233
|
+
// A secret read from the host environment must be there at startup (the name, never a value).
|
|
234
|
+
for (const [name, s] of Object.entries(cfg.secrets ?? {})) {
|
|
235
|
+
if (s.fromEnv !== undefined && !env[s.fromEnv]) {
|
|
236
|
+
throw new Error(`${configPath(env)}: secret ${name}: host variable ${s.fromEnv} is not set`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
163
239
|
let hold;
|
|
164
240
|
if (flags.hold !== undefined) {
|
|
165
241
|
hold = flags.hold === 'never' ? 'never' : /^\d+$/.test(flags.hold) ? Number(flags.hold) : flags.hold;
|
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
|
|
|
@@ -29,7 +30,7 @@ export const ANSI = { bold: '\x1b[1m', dim: '\x1b[2m', red: '\x1b[31m', green: '
|
|
|
29
30
|
*/
|
|
30
31
|
export const paint = (on, codes, text) => (on ? `${codes}${text}${ANSI.reset}` : text);
|
|
31
32
|
|
|
32
|
-
/** @typedef {{ id: string, agent?: string, method: string, url: string, rule: string, letter: string, bodyPreview?: string, expiresAt?: string|null, floor?: { kind: string, entry: string }, effect?: import('./effect.js').Effect, keyLast4?: string, modelKey?: 'none'|'other' }} AskRecord */
|
|
33
|
+
/** @typedef {{ id: string, agent?: string, method: string, url: string, rule: string, letter: string, bodyPreview?: string, expiresAt?: string|null, floor?: { kind: string, entry: string }, effect?: import('./effect.js').Effect, keyLast4?: string, modelKey?: 'none'|'other', profile?: string }} AskRecord */
|
|
33
34
|
|
|
34
35
|
/**
|
|
35
36
|
* The `To:` / `Amount:` / `Currency:` lines of a floor request, or one `Effect:` line saying why none was read.
|
|
@@ -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)})`
|
|
@@ -106,13 +128,14 @@ export function questionLines(ask, now = Date.now(), color = false) {
|
|
|
106
128
|
: rule;
|
|
107
129
|
const left = ask.expiresAt ? Math.max(0, Math.round((Date.parse(ask.expiresAt) - now) / 1000)) : null;
|
|
108
130
|
const name = safe(ask.agent) || 'agent';
|
|
131
|
+
const via = ask.profile !== undefined ? ` (profile ${safe(ask.profile)})` : '';
|
|
109
132
|
const head = color
|
|
110
|
-
? paint(true, yellow, `⏸ ${bold}${name}${unbold} wants to ${verb} ${host}`)
|
|
111
|
-
: `⏸ ${name} wants to ${verb} ${host}`;
|
|
133
|
+
? paint(true, yellow, `⏸ ${bold}${name}${unbold}${via} wants to ${verb} ${host}`)
|
|
134
|
+
: `⏸ ${name}${via} wants to ${verb} ${host}`;
|
|
112
135
|
const lines = [
|
|
113
136
|
head,
|
|
114
137
|
` ${paint(color, bold, 'Why:')} ${why}`,
|
|
115
|
-
` ${paint(color, bold, 'URL:')} ${paint(color, cyan, `${method} ${
|
|
138
|
+
` ${paint(color, bold, 'URL:')} ${paint(color, cyan, `${method} ${askUrl(ask)}`)}`,
|
|
116
139
|
];
|
|
117
140
|
lines.push(...effectLines(ask.effect, color));
|
|
118
141
|
const body = safe(ask.bodyPreview).slice(0, BODY_CHARS);
|