barebox 0.10.0 → 0.10.1
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 +11 -0
- package/barebox.context.md +4 -3
- package/package.json +3 -3
- package/src/certs.js +39 -29
- package/src/lists.js +77 -0
- package/src/policy.js +55 -22
- package/src/proxy.js +3 -2
- package/types/lists.d.ts +19 -0
- package/types/policy.d.ts +19 -7
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,17 @@ 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.10.1] - 2026-11-11
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
- bareguard 0.34.0 and rwxmap 0.11.1, pinned exactly; no behaviour change in barebox.
|
|
12
|
+
|
|
13
|
+
### Fixed
|
|
14
|
+
|
|
15
|
+
- 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.
|
|
16
|
+
- 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.
|
|
17
|
+
|
|
7
18
|
## [0.10.0] - 2026-11-10
|
|
8
19
|
|
|
9
20
|
Docs only; no code or behaviour changes.
|
package/barebox.context.md
CHANGED
|
@@ -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`.
|
|
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.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "barebox",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.1",
|
|
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.
|
|
54
|
-
"rwxmap": "0.
|
|
53
|
+
"bareguard": "0.34.0",
|
|
54
|
+
"rwxmap": "0.11.1"
|
|
55
55
|
}
|
|
56
56
|
}
|
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
|
-
|
|
58
|
-
|
|
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', ['
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
'
|
|
70
|
-
'
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
110
|
-
|
|
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', ['
|
|
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',
|
|
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
|
-
|
|
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
|
-
/**
|
|
38
|
-
const MODEL_PATHS =
|
|
39
|
-
'api.anthropic.com
|
|
40
|
-
'api.
|
|
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 `
|
|
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
|
-
|
|
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
|
|
91
|
-
* used as is, even if the gate file lacks it (then the gate denies it:
|
|
92
|
-
* fail closed)
|
|
93
|
-
*
|
|
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
|
-
|
|
104
|
-
|
|
105
|
-
|
|
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
|
@@ -21,7 +21,7 @@ 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
23
|
import { claimRuntime, ensurePrivateDir, runtimePaths } from './runtime.js';
|
|
24
|
-
import { paymentPath, toolFor, buildTools, modelTools, emptyMatcher } from './policy.js';
|
|
24
|
+
import { paymentPath, toolFor, buildTools, modelTools, modelList, emptyMatcher } from './policy.js';
|
|
25
25
|
import { checkUpstream } from './wall.js';
|
|
26
26
|
import { findPlaceholders, urlPlaceholders, applySecrets } from './secrets.js';
|
|
27
27
|
import { Gate } from 'bareguard';
|
|
@@ -140,6 +140,7 @@ export function createProxy(opts) {
|
|
|
140
140
|
const matcher = labels?.matcher ?? emptyMatcher;
|
|
141
141
|
const tools = buildTools(labels?.tools, [...allowLocal]);
|
|
142
142
|
const models = modelTools(labels?.tools, [...allowLocal]);
|
|
143
|
+
const modelEndpoints = modelList([...allowLocal]);
|
|
143
144
|
if (!logFile) throw new Error('createProxy: logFile is required');
|
|
144
145
|
if (typeof runtime !== 'string' || !runtime) throw new Error('createProxy: runtime is required');
|
|
145
146
|
// One live proxy per runtime, enforced here: claimed before the hold
|
|
@@ -748,7 +749,7 @@ export function createProxy(opts) {
|
|
|
748
749
|
hasBody, chunks: [], over: false, freeWork, asked: false, status: null, heldId: null,
|
|
749
750
|
endAsk: null };
|
|
750
751
|
// 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);
|
|
752
|
+
const tool = toolFor(matcher, tools, method, urlStr, modelEndpoints);
|
|
752
753
|
let cardLike = false;
|
|
753
754
|
if (hasBody) {
|
|
754
755
|
if (await readWorkBody(ctx)) return;
|
package/types/lists.d.ts
ADDED
|
@@ -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 `
|
|
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
|
|
22
|
-
* used as is, even if the gate file lacks it (then the gate denies it:
|
|
23
|
-
* fail closed)
|
|
24
|
-
*
|
|
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
|
|
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.
|