barebox 0.9.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 +20 -0
- package/README.md +113 -96
- 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,26 @@ 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
|
+
|
|
18
|
+
## [0.10.0] - 2026-11-10
|
|
19
|
+
|
|
20
|
+
Docs only; no code or behaviour changes.
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
|
|
24
|
+
- README rewritten: what barebox is and its scope (up to 40 agents per proxy), how it works (one proxy for HTTP and HTTPS, one gate, one `gate.jsonl` audit file you can stream), how letters `r`/`w`/`x` are assigned and what each of the three modes lets through, what it blocks by default, real output samples (the terminal question, a run summary, an audit line), one table of measured numbers, known limits, and how to replay Demo A and Demo B from a clone. The roadmap section is removed.
|
|
25
|
+
- The PRD is split into a current spec and four reference pages (built modules M0-M7, evidence and memory budget, the hackathon plan, scope and questions); the previous version is archived unchanged. The spec now carries the post-hackathon build order (M8-M16) and the known gaps it closes.
|
|
26
|
+
|
|
7
27
|
## [0.9.0] - 2026-11-03
|
|
8
28
|
|
|
9
29
|
### Added
|
package/README.md
CHANGED
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
barebox
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
>
|
|
12
|
-
>
|
|
11
|
+
> A lightweight sandbox you spawn per agent, to control what it may do. Reads pass, file writes can be undone, and anything irreversible (pay, send, publish, push) waits for your yes.
|
|
12
|
+
> Many sandboxes, one proxy, one gate, one audit file. Up to 40 agents per proxy: for a laptop or a small VPS, not for big swarms.
|
|
13
13
|
|
|
14
14
|
<p align="center">
|
|
15
15
|
<img src="https://img.shields.io/github/package-json/v/hamr0/barebox?label=version&color=2a4f8c" alt="version (auto from package.json)">
|
|
@@ -17,118 +17,149 @@
|
|
|
17
17
|
<img src="https://img.shields.io/badge/platform-Linux-2a4f8c" alt="platform: Linux">
|
|
18
18
|
</p>
|
|
19
19
|
|
|
20
|
-
|
|
20
|
+

|
|
21
21
|
|
|
22
|
-
|
|
22
|
+
Demo A, a live unedited run: Meta's muse model books a trip. 31 requests, 23 went out with no question, 8 stopped for a person (3 allowed, 5 denied); the real payment key reached the server once, after a yes. Full captioned take: [assets/demo-a.webm](assets/demo-a.webm).
|
|
23
23
|
|
|
24
|
-
|
|
25
|
-
- **Heavy isolation.** Docker or a VM: images, a daemon, root, and the agent can't use your installed toolchain. Most people skip it.
|
|
24
|
+
**Replay it** (Linux, from a clone; needs network, httpbin.org stands in for the real services):
|
|
26
25
|
|
|
27
|
-
|
|
26
|
+
```
|
|
27
|
+
git clone https://github.com/hamr0/barebox && cd barebox && npm install
|
|
28
|
+
bash examples/demo-a/run.sh # Demo A scripted: book a trip, all three modes, every cell asserted
|
|
29
|
+
bash examples/demo-a/run.sh --driver muse --live --mode auto # the live run above; needs BASETEN_API_KEY, you answer the holds
|
|
30
|
+
bash examples/demo-b/run.sh # Demo B: a prompt-injected agent tries 3 exfiltrations in every mode
|
|
31
|
+
```
|
|
28
32
|
|
|
29
|
-
##
|
|
33
|
+
## How it works
|
|
30
34
|
|
|
31
|
-
|
|
35
|
+
```
|
|
36
|
+
agent (your real node, python, git, claude ...)
|
|
37
|
+
|
|
|
38
|
+
+-----+-------- bwrap sandbox (unprivileged, one per agent) --------+
|
|
39
|
+
| files: your project, read-only + an undo layer (--overlay) |
|
|
40
|
+
| locked: ~/.ssh, cloud creds, token files -> empty |
|
|
41
|
+
| network: none of its own; 127.0.0.1:3128 -> its unix socket |
|
|
42
|
+
+-----+-------------------------------------------------------------+
|
|
43
|
+
| one unix socket per agent (the socket is the identity, not a header)
|
|
44
|
+
v
|
|
45
|
+
ONE proxy, HTTP and HTTPS -> ONE gate (bareguard) -> world
|
|
46
|
+
| |
|
|
47
|
+
| '-> gate.jsonl, one audit line per decision
|
|
48
|
+
'-> held request: asks you in the terminal, forwards or 403
|
|
49
|
+
```
|
|
32
50
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
| `x` | can't be undone: send, pay, publish, push | holds it at the door until you decide | at the moment it happens |
|
|
51
|
+
- **Walls:** [bubblewrap](https://github.com/containers/bubblewrap), no root, no daemon, no image. The agent uses your installed tools.
|
|
52
|
+
- **One proxy for all sandboxes**, plain HTTP and HTTPS. HTTPS is read through a local CA that exists only inside the sandbox, so the gate sees method, URL, headers and body.
|
|
53
|
+
- **One gate decides every request** by its letter and the mode (below). It is a simple policy for spawning sandboxed agents on the fly: one flag, no rule files.
|
|
54
|
+
- **One audit file**, `<runtime>/gate.jsonl`, one JSON line per decision in [bareguard](https://github.com/hamr0/bareguard)'s shape. It is append-only, so `tail -f` it, pipe it to `jq`, or ship it to your log stack.
|
|
38
55
|
|
|
39
|
-
|
|
56
|
+
## r, w, x and the three modes
|
|
40
57
|
|
|
41
|
-
|
|
42
|
-
- **Locked drawers (r).** It reads most things. Keys and password stores (`~/.ssh`, `~/secrets`, `~/.gnupg`, `~/.password-store`, keyrings), browser profiles, cloud and cluster credentials (`~/.aws`, `~/.azure`, `~/.config/gcloud`, `~/.kube`, `~/.docker`, `~/.config/gh`, `~/.config/op`) and token files (`~/.netrc`, `~/.npmrc`, `~/.pypirc`, `~/.git-credentials`, `~/.cargo/credentials.toml`) stay shut. The agent's own model credentials (`~/.claude`) do not (a known gap: those tokens refresh themselves).
|
|
43
|
-
- **One front door with a doorman (x).** No network of its own. Lookups pass; anything that sends, pays, or publishes waits for your yes.
|
|
44
|
-
- **Keys it never holds.** The agent types a placeholder; the doorman puts the real API key in the request header only after the request is allowed, and only for the hosts that key is bound to. Your environment does not reach the sandbox.
|
|
58
|
+
Every request gets one letter:
|
|
45
59
|
|
|
46
|
-
|
|
60
|
+
| Letter | What | How barebox gets the letter |
|
|
61
|
+
|---|---|---|
|
|
62
|
+
| `r` | reads, changes nothing | `GET`, `HEAD`, and calls to model APIs (Anthropic, OpenAI, a `localLlm`) |
|
|
63
|
+
| `w` | a change that can be set back | only where an [rwxmap](https://github.com/hamr0/rwxmap) label for that API says so |
|
|
64
|
+
| `x` | can't be undone: send, pay, publish, push, delete | every other `POST`, `PUT`, `PATCH`, `DELETE`; any other method is denied |
|
|
47
65
|
|
|
48
|
-
|
|
49
|
-
- No Docker, no VM, no cluster, no cloud control plane. Your box or a cheap VPS.
|
|
50
|
-
- Not a content filter and not intent detection — the doorman sees requests, not intent. Cert-pinned apps, non-HTTP egress and UDP are denied, not inspected.
|
|
66
|
+
File writes are a separate layer: with `--overlay` every change lands on an undo layer, and at the end you `sbx diff`, `sbx commit` or `sbx rollback`.
|
|
51
67
|
|
|
52
|
-
|
|
68
|
+
The mode (`sbx run --mode ...`) picks which letters pass without asking:
|
|
69
|
+
|
|
70
|
+
| Mode | Passes | Asks |
|
|
71
|
+
|---|---|---|
|
|
72
|
+
| `ask` | `r` | `w`, `x` |
|
|
73
|
+
| `auto` (default) | `r`, `w` | `x` |
|
|
74
|
+
| `trust` | `r`, `w`, `x` | nothing |
|
|
75
|
+
|
|
76
|
+
**The floor asks in every mode, `trust` included:** a card number (Luhn) in a body of 64 KB or less, or a payment path (`/checkout`, `/payment`, `/orders`, `/purchase`).
|
|
77
|
+
|
|
78
|
+
## What it blocks by default
|
|
79
|
+
|
|
80
|
+
| Blocked | How |
|
|
81
|
+
|---|---|
|
|
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) |
|
|
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
|
+
| 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
|
+
| 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) |
|
|
87
|
+
| Answering its own questions | the ask and answer files live outside the sandbox and are masked from it |
|
|
88
|
+
|
|
89
|
+
## What you see
|
|
90
|
+
|
|
91
|
+
A held request asks in the terminal where you ran `sbx run` (`y` allows, anything else denies):
|
|
53
92
|
|
|
54
93
|
```
|
|
55
|
-
agent
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
| socat inside: 127.0.0.1:3128 -> per-agent unix socket |
|
|
63
|
-
+-----+------------------------------------------------------------+
|
|
64
|
-
| per-agent unix socket (the connection = the agent's identity)
|
|
65
|
-
v
|
|
66
|
-
ONE shared proxy (Node, in-process: rwxmap + bareguard)
|
|
67
|
-
|-- r -> forward
|
|
68
|
-
|-- x -> hold, ask the human, forward or 403
|
|
69
|
-
'-- unknown -> per-mode default
|
|
94
|
+
⏸ auto-agent-1 wants to SEND data to httpbin.org
|
|
95
|
+
Why: the address looks like a payment
|
|
96
|
+
URL: POST https://httpbin.org/anything/v1/payment_intents
|
|
97
|
+
Data: {"amount":35000,"currency":"usd"}
|
|
98
|
+
Allow? [y/N] (hold h1)
|
|
99
|
+
y
|
|
100
|
+
✓ allowed
|
|
70
101
|
```
|
|
71
102
|
|
|
72
|
-
|
|
73
|
-
- **Identity** is the socket, not a header the agent could fake. One socket per agent, all into one proxy.
|
|
74
|
-
- **HTTPS inspection** uses a local CA that exists only inside the sandbox; the proxy reads method, URL, headers and body, then forwards.
|
|
75
|
-
- **The doorman's x-rules**, strongest first: card numbers in the body (Luhn) → payment paths (`/checkout`, `/payment`, `/orders`, `/purchase`; a list of payment domains is not built) → rwxmap labels for known APIs → every other request by its letter and the mode (`ask`, `auto`, `trust`; see `barebox.context.md`). The card and payment floor asks in every mode, `trust` included (calls to the built-in model endpoints, Anthropic and OpenAI, and to a `localLlm` server are not card-scanned; a model API you label `r` yourself still is); card numbers are checked in bodies of 64 KB or less.
|
|
76
|
-
- **Approvals** are asked in the terminal where you ran `sbx run`, in plain words (`agent wants to SEND data to httpbin.org … Allow? [y/N]`); `y` allows, anything else denies. Name the sandbox (`sbx run --name docs-bot -- <cmd>`) and a second terminal can answer too (`sbx pending --name docs-bot`, `sbx approve <id> --name docs-bot`, `sbx deny <id> --name docs-bot`); the first answer wins. A hold waits until you answer by default; `sbx run --hold 120 -- <cmd>` (or the `holdTimeoutSec` config key) sets a deadline, and a timeout means deny, with a clear `403` reason. One held request per agent at a time: later ones wait in line (16 at most, then `429 hold queue full`), and any deadline counts from arrival. Unattended runs (cron, CI, no terminal) have nobody to answer, so pass `--hold <seconds>` or the first held request waits forever.
|
|
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; for unattended runs (cron, CI) pass `--hold <seconds>`, and a timeout is a deny. One held request per agent at a time; up to 16 more wait in line.
|
|
77
104
|
|
|
78
|
-
|
|
105
|
+
Demo A's end-of-run summary (from the recorded take):
|
|
79
106
|
|
|
80
|
-
|
|
107
|
+
```
|
|
108
|
+
-- what barebox decided:
|
|
109
|
+
total 31 requests to the network: 23 free, 8 held for you (3 allowed, 5 denied) (model calls included)
|
|
110
|
+
search 3 free
|
|
111
|
+
pay 1 held: 1 allowed
|
|
112
|
+
POST /anything/hotels/checkout 1 held: 0 allowed, 1 denied
|
|
113
|
+
DELETE /anything/bookings/old-123 1 held: 0 allowed, 1 denied
|
|
114
|
+
model calls 18 free (labelled read-only)
|
|
115
|
+
key swaps 1 (the real test key went into the header only after your yes; the agent only ever had the placeholder)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
An audit line from `gate.jsonl` (a POST held, then denied on timeout):
|
|
119
|
+
|
|
120
|
+
```json
|
|
121
|
+
{"ts":"2026-11-03T21:41:04.869Z","seq":8,"aid":"1a541f36","phase":"gate","action":{"type":"net","tool":"http.POST","url":"https://httpbin.org/post","method":"POST","agent":"rdme","rid":"r2"},"decision":"deny","rule":"rwx.ask","reason":"hold timeout"}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## Keys the agent never holds
|
|
81
125
|
|
|
82
126
|
```json
|
|
83
127
|
{
|
|
84
128
|
"secrets": {
|
|
85
129
|
"STRIPE_API_KEY": { "fromEnv": "REAL_STRIPE_KEY", "hosts": ["api.stripe.com"] }
|
|
86
|
-
}
|
|
87
|
-
"env": { "pass": ["MY_TOOL_HOME"] }
|
|
130
|
+
}
|
|
88
131
|
}
|
|
89
132
|
```
|
|
90
133
|
|
|
91
|
-
|
|
134
|
+
In `~/.config/barebox/config.json`. Inside, `$STRIPE_API_KEY` is a random placeholder, new each run, and the agent uses it like the key (`curl -H "Authorization: Bearer $STRIPE_API_KEY" ...`). The real value goes into the request header only after the gate allows it, only to `api.stripe.com`, only over HTTPS. Anywhere else the placeholder is refused (`403 denied: secret.host`, `secret.scheme`, `secret.url`).
|
|
92
135
|
|
|
93
136
|
## Numbers
|
|
94
137
|
|
|
95
|
-
Measured, not estimated
|
|
138
|
+
Measured, not estimated: Fedora, kernel 7.2, bubblewrap 0.12.0, Node 22. Method and raw runs: [findings](docs/logs/findings.md).
|
|
96
139
|
|
|
97
|
-
| | barebox
|
|
140
|
+
| | barebox | [srt](https://github.com/anthropic-experimental/sandbox-runtime) 0.0.81 |
|
|
98
141
|
|---|---|---|
|
|
99
|
-
| Memory per sandbox | **7.8 MB** mean, 8.0 MB max | ~100 MB (
|
|
100
|
-
|
|
|
101
|
-
|
|
|
102
|
-
|
|
|
103
|
-
|
|
|
104
|
-
|
|
|
105
|
-
|
|
|
106
|
-
|
|
107
|
-
**What the demos show** (scripts in `examples/`, run by hand, every cell asserted):
|
|
108
|
-
|
|
109
|
-

|
|
110
|
-
|
|
111
|
-
The full 92-second take, captioned: [assets/demo-a.webm](assets/demo-a.webm).
|
|
142
|
+
| Memory per sandbox | **7.8 MB** mean, 8.0 MB max | ~100 MB (a proxy per sandbox) |
|
|
143
|
+
| Shared proxy, normal use (HTTPS, 10-40 agents) | **95-160 MB** | one per sandbox |
|
|
144
|
+
| Shared proxy, worst case (HTTPS, every agent with a held request, a full line and a full body slot) | **117 / 133-151 / 177-207 / 207-241 MB** at 10 / 20 / 30 / 40 agents | |
|
|
145
|
+
| Total, worst case (proxy + walls) | ~195-200 MB at 10, ~295-310 MB at 20, ~525-560 MB at 40 agents | ~1 GB at 10, ~2 GB at 20 |
|
|
146
|
+
| Start to exit, `sbx run -- true` | **0.70 s** median (0.80 s with `--overlay`; bwrap alone 6 ms) | 1.87-2.05 s |
|
|
147
|
+
| One real agent (Claude Code) | 248 MB inside vs 249 MB bare; barebox adds ~91 MB for the first agent, ~11 MB per further one | not measured |
|
|
148
|
+
| Agents per proxy | **40 max**, enforced (the 41st is refused; run another proxy) | |
|
|
149
|
+
| Demo B, 3 exfiltration attempts | **3 of 3 blocked** in every mode | |
|
|
112
150
|
|
|
113
|
-
|
|
114
|
-
- **Demo B, a prompt-injected agent.** In every mode (`ask`, `auto`, `trust`) all three exfiltration attempts fail: `~/.ssh` reads empty, the POST to the attacker's host is refused, a direct socket has no route. The good edits are committed and the injected agent's edits rolled back.
|
|
151
|
+
Ranges run from a quiet machine to a busy one.
|
|
115
152
|
|
|
116
|
-
|
|
153
|
+
## Known limits
|
|
117
154
|
|
|
118
|
-
|
|
155
|
+
barebox is a guardrail against mistakes and prompt-injected agents, not a security boundary against a determined attacker: the kernel is shared, so use a VM for that. Known gaps, each with a planned fix in [the PRD](docs/product/agent-sandbox-prd.md) (section 10):
|
|
119
156
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
| M4 | Undo layer: `diff`, `commit`, `rollback`, conflict flagging |
|
|
127
|
-
| M5 | Keys the agent never holds |
|
|
128
|
-
| M6 | Scale run: 20 agents + shared proxy |
|
|
129
|
-
| M7 | Demos: payment held for approval; prompt-injected `~/.ssh` exfil blocked |
|
|
130
|
-
|
|
131
|
-
M0–M2 are the go/no-go. Later: macOS (`sandbox-exec` + APFS clones), Windows via WSL2, Landlock/seccomp hardening. Full spec: [the PRD](docs/product/agent-sandbox-prd.md).
|
|
157
|
+
- Data in a `GET` URL goes out free: reads are `r`.
|
|
158
|
+
- The proxy resolves DNS before the gate decides, so data hidden in a hostname can leak.
|
|
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.
|
|
161
|
+
- `~/.claude` stays readable: Claude Code's tokens refresh themselves.
|
|
162
|
+
- Writes over local sockets (a Postgres, a Docker daemon) are not on the undo layer.
|
|
132
163
|
|
|
133
164
|
## Install
|
|
134
165
|
|
|
@@ -136,19 +167,7 @@ M0–M2 are the go/no-go. Later: macOS (`sandbox-exec` + APFS clones), Windows v
|
|
|
136
167
|
npm install barebox
|
|
137
168
|
```
|
|
138
169
|
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
## Try the POCs
|
|
142
|
-
|
|
143
|
-
Linux only, with `bwrap` (>= 0.11.0 only for the overlay), `socat`, `openssl`, Node >= 22.21 and Python 3. Needs a normal shell (namespaces + listening sockets), not a tool sandbox. The POCs are throwaway proofs, not the product.
|
|
144
|
-
|
|
145
|
-
```
|
|
146
|
-
git clone https://github.com/hamr0/barebox && cd barebox
|
|
147
|
-
npm run poc:m0 # 20 sandboxes, bypass suite
|
|
148
|
-
npm run redteam:m0 # breaks each wall on purpose; passes iff all detected
|
|
149
|
-
bash poc/m1/run-m1.sh local # HTTPS inspection against a local TLS echo server
|
|
150
|
-
bash poc/m1/run-m1.sh real # same, real internet, incl. git over https
|
|
151
|
-
```
|
|
170
|
+
Linux. Node.js >= 22.21, `bwrap`, `socat`, `openssl`; bubblewrap >= 0.11.0 for `--overlay` (Ubuntu 24.04 ships 0.9.0). Two dependencies, [bareguard](https://npmjs.com/package/bareguard) and [rwxmap](https://npmjs.com/package/rwxmap), pinned exactly. The `sbx` CLI comes with it; the API is in [`barebox.context.md`](barebox.context.md).
|
|
152
171
|
|
|
153
172
|
## The bare ecosystem
|
|
154
173
|
|
|
@@ -159,7 +178,7 @@ mix and match, each module works standalone.
|
|
|
159
178
|
|
|
160
179
|
- **[bareagent](https://npmjs.com/package/bare-agent)** — the think→act→observe loop. *Goal in → coordinated actions out.* Replaces LangChain, CrewAI, AutoGen.
|
|
161
180
|
- **[bareguard](https://npmjs.com/package/bareguard)** — the single gate every action passes through. *Action in → allow / deny / ask-a-human out. Work in → green / red.* Replaces hand-rolled allowlists and scattered policy code.
|
|
162
|
-
- **[barebox](https://github.com/hamr0/barebox)**
|
|
181
|
+
- **[barebox](https://github.com/hamr0/barebox)** — the walls and the front door, this repo. *Agent in → contained run out: writes undoable, irreversible actions held for a human.* Replaces Docker/VM isolation and approve-everything prompts.
|
|
163
182
|
- **[litectx](https://npmjs.com/package/litectx)** — tree-sitter code + memory graph with activation decay, plus lightweight context engineering (write · select · compress · isolate). *Query in → ranked context out.*
|
|
164
183
|
|
|
165
184
|
**Add-on for bareguard** — labels API operations for the gate.
|
|
@@ -172,8 +191,6 @@ mix and match, each module works standalone.
|
|
|
172
191
|
- **[baremobile](https://npmjs.com/package/baremobile)** — Android + iOS device control. *Screen in → pruned snapshot out.* Replaces Appium, Espresso, XCUITest.
|
|
173
192
|
- **[beeperbox](https://github.com/hamr0/beeperbox)** — 50+ messaging networks via one MCP server (headless Beeper Desktop in Docker). *Chat in → unified message stream out.* Replaces Twilio, per-platform bot APIs.
|
|
174
193
|
|
|
175
|
-
bareguard decides the action; barebox contains where it runs.
|
|
176
|
-
|
|
177
194
|
## License
|
|
178
195
|
|
|
179
196
|
Apache 2.0. See [LICENSE](LICENSE).
|
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.
|
|
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.
|