barebox 0.10.1 → 0.12.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 +14 -0
- package/README.md +4 -4
- package/barebox.context.md +10 -7
- package/package.json +1 -1
- package/src/bodyview.js +92 -0
- package/src/cli.js +14 -7
- package/src/config.js +3 -3
- package/src/prompt.js +51 -26
- package/src/proxy.js +24 -3
- package/types/bodyview.d.ts +19 -0
- package/types/config.d.ts +4 -4
- package/types/prompt.d.ts +5 -4
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,20 @@ 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.12.0] - 2026-11-12
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
- `sbx run` on a terminal answers at once with `→ sent` and appends the outcome when the proxy decides (`✓ allowed`, `✗ denied`, `✗ timed out (denied)`, ...): a `y` typed just before the `--hold` deadline shows `✗ timed out (denied)`, never `✓ allowed`, and no plain `decided` line repeats it. An answer that cannot be written prints `✗ not sent (<code>)` instead of nothing.
|
|
12
|
+
- After `✗ not sent` the same question stays open for a retry; a second hold never prints into an open `→ sent` line.
|
|
13
|
+
- `sbx run` without a terminal (cron, CI, `--json`, stdin or stderr redirected) now denies a held request after 3 minutes instead of waiting forever; with a terminal it still waits. `--hold` or `holdTimeoutSec` sets either.
|
|
14
|
+
|
|
15
|
+
## [0.11.0] - 2026-11-11
|
|
16
|
+
|
|
17
|
+
### Added
|
|
18
|
+
|
|
19
|
+
- Card numbers are found in `gzip` and `deflate` request bodies up to 64 KB of decoded output, and the ask preview shows such bodies decoded. The body as sent is always scanned too, so a false `Content-Encoding` cannot hide a plain card. `br`, `zstd`, raw deflate sent as `deflate`, a gzip member followed by extra bytes, and stacked encodings are not decoded; they are scanned as sent.
|
|
20
|
+
|
|
7
21
|
## [0.10.1] - 2026-11-11
|
|
8
22
|
|
|
9
23
|
### Changed
|
package/README.md
CHANGED
|
@@ -80,7 +80,7 @@ The mode (`sbx run --mode ...`) picks which letters pass without asking:
|
|
|
80
80
|
| Blocked | How |
|
|
81
81
|
|---|---|
|
|
82
82
|
| Keys and credentials: `~/.ssh`, `~/.gnupg`, `~/.password-store`, `~/secrets`, keyrings, browser profiles, `~/.aws`, `~/.azure`, `~/.config/gcloud`, `~/.kube`, `~/.docker`, `~/.config/gh`, `~/.config/op`, `~/.netrc`, `~/.npmrc`, `~/.pypirc`, `~/.git-credentials`, `~/.cargo/credentials.toml` | masked inside the sandbox: they read as empty |
|
|
83
|
-
| Your environment | cleared; only a short safe list (`TERM`, `LANG`, `LC_*`, `TZ`, `USER`, `SHELL`, ...) and names you list in `env.pass` get in (names like `*_TOKEN`, `*_KEY` are refused) |
|
|
83
|
+
| Your environment | cleared; only a short safe list (`TERM`, `LANG`, `LC_*`, `TZ`, `USER`, `SHELL`, ...) and names you list in `env.pass` get in (names like `*_TOKEN`, `*_KEY` are refused; set a harmless one such as `XKB_KEYMAP` with `env.set`) |
|
|
84
84
|
| Any network but the proxy | the sandbox has no network of its own. `--noproxy`, unset proxy env, a direct IP or a raw socket fail closed; UDP and non-HTTP traffic are denied |
|
|
85
85
|
| Private and local addresses | the proxy checks every resolved IP (IPv6 spellings of IPv4 included) and refuses private ranges and names that don't resolve |
|
|
86
86
|
| Real API keys | the agent holds a per-run placeholder; the proxy swaps in the real key after the gate allows the request, over HTTPS, and only for the key's bound hosts (see below) |
|
|
@@ -97,10 +97,10 @@ A held request asks in the terminal where you ran `sbx run` (`y` allows, anythin
|
|
|
97
97
|
Data: {"amount":35000,"currency":"usd"}
|
|
98
98
|
Allow? [y/N] (hold h1)
|
|
99
99
|
y
|
|
100
|
-
✓ allowed
|
|
100
|
+
→ sent ✓ allowed
|
|
101
101
|
```
|
|
102
102
|
|
|
103
|
-
Name the sandbox (`--name docs-bot`) and a second terminal can answer too: `sbx pending --name docs-bot`, `sbx approve h1 --name docs-bot`. A hold waits until you answer;
|
|
103
|
+
Name the sandbox (`--name docs-bot`) and a second terminal can answer too: `sbx pending --name docs-bot`, `sbx approve h1 --name docs-bot`. A hold waits until you answer at a terminal; without one (cron, CI, `--json`, stdin or stderr redirected) it is denied after 3 minutes. `--hold <seconds|never>` or `holdTimeoutSec` changes either, and a timeout is a deny. One held request per agent at a time; up to 16 more wait in line.
|
|
104
104
|
|
|
105
105
|
Demo A's end-of-run summary (from the recorded take):
|
|
106
106
|
|
|
@@ -157,7 +157,7 @@ barebox is a guardrail against mistakes and prompt-injected agents, not a securi
|
|
|
157
157
|
- Data in a `GET` URL goes out free: reads are `r`.
|
|
158
158
|
- The proxy resolves DNS before the gate decides, so data hidden in a hostname can leak.
|
|
159
159
|
- Model API calls pass with any key, an attacker's included.
|
|
160
|
-
- Bodies over 64 KB and
|
|
160
|
+
- Bodies over 64 KB are not scanned for card numbers. `gzip` and `deflate` bodies are decoded for the scan (up to 64 KB of output); `br`, `zstd` and bodies that fail to decode are scanned as sent, so a card inside their compressed bytes is not found.
|
|
161
161
|
- `~/.claude` stays readable: Claude Code's tokens refresh themselves.
|
|
162
162
|
- Writes over local sockets (a Postgres, a Docker daemon) are not on the undo layer.
|
|
163
163
|
|
package/barebox.context.md
CHANGED
|
@@ -60,7 +60,10 @@ When a request needs a decision (see "Modes and the gate" below), it parks.
|
|
|
60
60
|
the sandbox name, what it wants to do and why, the URL, a masked body
|
|
61
61
|
preview, then `Allow? [y/N] (hold h3)`. `y` or `yes` allows; anything else, Enter
|
|
62
62
|
included, denies with `denied at the terminal`. A line typed before a question
|
|
63
|
-
appears answers nothing.
|
|
63
|
+
appears answers nothing. `→ sent` prints at once when your answer is written, and the
|
|
64
|
+
outcome is appended on the same line when the proxy decides (`✓ allowed`, `✗ denied`,
|
|
65
|
+
`✗ timed out (denied)`, `✗ agent gone (denied)`, `✗ sandbox closed (denied)`, `✓`/`✗ answered
|
|
66
|
+
elsewhere`), so a `y` that arrives after the deadline shows `→ sent ✗ timed out (denied)`. Name the sandbox with `sbx run --name docs-bot`: the
|
|
64
67
|
name is the agent name and picks the runtime dir
|
|
65
68
|
(`$XDG_RUNTIME_DIR/barebox/<name>`, else `<tmpdir>/sbx-<uid>/<name>`, kept
|
|
66
69
|
after the run), and every other command takes `--name docs-bot` instead of
|
|
@@ -68,7 +71,7 @@ after the run), and every other command takes `--name docs-bot` instead of
|
|
|
68
71
|
|
|
69
72
|
A second terminal can answer at the same time through the file checkpoint
|
|
70
73
|
(`<runtime>/asks` + `<runtime>/answers`); the first answer wins and the
|
|
71
|
-
prompt
|
|
74
|
+
prompt prints `✓ answered elsewhere (allowed)` or `✗ answered elsewhere (<reason>)` when the proxy decides. A write that fails prints `✗ not sent (<code>), try again:` with the same question, and the next line typed retries; the hold also stays open for another terminal or its deadline:
|
|
72
75
|
|
|
73
76
|
```bash
|
|
74
77
|
npx sbx pending --name docs-bot
|
|
@@ -80,7 +83,7 @@ SBX_RUNTIME=/tmp/sbx npx sbx approve h1
|
|
|
80
83
|
SBX_RUNTIME=/tmp/sbx npx sbx deny h2 "reason here"
|
|
81
84
|
```
|
|
82
85
|
|
|
83
|
-
Held requests wait, counting from arrival, until a deadline: the library's default is 120 s (`createHolds`/`createProxy`; `'never'` supported), while `sbx run` waits until answered
|
|
86
|
+
Held requests wait, counting from arrival, until a deadline: the library's default is 120 s (`createHolds`/`createProxy`; `'never'` supported), while `sbx run` waits until answered when a terminal is attached and denies after 180 s without one (`--hold <seconds|never>` or `holdTimeoutSec` overrides either):
|
|
84
87
|
time spent in line and reading the body counts too, and a request past its
|
|
85
88
|
deadline is denied `hold timeout` whether waiting, sending, or parked. Each
|
|
86
89
|
agent holds at most one request being read or parked; later ones wait in
|
|
@@ -90,7 +93,7 @@ need the proxy to be alive: with no live proxy on the runtime `sbx pending`,
|
|
|
90
93
|
`approve` and `deny` exit 1 and say so, because nothing would read the answer.
|
|
91
94
|
`approve` and `deny` wait briefly to learn what the proxy did: an answer for a hold that already ended exits 1 with `<id> already decided`; if the proxy has not read it yet they print `answer written, the proxy has not read it yet` and still report `approved` / `denied`. `--name` for a sandbox that never ran exits 1 with `no sandbox named <n>` and creates nothing. The terminal question is colored only when stderr is a TTY and `NO_COLOR` is unset.
|
|
92
95
|
|
|
93
|
-
Unattended runs (cron, CI,
|
|
96
|
+
Unattended runs (cron, CI, `--json`, stdin or stderr not a TTY; redirecting only stdout still counts as a terminal): nobody answers on the terminal, so by default a held request is denied after 180 s instead of hanging the run. Pass `--hold <seconds|never>` (or set `holdTimeoutSec`) to change that, with or without a terminal.
|
|
94
97
|
|
|
95
98
|
## One call: `run()` and `sbx run`
|
|
96
99
|
|
|
@@ -124,7 +127,7 @@ Its exit code mirrors the agent's.
|
|
|
124
127
|
|
|
125
128
|
`sbx run` reads one optional config file,
|
|
126
129
|
`${XDG_CONFIG_HOME:-$HOME/.config}/barebox/config.json`, with keys `mode`,
|
|
127
|
-
`holdTimeoutSec` (positive integer or `"never"`;
|
|
130
|
+
`holdTimeoutSec` (positive integer or `"never"`; unset: `"never"` with a terminal, 180 without; overridden per run by `--hold`), `heldBodyMaxMB`
|
|
128
131
|
(positive integer) and `localLlm` (array of `"host:port"`). A flag beats the file, the file beats the default; an
|
|
129
132
|
unknown key, bad value or bad JSON exits 2 naming the file and key. The file
|
|
130
133
|
is hidden inside the sandbox wherever it resolves. The library does not read it.
|
|
@@ -152,7 +155,7 @@ optional single space or dash, first digit 2-6, Luhn-valid) and `paymentPath`
|
|
|
152
155
|
(`/checkout`, `/payment`, `/orders`, `/purchase`); both ask in every mode,
|
|
153
156
|
`trust` included. Nothing is denied because of a card. One exception: a call
|
|
154
157
|
to a model endpoint (see "Labels and model endpoints") is never card-scanned,
|
|
155
|
-
in any mode. Bodies over 64 KB stream through unscanned. The body never enters the gate's action.
|
|
158
|
+
in any mode. `gzip` and `deflate` bodies are decoded for the scan and the ask preview (decoded output capped at 64 KB; the upstream still gets the original bytes); `br` and other encodings are scanned as sent. Bodies over 64 KB stream through unscanned. The body never enters the gate's action.
|
|
156
159
|
|
|
157
160
|
barebox's hold queue is each gate's `humanChannel`: the ask files, `onAsk`
|
|
158
161
|
and `sbx approve|deny` work as above, and the ask carries the gate's `rule`
|
|
@@ -357,7 +360,7 @@ The overlay needs bubblewrap >= 0.11.0 for `--overlay` / `sbx diff|commit|rollba
|
|
|
357
360
|
## What this package does not do
|
|
358
361
|
|
|
359
362
|
Per-API labels cover only the vendors whose rwxmap folders you list in
|
|
360
|
-
`labels`; every other request is `http.<METHOD>`. The card-in-body floor checks bodies of 64 KB or less;
|
|
363
|
+
`labels`; every other request is `http.<METHOD>`. The card-in-body floor checks bodies of 64 KB or less (a `gzip` or `deflate` body is checked decoded, up to 64 KB of output; `br`, `zstd`, raw deflate sent as `deflate`, and a gzip member followed by extra bytes are checked as sent, so a card inside their compressed bytes is not found);
|
|
361
364
|
larger bodies stream through unchecked for cards. The removed `hold.shouldHold`
|
|
362
365
|
and `hold.match` are gone: pass `gateFor` instead. No Docker, no MCP server, no macOS/Windows —
|
|
363
366
|
Linux only. POC harnesses live in `poc/` in the repo and never ship.
|
package/package.json
CHANGED
package/src/bodyview.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// The body view: the one owner of "what a request body says". It gives the
|
|
2
|
+
// proxy a view of a body that fits the 64 KB working slot, decoded when it is
|
|
3
|
+
// gzip or deflate. The card scan and the ask preview read the view; forwarding
|
|
4
|
+
// never does (the upstream keeps the original compressed bytes).
|
|
5
|
+
//
|
|
6
|
+
// The rule: decoding only adds to what is scanned. The raw bytes as sent are
|
|
7
|
+
// always scanned by the caller; any decoded output (full, truncated, partial
|
|
8
|
+
// before an error) is scanned as well, and the
|
|
9
|
+
// card floor fires if either scan finds a card. No decode outcome can then
|
|
10
|
+
// check a labelled body less than an unlabelled one.
|
|
11
|
+
//
|
|
12
|
+
// Decoding goes through ONE proxy-wide queue (one decoder at a time):
|
|
13
|
+
// compressed request bodies are rare, so the queue costs almost no wait and
|
|
14
|
+
// bounds a burst of bombs to one live decoder (PRD section 9, "M10
|
|
15
|
+
// decisions"). Output stops at 64 KB with destroy(): zlib's maxOutputLength
|
|
16
|
+
// throws instead of truncating, and without destroy() a bomb keeps inflating.
|
|
17
|
+
// A body that does not decode is viewed as sent (partial output first); a gzip
|
|
18
|
+
// member followed by garbage is not decoded by Node's zlib, a known gap (PRD
|
|
19
|
+
// section 10). Raw deflate (no zlib header) sent as `deflate` is not decoded
|
|
20
|
+
// either: it is viewed as sent, a known gap.
|
|
21
|
+
import zlib from 'node:zlib';
|
|
22
|
+
|
|
23
|
+
const CAP = 65536;
|
|
24
|
+
// Looked up by name at call time, so a test can wrap the factory and count decoders.
|
|
25
|
+
const MAKE = { gzip: 'createGunzip', 'x-gzip': 'createGunzip', deflate: 'createInflate' };
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @typedef {object} BodyView
|
|
29
|
+
* @property {Buffer} text the decoded output when the body was decoded, else the body as sent;
|
|
30
|
+
* the caller must also scan the raw bytes
|
|
31
|
+
* @property {'plain'|'decoded'|'truncated'|'unread'} state plain: sent as is; decoded: gzip/deflate fully
|
|
32
|
+
* decoded; truncated: decoding stopped at 64 KB of output; unread: not decoded or broken, `text` is the
|
|
33
|
+
* partial output decoded before the error, else the body as sent
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Decode up to 64 KB of a gzip/deflate body. Resolves on the stream's close,
|
|
38
|
+
* so the queue never starts the next decoder while this one is still alive.
|
|
39
|
+
*
|
|
40
|
+
* @param {Buffer} buf compressed body
|
|
41
|
+
* @param {string} factory zlib factory name
|
|
42
|
+
* @returns {Promise<{ text: Buffer, state: 'decoded'|'truncated'|'unread' }>} decode result
|
|
43
|
+
*/
|
|
44
|
+
function decodeRaw(buf, factory) {
|
|
45
|
+
return new Promise((resolve) => {
|
|
46
|
+
const z = /** @type {import('node:zlib').Gunzip} */ (zlib[/** @type {'createGunzip'} */ (factory)]());
|
|
47
|
+
/** @type {Buffer[]} */
|
|
48
|
+
const out = [];
|
|
49
|
+
let n = 0;
|
|
50
|
+
// on error: the partial output if any, else the body as sent
|
|
51
|
+
const partial = () => (out.length ? Buffer.concat(out) : buf);
|
|
52
|
+
/** @type {{ text: Buffer, state: 'decoded'|'truncated'|'unread' }|null} */
|
|
53
|
+
let result = null;
|
|
54
|
+
z.on('data', (/** @type {Buffer} */ c) => {
|
|
55
|
+
if (result) return;
|
|
56
|
+
out.push(c);
|
|
57
|
+
n += c.length;
|
|
58
|
+
if (n >= CAP) {
|
|
59
|
+
result = { text: Buffer.concat(out, CAP), state: 'truncated' };
|
|
60
|
+
z.destroy();
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
z.on('end', () => { result ??= { text: Buffer.concat(out), state: 'decoded' }; });
|
|
64
|
+
z.on('error', () => { result ??= { text: partial(), state: 'unread' }; });
|
|
65
|
+
z.on('close', () => resolve(result ?? { text: partial(), state: 'unread' }));
|
|
66
|
+
z.end(buf);
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// One decoder at a time for the whole proxy; the tail never rejects.
|
|
71
|
+
let tail = Promise.resolve();
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* @param {Buffer} buf the body (at most 64 KB as sent)
|
|
75
|
+
* @param {Record<string, string | string[] | undefined>} headers request headers
|
|
76
|
+
* @returns {Promise<BodyView>} the view
|
|
77
|
+
*/
|
|
78
|
+
export async function viewBody(buf, headers) {
|
|
79
|
+
const enc = String(headers['content-encoding'] ?? '').trim().toLowerCase();
|
|
80
|
+
let text = buf;
|
|
81
|
+
/** @type {BodyView['state']} */
|
|
82
|
+
let state = 'plain';
|
|
83
|
+
if (enc !== '' && enc !== 'identity') {
|
|
84
|
+
const factory = Object.hasOwn(MAKE, enc) ? MAKE[/** @type {keyof typeof MAKE} */ (enc)] : null;
|
|
85
|
+
if (factory) {
|
|
86
|
+
const p = tail.then(() => decodeRaw(buf, factory));
|
|
87
|
+
tail = p.then(() => {}, () => {});
|
|
88
|
+
({ text, state } = await p);
|
|
89
|
+
} else state = 'unread';
|
|
90
|
+
}
|
|
91
|
+
return { text, state };
|
|
92
|
+
}
|
package/src/cli.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
// cwd-relative default.
|
|
8
8
|
//
|
|
9
9
|
// Settings (mode, holdTimeoutSec, heldBodyMaxMB, localLlm) come from the one config file, see config.js;
|
|
10
|
-
// a flag beats the file. A bad file is a usage-class error (exit 2).
|
|
10
|
+
// a flag beats the file, the file beats the default (holdTimeoutSec unset: wait with a terminal, 180 s then deny without). A bad file is a usage-class error (exit 2).
|
|
11
11
|
//
|
|
12
12
|
// With a terminal (stdin and stderr TTYs, no --json) `sbx run` asks each hold in place (prompt.js);
|
|
13
13
|
// `--name <n>` names the sandbox (agent name + runtime dir, runtime.js namedRuntime) and every
|
|
@@ -43,6 +43,8 @@ import { DEFAULT_POLL_MS } 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
|
+
// Seconds a held request waits when no one is at a terminal and neither --hold nor holdTimeoutSec is set.
|
|
47
|
+
const HOLD_NO_TERMINAL_SEC = 180;
|
|
46
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)';
|
|
47
49
|
|
|
48
50
|
/** Hold ids the CLI accepts: `h<n>` only. Anything else is a usage error, never a path. */
|
|
@@ -216,7 +218,7 @@ async function run(args) {
|
|
|
216
218
|
usage();
|
|
217
219
|
}
|
|
218
220
|
if (values.mode !== undefined && !MODES.includes(values.mode)) usage();
|
|
219
|
-
/** @type {{ mode: string, holdTimeoutSec
|
|
221
|
+
/** @type {{ mode: string, holdTimeoutSec?: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} */
|
|
220
222
|
let cfg;
|
|
221
223
|
try {
|
|
222
224
|
cfg = resolveConfig({ mode: values.mode, hold: values.hold });
|
|
@@ -233,9 +235,14 @@ async function run(args) {
|
|
|
233
235
|
err(e instanceof Error ? e.message : String(e));
|
|
234
236
|
process.exit(2);
|
|
235
237
|
}
|
|
236
|
-
const timeoutMs = cfg.holdTimeoutSec === 'never' ? 'never' : Number(cfg.holdTimeoutSec) * 1000;
|
|
237
238
|
if (!command.length) usage();
|
|
238
239
|
const json = values.json ?? false;
|
|
240
|
+
// A person at this terminal (stdin and stderr are TTYs, not --json) answers
|
|
241
|
+
// holds here; the file channel stays on, so `sbx approve` still works too.
|
|
242
|
+
const interactive = !json && !!process.stdin.isTTY && !!process.stderr.isTTY;
|
|
243
|
+
// No --hold and no holdTimeoutSec: wait for the person at a terminal, else deny after 180 s.
|
|
244
|
+
const hold = cfg.holdTimeoutSec ?? (interactive ? 'never' : HOLD_NO_TERMINAL_SEC);
|
|
245
|
+
const timeoutMs = hold === 'never' ? 'never' : Number(hold) * 1000;
|
|
239
246
|
const overlay = values.overlay ?? false;
|
|
240
247
|
const name = values.name;
|
|
241
248
|
if (name !== undefined) {
|
|
@@ -250,10 +257,8 @@ async function run(args) {
|
|
|
250
257
|
for (const k of keys) if (c[k] != null) c[k] = safe(c[k]);
|
|
251
258
|
return c;
|
|
252
259
|
};
|
|
253
|
-
// A person at this terminal (stdin and stderr are TTYs, not --json) answers
|
|
254
|
-
// holds here; the file channel stays on, so `sbx approve` still works too.
|
|
255
260
|
const errColor = !!process.stderr.isTTY && !process.env.NO_COLOR;
|
|
256
|
-
const prompt =
|
|
261
|
+
const prompt = interactive
|
|
257
262
|
? createTerminalPrompt({
|
|
258
263
|
input: process.stdin,
|
|
259
264
|
output: process.stderr,
|
|
@@ -261,13 +266,15 @@ async function run(args) {
|
|
|
261
266
|
answer: (id, decision, reason) => writeAnswer(runtimePaths(runtime), id, decision, reason),
|
|
262
267
|
})
|
|
263
268
|
: null;
|
|
269
|
+
const prompted = new Set(); // holds the prompt showed: their answer is shown there too
|
|
264
270
|
const emitAsk = (h) => {
|
|
265
|
-
if (prompt?.ask(h)) return;
|
|
271
|
+
if (prompt?.ask(h)) { prompted.add(h.id); return; }
|
|
266
272
|
const c = clean(h, ['id', 'agent', 'method', 'url', 'rule', 'bodyPreview']);
|
|
267
273
|
if (json) out(JSON.stringify({ ev: 'ask', ...c }));
|
|
268
274
|
else out(`ask ${c.id} ${c.agent} ${c.method} ${c.url} rule=${c.rule}`);
|
|
269
275
|
};
|
|
270
276
|
const emitDecided = (e) => {
|
|
277
|
+
if (!json && prompted.delete(e.id)) return;
|
|
271
278
|
const c = clean(e, ['id', 'decision', 'reason']);
|
|
272
279
|
if (json) out(JSON.stringify({ ev: 'decided', id: c.id, decision: c.decision, reason: c.reason }));
|
|
273
280
|
else out(`decided ${c.id} ${c.decision}${c.reason ? ` (${c.reason})` : ''}`);
|
package/src/config.js
CHANGED
|
@@ -7,7 +7,7 @@ import os from 'node:os';
|
|
|
7
7
|
import path from 'node:path';
|
|
8
8
|
import { MODES } from './policy.js';
|
|
9
9
|
|
|
10
|
-
const DEFAULTS = { mode: 'auto',
|
|
10
|
+
const DEFAULTS = { mode: 'auto', localLlm: [], labels: [], tenants: {} };
|
|
11
11
|
|
|
12
12
|
/** One `host:port` (host without a colon, port 1-65535). @param {unknown} v @returns {boolean} */
|
|
13
13
|
const isHostPort = (v) => {
|
|
@@ -97,7 +97,7 @@ export function configPath(env = process.env) {
|
|
|
97
97
|
* Read the config file over the defaults. No file means defaults.
|
|
98
98
|
*
|
|
99
99
|
* @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
|
|
100
|
-
* @returns {{ mode: string, holdTimeoutSec
|
|
100
|
+
* @returns {{ mode: string, holdTimeoutSec?: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
|
|
101
101
|
* @throws {Error} naming the file (and the key) on invalid JSON, an unknown key or a bad value
|
|
102
102
|
*/
|
|
103
103
|
export function loadConfig(env = process.env) {
|
|
@@ -139,7 +139,7 @@ export function loadConfig(env = process.env) {
|
|
|
139
139
|
* @param {string} [flags.mode] `--mode`
|
|
140
140
|
* @param {string} [flags.hold] `--hold` (`"never"` or a positive integer of seconds, as typed)
|
|
141
141
|
* @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
|
|
142
|
-
* @returns {{ mode: string, holdTimeoutSec
|
|
142
|
+
* @returns {{ mode: string, holdTimeoutSec?: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
|
|
143
143
|
* @throws {Error} as {@link loadConfig}
|
|
144
144
|
*/
|
|
145
145
|
export function resolveConfig(flags = {}, env = process.env) {
|
package/src/prompt.js
CHANGED
|
@@ -71,40 +71,67 @@ export function questionLines(ask, now = Date.now(), color = false) {
|
|
|
71
71
|
}
|
|
72
72
|
|
|
73
73
|
/**
|
|
74
|
-
* The terminal prompt.
|
|
75
|
-
* and returns true, or returns false when
|
|
76
|
-
* is
|
|
77
|
-
*
|
|
74
|
+
* The terminal prompt. It owns one hold from its question to the proxy's
|
|
75
|
+
* verdict. `ask()` opens a question and returns true, or returns false when a
|
|
76
|
+
* hold is still current (asking or awaiting its verdict) or the prompt is
|
|
77
|
+
* closed, so the caller prints the plain `ask` line instead; `decided()`
|
|
78
|
+
* ends the current hold with its outcome line, `close()` releases
|
|
78
79
|
* `input`.
|
|
79
80
|
*
|
|
80
81
|
* @param {{ input: import('node:stream').Readable, output: { write: (s: string) => unknown }, color?: boolean, answer: (id: string, decision: 'allow'|'deny', reason?: string) => boolean|void }} opts streams and the answer writer
|
|
81
82
|
* @returns {{ ask: (ask: AskRecord) => boolean, decided: (e: { id: string, decision: string, reason?: string }) => void, close: () => void }} the prompt
|
|
82
83
|
*/
|
|
83
84
|
export function createTerminalPrompt({ input, output, answer, color = false }) {
|
|
84
|
-
/**
|
|
85
|
-
|
|
85
|
+
/** The one hold this prompt owns, from its question to the proxy's verdict. `typedYes`: true/false once our answer was written, null when another answer won, undefined while still asking.
|
|
86
|
+
* @type {{ ask: AskRecord, state: 'asking'|'sent', typedYes?: boolean|null }|null} */
|
|
87
|
+
let current = null;
|
|
86
88
|
let buf = '';
|
|
87
89
|
let closed = false;
|
|
88
90
|
const say = (/** @type {string} */ s) => { output.write(`${s}\n`); };
|
|
89
91
|
|
|
92
|
+
// The one place that words an outcome. `typedYes` is true/false when our
|
|
93
|
+
// typed answer was written (✓/✗ allowed/denied only when the proxy's verdict
|
|
94
|
+
// matches it), undefined/null when nothing of ours was sent.
|
|
95
|
+
const outcome = (/** @type {{ decision: string, reason?: string }} */ e, /** @type {boolean|null|undefined} */ typedYes) => {
|
|
96
|
+
const why = safe(e.reason);
|
|
97
|
+
return typedYes === true && e.decision === 'allow' ? paint(color, ANSI.green + ANSI.bold, '✓ allowed')
|
|
98
|
+
: typedYes === false && e.decision === 'deny' && why === 'denied at the terminal' ? paint(color, ANSI.red + ANSI.bold, '✗ denied')
|
|
99
|
+
: why === 'hold timeout' ? paint(color, ANSI.red, '✗ timed out (denied)')
|
|
100
|
+
: why === 'client gone' ? paint(color, ANSI.red, '✗ agent gone (denied)')
|
|
101
|
+
: why === 'proxy closing' ? paint(color, ANSI.red, '✗ sandbox closed (denied)')
|
|
102
|
+
: e.decision === 'allow' ? '✓ answered elsewhere (allowed)'
|
|
103
|
+
: `✗ answered elsewhere (${why || 'denied'})`;
|
|
104
|
+
};
|
|
105
|
+
|
|
90
106
|
const onLine = (/** @type {string} */ line) => {
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
open = null; // closed before the write: one answer per question
|
|
107
|
+
const hold = current;
|
|
108
|
+
if (!hold || hold.state !== 'asking') return; // unreachable at runtime (onData checks); narrows the type for tsc
|
|
94
109
|
const yes = YES.has(line.trim().toLowerCase());
|
|
110
|
+
let written = false;
|
|
95
111
|
try {
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
//
|
|
112
|
+
written = answer(hold.ask.id, yes ? 'allow' : 'deny', yes ? undefined : 'denied at the terminal') !== false;
|
|
113
|
+
} catch (e) {
|
|
114
|
+
// The write failed (disk full, runtime gone, ...); the run goes on and the
|
|
115
|
+
// hold stays open and asking: the next line retries. Say so at once:
|
|
116
|
+
// nothing else would, and a hold with no timeout would wait on a blank
|
|
117
|
+
// line. Never the message: it may hold a path.
|
|
118
|
+
const code = e && typeof e === 'object' && 'code' in e && typeof e.code === 'string' ? e.code : 'error';
|
|
119
|
+
const question = questionLines(hold.ask, Date.now(), color).at(-1)?.trimStart();
|
|
120
|
+
say(`${paint(color, ANSI.red, `✗ not sent (${safe(code)}), try again:`)} ${question}`);
|
|
121
|
+
return;
|
|
101
122
|
}
|
|
123
|
+
// The receipt is instant; the verdict is appended by `decided` once the proxy
|
|
124
|
+
// has read the file (it may still time the hold out first). A lost write
|
|
125
|
+
// (another answer won) prints nothing now, but its `decided` still words the outcome.
|
|
126
|
+
hold.state = 'sent';
|
|
127
|
+
hold.typedYes = written ? yes : null;
|
|
128
|
+
if (written) output.write(`${paint(color, ANSI.dim, '→ sent')} `);
|
|
102
129
|
};
|
|
103
130
|
|
|
104
131
|
const onData = (/** @type {string|Buffer} */ chunk) => {
|
|
105
|
-
if (
|
|
132
|
+
if (current?.state !== 'asking') return;
|
|
106
133
|
buf += String(chunk);
|
|
107
|
-
for (let m = EOL.exec(buf); m &&
|
|
134
|
+
for (let m = EOL.exec(buf); m && current?.state === 'asking'; m = EOL.exec(buf)) {
|
|
108
135
|
const line = buf.slice(0, m.index);
|
|
109
136
|
buf = buf.slice(m.index + m[0].length);
|
|
110
137
|
onLine(line);
|
|
@@ -116,23 +143,21 @@ export function createTerminalPrompt({ input, output, answer, color = false }) {
|
|
|
116
143
|
|
|
117
144
|
return {
|
|
118
145
|
ask(ask) {
|
|
119
|
-
if (closed ||
|
|
120
|
-
|
|
146
|
+
if (closed || current) return false;
|
|
147
|
+
current = { ask, state: 'asking' };
|
|
121
148
|
buf = ''; // a half-typed line from before the question is stale
|
|
122
|
-
for (const l of questionLines(
|
|
149
|
+
for (const l of questionLines(ask, Date.now(), color)) say(l);
|
|
123
150
|
return true;
|
|
124
151
|
},
|
|
125
152
|
decided(e) {
|
|
126
|
-
if (
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
say(
|
|
130
|
-
: why === 'client gone' || why === 'proxy closing' ? paint(color, ANSI.red, `agent gone: ${safe(e.decision)}`)
|
|
131
|
-
: `answered elsewhere: ${safe(e.decision)}${why ? ` (${why})` : ''}`);
|
|
153
|
+
if (current?.ask.id !== e.id) return;
|
|
154
|
+
const typedYes = current.typedYes;
|
|
155
|
+
current = null; // closed before anything else: no answer can follow
|
|
156
|
+
say(outcome(e, typedYes));
|
|
132
157
|
},
|
|
133
158
|
close() {
|
|
134
159
|
closed = true;
|
|
135
|
-
|
|
160
|
+
current = null;
|
|
136
161
|
input.removeListener('data', onData);
|
|
137
162
|
input.pause();
|
|
138
163
|
},
|
package/src/proxy.js
CHANGED
|
@@ -20,6 +20,7 @@ import path from 'node:path';
|
|
|
20
20
|
import { ensureCA, certFor, HOST_RE } from './certs.js';
|
|
21
21
|
import { createCardScanner } from './cardscan.js';
|
|
22
22
|
import { ASK_BODY_LIMIT, DEFAULT_HOLD_MAX_BODY, bodyPreview, createHolds } from './holds.js';
|
|
23
|
+
import { viewBody } from './bodyview.js';
|
|
23
24
|
import { claimRuntime, ensurePrivateDir, runtimePaths } from './runtime.js';
|
|
24
25
|
import { paymentPath, toolFor, buildTools, modelTools, modelList, emptyMatcher } from './policy.js';
|
|
25
26
|
import { checkUpstream } from './wall.js';
|
|
@@ -502,6 +503,7 @@ export function createProxy(opts) {
|
|
|
502
503
|
* @property {number|null} status HTTP status the channel wants for a denial (null: 403)
|
|
503
504
|
* @property {string|null} heldId id of the held body file, once spooled
|
|
504
505
|
* @property {((reason: string) => void)|null} endAsk end a not-yet-parked ask as a denial
|
|
506
|
+
* @property {Buffer|null} decodedHead copy of the first 4 KB of a gzip/deflate body, decoded (the ask preview)
|
|
505
507
|
*/
|
|
506
508
|
|
|
507
509
|
/**
|
|
@@ -608,7 +610,7 @@ export function createProxy(opts) {
|
|
|
608
610
|
// Parked: the tunnel stays open until the ask channel decides.
|
|
609
611
|
// null: the reservation already expired and onExpire refused.
|
|
610
612
|
parked = queue.add({ agent, method: ctx.method, url: ctx.url,
|
|
611
|
-
preview: bodyPreview(ctx.tee.head), bodyBytes: ctx.tee.bytes,
|
|
613
|
+
preview: bodyPreview(ctx.decodedHead ?? ctx.tee.head), bodyBytes: ctx.tee.bytes,
|
|
612
614
|
sock, note: event.rule ?? 'ask', letter: event.rwxLetter, finish,
|
|
613
615
|
slot, arrivedAt: slot.arrivedAt }) !== null;
|
|
614
616
|
};
|
|
@@ -747,14 +749,16 @@ export function createProxy(opts) {
|
|
|
747
749
|
/** @type {RequestCtx} */
|
|
748
750
|
const ctx = { agent, method, url: urlStr, headers: { ...creq.headers }, creq, cres, tee,
|
|
749
751
|
hasBody, chunks: [], over: false, freeWork, asked: false, status: null, heldId: null,
|
|
750
|
-
endAsk: null };
|
|
752
|
+
endAsk: null, decodedHead: null };
|
|
751
753
|
// A model call is never card-scanned (user decision, Nov 2); the floor keeps every other request.
|
|
752
754
|
const tool = toolFor(matcher, tools, method, urlStr, modelEndpoints);
|
|
753
755
|
let cardLike = false;
|
|
754
756
|
if (hasBody) {
|
|
755
757
|
if (await readWorkBody(ctx)) return;
|
|
756
758
|
// Past 64 KB the body streams on unscanned (known gap).
|
|
757
|
-
if (!ctx.over && !models.has(tool))
|
|
759
|
+
if (!ctx.over && !models.has(tool)) {
|
|
760
|
+
cardLike = await scanBody(ctx);
|
|
761
|
+
}
|
|
758
762
|
}
|
|
759
763
|
// The body never goes in the action: bareguard writes the action to its audit file.
|
|
760
764
|
const action = { type: 'net', tool, url: urlStr, method, agent,
|
|
@@ -850,6 +854,23 @@ export function createProxy(opts) {
|
|
|
850
854
|
return false;
|
|
851
855
|
}
|
|
852
856
|
|
|
857
|
+
/**
|
|
858
|
+
* Scan the working slice of the body for card numbers and keep a copy of the
|
|
859
|
+
* decoded head as the ask preview. Its own frame, so no reference to the
|
|
860
|
+
* body or its decoded view outlives the scan (same reason as `readWorkBody`).
|
|
861
|
+
*
|
|
862
|
+
* @param {RequestCtx} ctx request context, chunks already read
|
|
863
|
+
* @returns {Promise<boolean>} true when the body looks like a card number
|
|
864
|
+
*/
|
|
865
|
+
async function scanBody(ctx) {
|
|
866
|
+
const body = Buffer.concat(ctx.chunks);
|
|
867
|
+
const view = await viewBody(body, ctx.headers);
|
|
868
|
+
// A copy, never a subarray: a subarray would keep the whole decoded buffer alive.
|
|
869
|
+
if (view.state === 'decoded' || view.state === 'truncated') ctx.decodedHead = Buffer.from(view.text.subarray(0, ASK_BODY_LIMIT));
|
|
870
|
+
// The raw bytes are always scanned; decoded output is scanned as well (one scanner per buffer).
|
|
871
|
+
return createCardScanner().push(body) || (view.text !== body && createCardScanner().push(view.text));
|
|
872
|
+
}
|
|
873
|
+
|
|
853
874
|
/**
|
|
854
875
|
* Read a paused request's body until it ends or passes `limit` bytes
|
|
855
876
|
* (then pause again, keeping everything read so far in `chunks`).
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @param {Buffer} buf the body (at most 64 KB as sent)
|
|
3
|
+
* @param {Record<string, string | string[] | undefined>} headers request headers
|
|
4
|
+
* @returns {Promise<BodyView>} the view
|
|
5
|
+
*/
|
|
6
|
+
export function viewBody(buf: Buffer, headers: Record<string, string | string[] | undefined>): Promise<BodyView>;
|
|
7
|
+
export type BodyView = {
|
|
8
|
+
/**
|
|
9
|
+
* the decoded output when the body was decoded, else the body as sent;
|
|
10
|
+
* the caller must also scan the raw bytes
|
|
11
|
+
*/
|
|
12
|
+
text: Buffer;
|
|
13
|
+
/**
|
|
14
|
+
* plain: sent as is; decoded: gzip/deflate fully
|
|
15
|
+
* decoded; truncated: decoding stopped at 64 KB of output; unread: not decoded or broken, `text` is the
|
|
16
|
+
* partial output decoded before the error, else the body as sent
|
|
17
|
+
*/
|
|
18
|
+
state: "plain" | "decoded" | "truncated" | "unread";
|
|
19
|
+
};
|
package/types/config.d.ts
CHANGED
|
@@ -9,12 +9,12 @@ 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
|
|
12
|
+
* @returns {{ mode: string, holdTimeoutSec?: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, 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): {
|
|
16
16
|
mode: string;
|
|
17
|
-
holdTimeoutSec
|
|
17
|
+
holdTimeoutSec?: number | string;
|
|
18
18
|
localLlm: string[];
|
|
19
19
|
labels: string[];
|
|
20
20
|
tenants: Record<string, string[]>;
|
|
@@ -36,7 +36,7 @@ export function loadConfig(env?: NodeJS.ProcessEnv): {
|
|
|
36
36
|
* @param {string} [flags.mode] `--mode`
|
|
37
37
|
* @param {string} [flags.hold] `--hold` (`"never"` or a positive integer of seconds, as typed)
|
|
38
38
|
* @param {NodeJS.ProcessEnv} [env] environment to read (default `process.env`)
|
|
39
|
-
* @returns {{ mode: string, holdTimeoutSec
|
|
39
|
+
* @returns {{ mode: string, holdTimeoutSec?: number|string, localLlm: string[], labels: string[], tenants: Record<string, string[]>, heldBodyMaxMB?: number, env?: { pass?: string[], set?: Record<string, string> }, secrets?: Record<string, { fromEnv?: string, value?: string, hosts: string[] }> }} effective settings (`heldBodyMaxMB` absent means the library default)
|
|
40
40
|
* @throws {Error} as {@link loadConfig}
|
|
41
41
|
*/
|
|
42
42
|
export function resolveConfig(flags?: {
|
|
@@ -44,7 +44,7 @@ export function resolveConfig(flags?: {
|
|
|
44
44
|
hold?: string | undefined;
|
|
45
45
|
}, env?: NodeJS.ProcessEnv): {
|
|
46
46
|
mode: string;
|
|
47
|
-
holdTimeoutSec
|
|
47
|
+
holdTimeoutSec?: number | string;
|
|
48
48
|
localLlm: string[];
|
|
49
49
|
labels: string[];
|
|
50
50
|
tenants: Record<string, string[]>;
|
package/types/prompt.d.ts
CHANGED
|
@@ -10,10 +10,11 @@
|
|
|
10
10
|
*/
|
|
11
11
|
export function questionLines(ask: AskRecord, now?: number, color?: boolean): string[];
|
|
12
12
|
/**
|
|
13
|
-
* The terminal prompt.
|
|
14
|
-
* and returns true, or returns false when
|
|
15
|
-
* is
|
|
16
|
-
*
|
|
13
|
+
* The terminal prompt. It owns one hold from its question to the proxy's
|
|
14
|
+
* verdict. `ask()` opens a question and returns true, or returns false when a
|
|
15
|
+
* hold is still current (asking or awaiting its verdict) or the prompt is
|
|
16
|
+
* closed, so the caller prints the plain `ask` line instead; `decided()`
|
|
17
|
+
* ends the current hold with its outcome line, `close()` releases
|
|
17
18
|
* `input`.
|
|
18
19
|
*
|
|
19
20
|
* @param {{ input: import('node:stream').Readable, output: { write: (s: string) => unknown }, color?: boolean, answer: (id: string, decision: 'allow'|'deny', reason?: string) => boolean|void }} opts streams and the answer writer
|