barebox 0.10.0 → 0.11.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,23 @@ 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.11.0] - 2026-11-11
8
+
9
+ ### Added
10
+
11
+ - 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.
12
+
13
+ ## [0.10.1] - 2026-11-11
14
+
15
+ ### Changed
16
+
17
+ - bareguard 0.34.0 and rwxmap 0.11.1, pinned exactly; no behaviour change in barebox.
18
+
19
+ ### Fixed
20
+
21
+ - A host written with a trailing dot (`api.anthropic.com.`) now matches its labels and the built-in model endpoints; before, it fell back to the method's letter.
22
+ - Parallel first connections to a new host no longer lose some tunnels to a half-written certificate, and a crash while creating the CA no longer leaves a broken CA.
23
+
7
24
  ## [0.10.0] - 2026-11-10
8
25
 
9
26
  Docs only; no code or behaviour changes.
package/README.md CHANGED
@@ -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 compressed bodies are not scanned for card numbers.
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
 
@@ -152,7 +152,7 @@ optional single space or dash, first digit 2-6, Luhn-valid) and `paymentPath`
152
152
  (`/checkout`, `/payment`, `/orders`, `/purchase`); both ask in every mode,
153
153
  `trust` included. Nothing is denied because of a card. One exception: a call
154
154
  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.
155
+ 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
156
 
157
157
  barebox's hold queue is each gate's `humanChannel`: the ask files, `onAsk`
158
158
  and `sbx approve|deny` work as above, and the ask carries the gate's `rule`
@@ -302,7 +302,8 @@ Model endpoints are `r` (free in every mode): `api.anthropic.com`
302
302
  `POST /v1/chat/completions`, `/v1/responses` and `/v1/embeddings`; and on each
303
303
  `localLlm` host:port `POST /api/chat`, `/api/generate`, `/api/embed`,
304
304
  `/v1/chat/completions` and `/v1/completions` (over http or https). Any other path on
305
- those hosts is a normal `POST`. Model calls skip the card floor (the
305
+ those hosts is a normal `POST`. A host written with a trailing dot
306
+ (`api.anthropic.com.`) is the same host for labels and model endpoints. Model calls skip the card floor (the
306
307
  `paymentPath` mark still applies): a model call carries the whole conversation,
307
308
  and a card number in it must not kill the agent.
308
309
 
@@ -343,8 +344,8 @@ The overlay needs bubblewrap >= 0.11.0 for `--overlay` / `sbx diff|commit|rollba
343
344
  `NODE_EXTRA_CA_CERTS`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`,
344
345
  `GIT_SSL_CAINFO`. Without it every HTTPS call from inside fails
345
346
  verification. Only `ca.pem` enters the sandbox, never the key.
346
- - Certificates live in `<runtime>/certs` (`runtime` is required). There is no `certDir` option and no control socket: decisions flow through `<runtime>/asks` + `<runtime>/answers` or `hold.onAsk`. Each minted certificate gets a random 128-bit serial (no shared `ca.srl`), and at most 4 mints run at once.
347
- - Memory and limits: one proxy serves at most 40 agents, enforced. `addAgent` throws `createProxy: agent limit reached (40 agents per proxy); run another proxy for more`; the TCP door's `tcp` agent does not count, and `removeAgent` frees a place. For more than 40 agents run more proxies. Measured worst case (every agent with 1 parked + 16 waiting + a filled 64 KB body slot): proxy about 117 / 133-151 / 177-207 / 207-241 MB at 10 / 20 / 30 / 40 agents with every request in its own HTTPS tunnel, quiet to busy machine (the budget at 40 agents is the range 205-245 MB; needs bareguard 0.30.0), plus about 8 MB per sandbox (limit 10). Normal use is about 95-160 MB over HTTPS with keep-alive tunnels open (about 85-120 MB for plain HTTP). Audit file size does not move these numbers. barebox is for small teams: free, local and lightweight, built to assist and to connect to many tools, not to run swarms or thousands of agents.
347
+ - Certificates live in `<runtime>/certs` (`runtime` is required). There is no `certDir` option and no control socket: decisions flow through `<runtime>/asks` + `<runtime>/answers` or `hold.onAsk`. Each minted certificate gets a random 128-bit serial (no shared `ca.srl`), and at most 4 mints run at once. Keys and certs (the CA too) are written to temp names and renamed, key first and cert last, so a final name exists only as a complete pair and a crash mid-write leaves no broken CA.
348
+ - Memory and limits: one proxy serves at most 40 agents, enforced. `addAgent` throws `createProxy: agent limit reached (40 agents per proxy); run another proxy for more`; the TCP door's `tcp` agent does not count, and `removeAgent` frees a place. For more than 40 agents run more proxies. Measured worst case (every agent with 1 parked + 16 waiting + a filled 64 KB body slot): proxy about 117 / 133-151 / 177-207 / 207-241 MB at 10 / 20 / 30 / 40 agents with every request in its own HTTPS tunnel, quiet to busy machine (the budget at 40 agents is the range 205-245 MB; needs bareguard 0.30.0 or later, re-measured on the pinned 0.34.0 at 206 MB), plus about 8 MB per sandbox (limit 10). Normal use is about 95-160 MB over HTTPS with keep-alive tunnels open (about 85-120 MB for plain HTTP). Audit file size does not move these numbers. barebox is for small teams: free, local and lightweight, built to assist and to connect to many tools, not to run swarms or thousands of agents.
348
349
  - The TCP door is one agent: every connection through `createProxy`'s TCP `port` counts as the agent `tcp` and shares one hold line. Use `addAgent` sockets (`sbx run` does) for separate lines per agent. `removeAgent(name)` ends that agent's open connections; its held requests end as deny / client gone. `run()` calls it when the sandbox exits, so a request still held then ends as client gone, not `proxy closing`.
349
350
  - The upstream wall answers `403` for loopback, link-local (incl. `169.254.169.254`), the host's own addresses, private LAN ranges and unresolvable names. An IPv4 embedded in IPv6 is checked in every spelling: mapped, compat, uncompressed, NAT64 `64:ff9b::/96` (local-use `/48` denied outright) and 6to4 `2002::/16`; NAT64 and 6to4 of public sites stay reachable. Every DNS answer is checked and the dial is pinned to the checked IP; test-only options live under `unsafeTestOnly` (`allowLoopback`, `resolveUpstream`) and production never sets them.
350
351
  - `createProxy` throws synchronously on an unopenable `logFile` (a directory, a missing parent, no permission) and releases the runtime. The runtime root, `asks/`, `answers/`, `held/` and `socks/` are owner-only (`0700`) whatever the umask. An existing runtime dir you own is tightened to `0700`; one you don't own (such as `/tmp`) is refused with an error naming the dir and its owner and suggesting a subdir like `/tmp/sbx`. The audit file (`logFile`, `gate.jsonl`) is set to `0600` every time a proxy starts. No request header and no body content is written to it: a body is logged as its length and SHA-256 only. The ask payload's `bodyPreview` (the first 4 KB, card numbers masked except the last 4) lives in the ask file only; other secrets inside a body still show there until bareguard redaction lands. Your `redact` hook shapes the `meta` of barebox's own annotate lines.
@@ -356,7 +357,7 @@ The overlay needs bubblewrap >= 0.11.0 for `--overlay` / `sbx diff|commit|rollba
356
357
  ## What this package does not do
357
358
 
358
359
  Per-API labels cover only the vendors whose rwxmap folders you list in
359
- `labels`; every other request is `http.<METHOD>`. The card-in-body floor checks bodies of 64 KB or less;
360
+ `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);
360
361
  larger bodies stream through unchecked for cards. The removed `hold.shouldHold`
361
362
  and `hold.match` are gone: pass `gateFor` instead. No Docker, no MCP server, no macOS/Windows —
362
363
  Linux only. POC harnesses live in `poc/` in the repo and never ship.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barebox",
3
- "version": "0.10.0",
3
+ "version": "0.11.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": {
@@ -50,7 +50,7 @@
50
50
  "typescript": "5"
51
51
  },
52
52
  "dependencies": {
53
- "bareguard": "0.30.0",
54
- "rwxmap": "0.8.0"
53
+ "bareguard": "0.34.0",
54
+ "rwxmap": "0.11.1"
55
55
  }
56
56
  }
@@ -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/certs.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // CONNECT. Nothing is pre-generated: a fresh runtime dir works on any host.
5
5
  // Minting shells out to `openssl` (the PRD decision: no JS crypto for X.509).
6
6
  import { execFile } from 'node:child_process';
7
- import { mkdirSync, chmodSync, existsSync, writeFileSync, rmSync } from 'node:fs';
7
+ import { mkdirSync, chmodSync, existsSync, writeFileSync, rmSync, renameSync } from 'node:fs';
8
8
  import { join } from 'node:path';
9
9
  import { randomBytes } from 'node:crypto';
10
10
 
@@ -54,23 +54,27 @@ export async function ensureCA(dir) {
54
54
  const keyPath = join(dir, 'ca.key');
55
55
  const certPath = join(dir, 'ca.pem');
56
56
  if (existsSync(certPath)) return { keyPath, certPath };
57
- await sh('openssl', ['genrsa', '-out', keyPath, '2048']);
58
- chmodSync(keyPath, 0o600);
57
+ // Write to temp names, then rename key first and cert last: ca.pem exists
58
+ // only when the pair is complete, so a crash never leaves a CA that is trusted but broken.
59
+ const keyTmp = `${keyPath}.tmp`;
60
+ const certTmp = `${certPath}.tmp`;
61
+ const csr = join(dir, 'ca.csr.tmp');
59
62
  const ext = join(dir, 'ca.ext.tmp');
60
- writeFileSync(ext,
61
- 'basicConstraints=critical,CA:true\n' +
62
- 'keyUsage=critical,keyCertSign,cRLSign,digitalSignature\n' +
63
- 'subjectKeyIdentifier=hash\n' +
64
- 'authorityKeyIdentifier=keyid:always,issuer\n');
65
63
  try {
66
- await sh('openssl', ['req', '-new', '-key', keyPath, '-out', join(dir, 'ca.csr.tmp'),
67
- '-subj', '/CN=barebox-ca']);
68
- await sh('openssl', ['x509', '-req', '-in', join(dir, 'ca.csr.tmp'),
69
- '-signkey', keyPath, '-sha256', '-days', '825',
70
- '-out', certPath, '-extfile', ext]);
64
+ await sh('openssl', ['genrsa', '-out', keyTmp, '2048']);
65
+ chmodSync(keyTmp, 0o600);
66
+ writeFileSync(ext,
67
+ 'basicConstraints=critical,CA:true\n' +
68
+ 'keyUsage=critical,keyCertSign,cRLSign,digitalSignature\n' +
69
+ 'subjectKeyIdentifier=hash\n' +
70
+ 'authorityKeyIdentifier=keyid:always,issuer\n');
71
+ await sh('openssl', ['req', '-new', '-key', keyTmp, '-out', csr, '-subj', '/CN=barebox-ca']);
72
+ await sh('openssl', ['x509', '-req', '-in', csr, '-signkey', keyTmp, '-sha256', '-days', '825',
73
+ '-out', certTmp, '-extfile', ext]);
74
+ renameSync(keyTmp, keyPath);
75
+ renameSync(certTmp, certPath);
71
76
  } finally {
72
- rmSync(join(dir, 'ca.csr.tmp'), { force: true });
73
- rmSync(ext, { force: true });
77
+ for (const f of [csr, ext, keyTmp, certTmp]) rmSync(f, { force: true });
74
78
  }
75
79
  return { keyPath, certPath };
76
80
  }
@@ -89,10 +93,11 @@ export async function certFor(dir, host) {
89
93
  const { readFileSync } = await import('node:fs');
90
94
  const keyPath = join(dir, `${host}.key`);
91
95
  const certPath = join(dir, `${host}.pem`);
92
- if (existsSync(keyPath) && existsSync(certPath)) {
96
+ // In-flight first: while a mint runs, nothing is read from disk.
97
+ let p = inflight.get(host);
98
+ if (!p && existsSync(keyPath) && existsSync(certPath)) {
93
99
  return { key: readFileSync(keyPath), cert: readFileSync(certPath) };
94
100
  }
95
- let p = inflight.get(host);
96
101
  if (!p) {
97
102
  p = withMintSlot(() => mint(dir, host, keyPath, certPath)).finally(() => { inflight.delete(host); });
98
103
  inflight.set(host, p);
@@ -106,24 +111,29 @@ async function mint(dir, host, keyPath, certPath) {
106
111
  // A crashed mint must not leave half a pair behind that later reads as valid.
107
112
  rmSync(keyPath, { force: true });
108
113
  rmSync(certPath, { force: true });
109
- await sh('openssl', ['genrsa', '-out', keyPath, '2048']);
110
- chmodSync(keyPath, 0o600);
114
+ // Temp names, then rename key first and cert last: the final names exist
115
+ // only as a complete pair.
116
+ const keyTmp = `${keyPath}.tmp`;
117
+ const certTmp = `${certPath}.tmp`;
111
118
  const san = /^\d+\.\d+\.\d+\.\d+$/.test(host) ? `IP:${host}` : `DNS:${host}`;
112
119
  const ext = join(dir, `${host}.ext.tmp`);
113
120
  const csr = join(dir, `${host}.csr.tmp`);
114
- writeFileSync(ext,
115
- 'basicConstraints=CA:false\n' +
116
- 'keyUsage=digitalSignature,keyEncipherment\n' +
117
- 'extendedKeyUsage=serverAuth\n' +
118
- `subjectAltName=${san}\n`);
119
- const { keyPath: caKey, certPath: caCert } = await ensureCA(dir);
120
121
  try {
121
- await sh('openssl', ['req', '-new', '-key', keyPath, '-out', csr, '-subj', `/CN=${host}`]);
122
+ await sh('openssl', ['genrsa', '-out', keyTmp, '2048']);
123
+ chmodSync(keyTmp, 0o600);
124
+ writeFileSync(ext,
125
+ 'basicConstraints=CA:false\n' +
126
+ 'keyUsage=digitalSignature,keyEncipherment\n' +
127
+ 'extendedKeyUsage=serverAuth\n' +
128
+ `subjectAltName=${san}\n`);
129
+ const { keyPath: caKey, certPath: caCert } = await ensureCA(dir);
130
+ await sh('openssl', ['req', '-new', '-key', keyTmp, '-out', csr, '-subj', `/CN=${host}`]);
122
131
  await sh('openssl', ['x509', '-req', '-in', csr, '-CA', caCert, '-CAkey', caKey,
123
- '-set_serial', '0x' + randomBytes(16).toString('hex'), '-days', '825', '-sha256', '-out', certPath, '-extfile', ext]);
132
+ '-set_serial', '0x' + randomBytes(16).toString('hex'), '-days', '825', '-sha256', '-out', certTmp, '-extfile', ext]);
133
+ renameSync(keyTmp, keyPath);
134
+ renameSync(certTmp, certPath);
124
135
  } finally {
125
- rmSync(csr, { force: true });
126
- rmSync(ext, { force: true });
136
+ for (const f of [csr, ext, keyTmp, certTmp]) rmSync(f, { force: true });
127
137
  }
128
138
  return { key: readFileSync(keyPath), cert: readFileSync(certPath) };
129
139
  }
package/src/lists.js ADDED
@@ -0,0 +1,77 @@
1
+ // lists.js — the one owner of "does this request match an endpoint list?".
2
+ //
3
+ // A list is entries like `"POST gmail.googleapis.com/gmail/v1/users/{userId}/messages/send"`:
4
+ // `{name}` matches one path segment, everything else is exact. It is built on
5
+ // rwxmap's matcher with one sidecar per host (every row of a sidecar applies to
6
+ // every server in it). The host is checked in a Map first: rwxmap's `match()` runs
7
+ // a classifier on every miss, and most requests are for hosts on no list.
8
+ import { matcherFrom } from 'rwxmap/match';
9
+
10
+ const METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'];
11
+
12
+ /**
13
+ * The one place a request URL is normalised: one trailing dot is stripped from the
14
+ * host (`api.anthropic.com.` is `api.anthropic.com`). Throws like `URL` on a non-URL.
15
+ *
16
+ * @param {string} url full request URL
17
+ * @returns {string} the normalised URL
18
+ */
19
+ export function normalizeUrl(url) {
20
+ const u = new URL(url);
21
+ if (u.hostname.endsWith('.')) u.hostname = u.hostname.slice(0, -1);
22
+ return u.href;
23
+ }
24
+
25
+ /**
26
+ * @param {string} entry `"METHOD host[:port]/path"`
27
+ * @returns {{ method: string, host: string, path: string }} the parts; throws on a bad entry
28
+ */
29
+ function parseEntry(entry) {
30
+ const bad = (why) => new Error(`endpoint list: ${JSON.stringify(entry)}: ${why}`);
31
+ if (typeof entry !== 'string') throw bad('must be a string');
32
+ const sp = entry.indexOf(' ');
33
+ const method = sp < 0 ? '' : entry.slice(0, sp);
34
+ if (!METHODS.includes(method)) throw bad(`method must be one of ${METHODS.join(' ')} (upper case)`);
35
+ const rest = entry.slice(sp + 1).trim();
36
+ if (rest.includes('://')) throw bad('no scheme');
37
+ if (rest.includes('*')) throw bad('no `*` (host patterns are not supported)');
38
+ const slash = rest.indexOf('/');
39
+ const host = slash < 0 ? rest : rest.slice(0, slash);
40
+ if (!host) throw bad('host must not be empty');
41
+ if (/:(443|80)$/.test(host)) throw bad('drop the default port (:443/:80); the URL host never carries it');
42
+ if (host !== host.toLowerCase()) throw bad('host must be lower case');
43
+ if (slash < 0) throw bad('path must start with /');
44
+ return { method, host, path: rest.slice(slash) };
45
+ }
46
+
47
+ /**
48
+ * Build an endpoint list.
49
+ *
50
+ * @param {string[]} entries `"METHOD host[:port]/path"` strings
51
+ * @param {typeof matcherFrom} [makeMatcher] builds one host's matcher (a test counts its `match` calls)
52
+ * @returns {{ match: (method: string, url: string) => string | null }} `match` returns the matched entry, else `null`
53
+ */
54
+ export function endpointList(entries, makeMatcher = matcherFrom) {
55
+ /** @type {Map<string, any[]>} */
56
+ const rowsByHost = new Map();
57
+ for (const entry of entries) {
58
+ const { method, host, path } = parseEntry(entry);
59
+ const rows = rowsByHost.get(host) ?? [];
60
+ rowsByHost.set(host, rows);
61
+ rows.push({ key: entry, method, path, letter: 'r', marker: 'settled' });
62
+ }
63
+ // One sidecar per host, never one for all of them.
64
+ const byHost = new Map();
65
+ for (const [host, hostRows] of rowsByHost) {
66
+ byHost.set(host, makeMatcher([{ vendor: '', servers: [`https://${host}`], rows: hostRows }]));
67
+ }
68
+ return {
69
+ match(method, url) {
70
+ const u = new URL(normalizeUrl(url));
71
+ const m = byHost.get(u.host);
72
+ if (!m) return null;
73
+ const r = m.match(method, u.href);
74
+ return r.source === 'spec' ? r.key : null;
75
+ },
76
+ };
77
+ }
package/src/policy.js CHANGED
@@ -13,6 +13,8 @@
13
13
  // is `flags`: it asks in every mode, trust included.
14
14
  import { Gate } from 'bareguard';
15
15
  import { matcherFrom } from 'rwxmap/match';
16
+ import { requestKey } from 'rwxmap/discover';
17
+ import { endpointList, normalizeUrl } from './lists.js';
16
18
 
17
19
  /** The mode names, in the order the CLI and config list them. */
18
20
  export const MODES = ['ask', 'auto', 'trust'];
@@ -34,21 +36,47 @@ const TOOLS = {
34
36
  'http.DELETE': 'x',
35
37
  };
36
38
 
37
- /** Model-call endpoints per host (`host[:port]`); each is `POST` and reads (`r`). */
38
- const MODEL_PATHS = {
39
- 'api.anthropic.com': ['/v1/messages', '/v1/messages/count_tokens'],
40
- 'api.openai.com': ['/v1/chat/completions', '/v1/responses', '/v1/embeddings'],
41
- };
39
+ /** Built-in model-call endpoints (`POST`, `r`), as endpoint-list entries. */
40
+ const MODEL_PATHS = [
41
+ 'POST api.anthropic.com/v1/messages',
42
+ 'POST api.anthropic.com/v1/messages/count_tokens',
43
+ 'POST api.openai.com/v1/chat/completions',
44
+ 'POST api.openai.com/v1/responses',
45
+ 'POST api.openai.com/v1/embeddings',
46
+ ];
47
+ /** The endpoints of one local model server (`host:port`), as list entries. */
42
48
  const LOCAL_LLM_PATHS = ['/api/chat', '/api/generate', '/api/embed',
43
49
  '/v1/chat/completions', '/v1/completions'];
44
50
 
51
+ /** @param {string[]} localLlm `host:port` pairs @returns {string[]} every model endpoint entry */
52
+ function modelEntries(localLlm) {
53
+ const entries = [...MODEL_PATHS];
54
+ for (const hp of localLlm) for (const p of LOCAL_LLM_PATHS) entries.push(`POST ${hp.toLowerCase().replace(/:(80|443)$/, '')}${p}`);
55
+ return entries;
56
+ }
57
+
58
+ /** @param {string} entry `"POST host/path"` @returns {string} the model tool name for it (`<host>.POST <path>`) */
59
+ function modelToolName(entry) {
60
+ const sp = entry.indexOf(' ');
61
+ return requestKey(entry.slice(0, sp), `https://${entry.slice(sp + 1)}`);
62
+ }
63
+
64
+ /**
65
+ * The model endpoints as one endpoint list (the built-ins plus each local server).
66
+ *
67
+ * @param {string[]} [localLlm] `host:port` pairs of local model servers
68
+ * @returns {{ match: (method: string, url: string) => string | null }} matches to the entry string
69
+ */
70
+ export function modelList(localLlm = []) {
71
+ return endpointList(modelEntries(localLlm));
72
+ }
73
+
45
74
  /** The matcher used when no label files are loaded: every request is request-only. */
46
75
  export const emptyMatcher = matcherFrom([]);
47
76
 
48
77
  /**
49
78
  * The one tools table of a runtime: the `http.*` tools, the model endpoints
50
- * (`r`) and the label tools. Model keys come from `matcher.match()` itself so
51
- * there is no second key builder.
79
+ * (`r`) and the label tools. Model keys come from rwxmap's `requestKey`.
52
80
  *
53
81
  * @param {Record<string, any>} [labelTools] the label files' gate-file tools (`{ key: { letter, marker } }`)
54
82
  * @param {string[]} [localLlm] `host:port` pairs of local model servers
@@ -63,13 +91,7 @@ export function buildTools(labelTools = {}, localLlm = []) {
63
91
 
64
92
  /** @param {string[]} localLlm @returns {Set<string>} every model endpoint's tool key */
65
93
  function modelKeys(localLlm) {
66
- const keys = new Set();
67
- const add = (scheme, host, paths) => {
68
- for (const p of paths) keys.add(emptyMatcher.match('POST', `${scheme}://${host}${p}`).key);
69
- };
70
- for (const [host, paths] of Object.entries(MODEL_PATHS)) add('https', host, paths);
71
- for (const hp of localLlm) add('http', hp, LOCAL_LLM_PATHS);
72
- return keys;
94
+ return new Set(modelEntries(localLlm).map(modelToolName));
73
95
  }
74
96
 
75
97
  /**
@@ -87,22 +109,33 @@ export function modelTools(labelTools = {}, localLlm = []) {
87
109
  }
88
110
 
89
111
  /**
90
- * The tool name for one request. A spec key (a label file documents it) is
91
- * used as is, even if the gate file lacks it (then the gate denies it:
92
- * fail closed). A request-only key is used only when it is a known model
93
- * endpoint; everything else is `http.<METHOD>`. Never the matcher's letter.
112
+ * The tool name for one request, in order: a spec key (a label file documents
113
+ * it) is used as is, even if the gate file lacks it (then the gate denies it:
114
+ * fail closed); else a model endpoint's name when the tools table has it; else
115
+ * `http.<METHOD>`. Never the matcher's letter. The host is normalised once
116
+ * (`normalizeUrl`).
94
117
  *
95
118
  * @param {{ match: (method: string, url: string) => { key: string, source: string } }} matcher
96
119
  * @param {Record<string, any>} tools the runtime's tools table
97
120
  * @param {string} method HTTP method
98
121
  * @param {string} url full request URL
122
+ * @param {{ match: (method: string, url: string) => string | null }} models the runtime's model list (`modelList(localLlm)`); required, no default
99
123
  * @returns {string} the tool name
100
124
  */
101
- export function toolFor(matcher, tools, method, url) {
125
+ export function toolFor(matcher, tools, method, url, models) {
126
+ let norm;
102
127
  try {
103
- const r = matcher.match(method, url);
104
- if (r.source === 'spec' || Object.hasOwn(tools, r.key)) return r.key;
105
- } catch { /* not an http(s) URL: fall through */ }
128
+ norm = normalizeUrl(url);
129
+ } catch { return `http.${method}`; } // not a URL
130
+ // rwxmap's match() throws on a non-http(s) URL (ftp://...), so it is checked here, not caught.
131
+ if (!/^https?:/.test(norm)) return `http.${method}`;
132
+ const r = matcher.match(method, norm);
133
+ if (r.source === 'spec') return r.key;
134
+ const entry = models.match(method, norm);
135
+ if (entry !== null) {
136
+ const name = modelToolName(entry);
137
+ if (Object.hasOwn(tools, name)) return name;
138
+ }
106
139
  return `http.${method}`;
107
140
  }
108
141
 
package/src/proxy.js CHANGED
@@ -20,8 +20,9 @@ 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
- import { paymentPath, toolFor, buildTools, modelTools, emptyMatcher } from './policy.js';
25
+ import { paymentPath, toolFor, buildTools, modelTools, modelList, emptyMatcher } from './policy.js';
25
26
  import { checkUpstream } from './wall.js';
26
27
  import { findPlaceholders, urlPlaceholders, applySecrets } from './secrets.js';
27
28
  import { Gate } from 'bareguard';
@@ -140,6 +141,7 @@ export function createProxy(opts) {
140
141
  const matcher = labels?.matcher ?? emptyMatcher;
141
142
  const tools = buildTools(labels?.tools, [...allowLocal]);
142
143
  const models = modelTools(labels?.tools, [...allowLocal]);
144
+ const modelEndpoints = modelList([...allowLocal]);
143
145
  if (!logFile) throw new Error('createProxy: logFile is required');
144
146
  if (typeof runtime !== 'string' || !runtime) throw new Error('createProxy: runtime is required');
145
147
  // One live proxy per runtime, enforced here: claimed before the hold
@@ -501,6 +503,7 @@ export function createProxy(opts) {
501
503
  * @property {number|null} status HTTP status the channel wants for a denial (null: 403)
502
504
  * @property {string|null} heldId id of the held body file, once spooled
503
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)
504
507
  */
505
508
 
506
509
  /**
@@ -607,7 +610,7 @@ export function createProxy(opts) {
607
610
  // Parked: the tunnel stays open until the ask channel decides.
608
611
  // null: the reservation already expired and onExpire refused.
609
612
  parked = queue.add({ agent, method: ctx.method, url: ctx.url,
610
- preview: bodyPreview(ctx.tee.head), bodyBytes: ctx.tee.bytes,
613
+ preview: bodyPreview(ctx.decodedHead ?? ctx.tee.head), bodyBytes: ctx.tee.bytes,
611
614
  sock, note: event.rule ?? 'ask', letter: event.rwxLetter, finish,
612
615
  slot, arrivedAt: slot.arrivedAt }) !== null;
613
616
  };
@@ -746,14 +749,16 @@ export function createProxy(opts) {
746
749
  /** @type {RequestCtx} */
747
750
  const ctx = { agent, method, url: urlStr, headers: { ...creq.headers }, creq, cres, tee,
748
751
  hasBody, chunks: [], over: false, freeWork, asked: false, status: null, heldId: null,
749
- endAsk: null };
752
+ endAsk: null, decodedHead: null };
750
753
  // A model call is never card-scanned (user decision, Nov 2); the floor keeps every other request.
751
- const tool = toolFor(matcher, tools, method, urlStr);
754
+ const tool = toolFor(matcher, tools, method, urlStr, modelEndpoints);
752
755
  let cardLike = false;
753
756
  if (hasBody) {
754
757
  if (await readWorkBody(ctx)) return;
755
758
  // Past 64 KB the body streams on unscanned (known gap).
756
- if (!ctx.over && !models.has(tool)) cardLike = createCardScanner().push(Buffer.concat(ctx.chunks));
759
+ if (!ctx.over && !models.has(tool)) {
760
+ cardLike = await scanBody(ctx);
761
+ }
757
762
  }
758
763
  // The body never goes in the action: bareguard writes the action to its audit file.
759
764
  const action = { type: 'net', tool, url: urlStr, method, agent,
@@ -849,6 +854,23 @@ export function createProxy(opts) {
849
854
  return false;
850
855
  }
851
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
+
852
874
  /**
853
875
  * Read a paused request's body until it ends or passes `limit` bytes
854
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
+ };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The one place a request URL is normalised: one trailing dot is stripped from the
3
+ * host (`api.anthropic.com.` is `api.anthropic.com`). Throws like `URL` on a non-URL.
4
+ *
5
+ * @param {string} url full request URL
6
+ * @returns {string} the normalised URL
7
+ */
8
+ export function normalizeUrl(url: string): string;
9
+ /**
10
+ * Build an endpoint list.
11
+ *
12
+ * @param {string[]} entries `"METHOD host[:port]/path"` strings
13
+ * @param {typeof matcherFrom} [makeMatcher] builds one host's matcher (a test counts its `match` calls)
14
+ * @returns {{ match: (method: string, url: string) => string | null }} `match` returns the matched entry, else `null`
15
+ */
16
+ export function endpointList(entries: string[], makeMatcher?: typeof matcherFrom): {
17
+ match: (method: string, url: string) => string | null;
18
+ };
19
+ import { matcherFrom } from 'rwxmap/match';
package/types/policy.d.ts CHANGED
@@ -1,7 +1,15 @@
1
+ /**
2
+ * The model endpoints as one endpoint list (the built-ins plus each local server).
3
+ *
4
+ * @param {string[]} [localLlm] `host:port` pairs of local model servers
5
+ * @returns {{ match: (method: string, url: string) => string | null }} matches to the entry string
6
+ */
7
+ export function modelList(localLlm?: string[]): {
8
+ match: (method: string, url: string) => string | null;
9
+ };
1
10
  /**
2
11
  * The one tools table of a runtime: the `http.*` tools, the model endpoints
3
- * (`r`) and the label tools. Model keys come from `matcher.match()` itself so
4
- * there is no second key builder.
12
+ * (`r`) and the label tools. Model keys come from rwxmap's `requestKey`.
5
13
  *
6
14
  * @param {Record<string, any>} [labelTools] the label files' gate-file tools (`{ key: { letter, marker } }`)
7
15
  * @param {string[]} [localLlm] `host:port` pairs of local model servers
@@ -18,15 +26,17 @@ export function buildTools(labelTools?: Record<string, any>, localLlm?: string[]
18
26
  */
19
27
  export function modelTools(labelTools?: Record<string, any>, localLlm?: string[]): Set<string>;
20
28
  /**
21
- * The tool name for one request. A spec key (a label file documents it) is
22
- * used as is, even if the gate file lacks it (then the gate denies it:
23
- * fail closed). A request-only key is used only when it is a known model
24
- * endpoint; everything else is `http.<METHOD>`. Never the matcher's letter.
29
+ * The tool name for one request, in order: a spec key (a label file documents
30
+ * it) is used as is, even if the gate file lacks it (then the gate denies it:
31
+ * fail closed); else a model endpoint's name when the tools table has it; else
32
+ * `http.<METHOD>`. Never the matcher's letter. The host is normalised once
33
+ * (`normalizeUrl`).
25
34
  *
26
35
  * @param {{ match: (method: string, url: string) => { key: string, source: string } }} matcher
27
36
  * @param {Record<string, any>} tools the runtime's tools table
28
37
  * @param {string} method HTTP method
29
38
  * @param {string} url full request URL
39
+ * @param {{ match: (method: string, url: string) => string | null }} models the runtime's model list (`modelList(localLlm)`); required, no default
30
40
  * @returns {string} the tool name
31
41
  */
32
42
  export function toolFor(matcher: {
@@ -34,7 +44,9 @@ export function toolFor(matcher: {
34
44
  key: string;
35
45
  source: string;
36
46
  };
37
- }, tools: Record<string, any>, method: string, url: string): string;
47
+ }, tools: Record<string, any>, method: string, url: string, models: {
48
+ match: (method: string, url: string) => string | null;
49
+ }): string;
38
50
  /**
39
51
  * True when the URL's path names a payment destination (the floor's
40
52
  * URL-visible half). An unparsable URL is not one.