Compare commits

..
13 Commits
Author SHA1 Message Date
dckcandClaude Opus 5.5 e5ed407e55 capsite/toybox: a mount outlives its handler: the vat restarts on demand
A handler is a live reference, held by the VatAdmin DO; workerd evicts
an idle DO within seconds, and with it the handler, so a vat's page went
503 almost at once.

createVat now keeps a vat's params when they hold only data and
ingresses (an ingress by its key: the VatAdmin can make it again), and
which vat was given which ingress. A request for a mount with no handler
restarts that vat with its params; it rebuilds its root, serves again,
and the request is answered. A vat whose params hold another peer's
objects isn't restartable yet.

The test crashes its own toybox (a crash ends every session to it), and
the creator waits for the root's handoff before it disconnects, as
scripts/hello.js now does too.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 21:44:29 -05:00
dckcandClaude Opus 5.5 a984461cee capsite/toybox: ingress is a capability; a hello-world web vat
E(vatAdmin).makeIngress(labels) reserves a mount and returns an ingress;
whoever holds it serves requests carrying those labels by calling
E(ingress).serve(handler). A vat gets one in its params, like any other
remote object; nothing in a vat's module is an entrypoint. A request
reaches the handler as passable data (method, path, labels, body), and
the response comes back as data (status, headers, body). The handler is
a live reference for now: after a restart its mount answers 503.

vats/hello.js serves hello, world; pnpm hello creates it on a running
toybox (client.js is the Node OCapN client, shared with the tests).

pnpm start and pnpm switchboard never ran: systemd-socket-activate wants
absolute paths for unix sockets.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 21:44:29 -05:00
dckcandClaude Opus 5.5 8025ec4b20 capsite/toybox: TODO: the counter vat as a durable Exo
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 21:44:29 -05:00
dckcandClaude Opus 5.5 f64dac4434 capsite/toybox: an OCapN counter vat; no import GC in workerd peers
vats/counter.js keeps its count in the vat's storage; the test checks
that it counts and that two counter vats count apart.

Running it after the greeter test hung: a FinalizationRegistry callback
in the vatAdmin, collecting an import, sent op:gc over the client's
WebSocket, and workerd forbids I/O outside a request. The vatAdmin's and
the vats' OCapN clients now run with enableImportCollection: false, so
imports go when their session does.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 21:44:29 -05:00
dckcandClaude Opus 5.5 193a126d1c capsite/toybox: routing carries no secrets
The ingress no longer reads labels from a Toybox-Labels header. A header
was no place for the webkey pattern: browsers can't set one on a
WebSocket, and the pattern puts the secret in-band anyway. A page keeps
it in its fragment, reaches the vat by public labels, and sends it in
the body of a call, which the vat checks like a swissnum.

A request still reaches a vat only by naming every label of its mount.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 21:44:29 -05:00
dckcandClaude Opus 5.5 28b1c3c9d3 capsite/toybox: no encoder object in module scope
A module-level TextEncoder is a mutable object every importer shares.
Keep only its encode method, bound and hardened; the encoder itself is
unreachable. The code hash uses it too.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 21:44:29 -05:00
dckcandClaude Opus 5.5 7fcd251261 capsite/toybox: mount lookups in SQL, not a scan in JS
Each request parsed every mount's labels and searched them in JS. Labels
now sit one per row in mount_label, indexed on (key, value): a lookup
joins the request's labels (json_each) on the index and keeps the vat
whose every label matched. The overlap check at registration is SQL too.

mount.labels keeps the whole set as JSON; mounts stored before
mount_label get their rows filled in when the schema runs. The SQL lives
in mounts-sql.js, tested on node:sqlite, old-shape state included.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 21:44:29 -05:00
dckcandClaude Opus 5.5 9356f63c64 capsite/toybox: OCapN vats; createVat takes remote objects
The admin socket now also speaks OCapN over Cap'n Web: a WebSocket there
reaches the VatAdmin DO, an OCapN peer whose bootstrap (swissnum
vatAdmin) offers createVat(src, params). params may hold remote objects;
the vat's root comes back as one.

Each OCapN vat is its own peer: SES and @endo/ocapn run in its facet
(vat-runtime.js, bundled with esbuild), around the vat's own module,
which exports buildRootObject(vatPowers, params). Passing a client's
object to a vat, or a vat's root to the client, is an OCapN handoff, so
the receiver dials the exporter. Nothing here can dial out, so the
VatAdmin is also the router: a client registers its gateway under a
designator, a vat's designator is its id, and every peer reaches every
other through it. The netlayer is ertp-clerk's, made to work over Workers
RPC stubs and plain promises as well as Cap'n Web.

Not yet: sturdyrefs that survive a restart, an adminNode, and grants
(egress, mount) for OCapN vats. App vats (export class App) still work
beside them.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 21:44:29 -05:00
dckcandClaude Opus 5.5 8d8900d84d capsite/toybox: vats have ids, not names; ingress by mount
createVat (POST / on the admin socket) makes a vat with newUniqueId and
returns its id, which addresses it only there. A vat is reachable only
where it is mounted: ?mount=<labels> on each start, as ?egress= is
granted; absent means none.

The ingress reads a request's labels from its query string, plus a
Toybox-Labels header for secret ones (a URL ends up in logs and
Referers). It routes to the vat whose mount labels the request carries,
every one: stricter than Flower's no-conflict match, since an ingress
client holds no constrained handle and a label it omits must not match.
Registration keeps Flower's rule, so a mount must conflict with every
other and no request can carry two. The app keeps the whole path and
sees its connection labels in Toybox-Connection-Labels.

A vat from before ids lives at idFromName(name). PUT /by-name/<name>
reaches it on the admin socket; it stays unreachable from outside until
mounted.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 21:44:29 -05:00
dckcandClaude Opus 5.5 f0557d29d6 capsite/toybox: egress through Flower-style switchboard handles
The switchboard now serves a Cap'n Web Handle on each of its sockets:
public (no loopback or private addresses) and local. A socket's labels
are fixed in config, so holding the socket's fd is holding that handle;
constrain(labels) returns a narrower one, as Flower's Constrain returns
a narrower fd. Labels only accumulate: a missing key matches anything,
and a key both sides set must agree (labels.js, shared by both).

The switchboard enforces the labels; toybox's Egress no longer checks
URLs itself. It opens a session to its one switchboard socket, constrains
the handle to the vat's grant, and forwards through it; a WebSocket
crosses the session as a pair of message streams. A vat narrows its own
grant with env.egress.constrain().

Grants are now labels as JSON. One stored before, a bare host[:port],
reads as {host, port}.

pnpm start and the systemd units give toybox the public handle; the
switchboard unit binds the local one in its own 0700 runtime directory.
The tests give their toybox the local handle to reach an echo server,
and check that a toybox holding only the public one never reaches it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 21:44:29 -05:00
dckcandClaude Opus 5.5 2820c015ee capsite/toybox: a grant is an object in env, not the vat's global fetch
A vat's globalOutbound is now always null. A granted host arrives as
env.egress, an Egress the app can hand to whichever of its parts should
have it; as globalOutbound it was ambient to every module in the vat.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 21:44:29 -05:00
dckcandClaude Opus 5.5 7bf6eb44c7 capsite/toybox: a switchboard, the vats' only way out
A vat granted a host (PUT /<vat>?egress=<host> on the admin socket) gets
Egress as its globalOutbound, with the host in ctx.props where the vat
can't change it. Egress forwards matching requests, WebSocket upgrades
included, to the switchboard and refuses the rest with a 403; with no
grant, fetch still throws.

The switchboard is a separate workerd: a Switchboard DO that calls fetch
and returns the response, so a 101's webSocket passes through. toybox
reaches it over a unix socket in HTTP proxy style, which keeps the full
URL, scheme included. Its network service is the outer fence, with TLS
trusting the browser CAs; systemd units for it join toybox's, and only
the toybox group can open its socket.

The loaded Worker is now named by vat and incarnation, not by code hash:
the same code with a different grant must not share a Worker. The new
incarnation table sits beside the old ones; vats installed before it
read as incarnation 0 with no grant.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 21:44:29 -05:00
dckcandClaude Opus 5.5 88739d9495 capsite/toybox: vats with code installed at runtime, on workerd
Each vat is a Durable Object that stores code by hash and runs it as a
facet through the Worker Loader: an empty env, no fetch, storage that
carries over upgrades. Two sockets with no configured address: whoever
starts workerd hands them in (systemd socket activation), so the admin
socket is the authority to install code.

Tests run a real workerd: install, upgrade, isolation between vats, no
fetch, the public port can't install, and code and state survive a crash.
They spawn the package binary rather than the .bin shim, which forks
workerd, so killing the shim orphaned it and the test run never ended.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 21:44:29 -05:00
62 changed files with 2445 additions and 1516 deletions

No files matched your search

-1
View File
@@ -10,4 +10,3 @@ dist/
worker-configuration.d.ts
emdash-env.d.ts# diigo exports: personal data
export/
result
+8 -12
View File
@@ -89,12 +89,6 @@ narrative.
[the issues sketch](potluck/issues-sketch.md))? If the policy
changes, stripping stored rows is a durable-state migration.
- [ ] **1h. Align the UX with the RPC interface: every action findable, under the authority it needs.** Map and misalignments: [the UX map](capsite-notes.md#diigo-cache-ux-map-2026-10-07). First use on bldbox (2026-10-14) found search but no way there.
- [ ] 1h-i. Home links each public page in the username index.
- [ ] 1h-ii. The webkey page links its public companion's page.
- [ ] 1h-iii. Search private bookmarks from the webkey page: the 1d filters over the private cache's `items`, by RPC held by the cache key.
- [ ] 1h-iv. Publish and dump move from HTTP form routes to the webkey page's RPC.
- [ ] **2. potluck reads the public cache**: public data, so no capability, no cookie, no secret on potluck's side. The [diigo-week](diigo-week/README.md) plugin reads `GET /public/dckc-madmode?in=<week>&by=created` as microformats (an `h-feed` of `h-entry` bookmarks). Working in dev 2026-10-09; 2-iii postponed.
- [x] 2-i. Transport: the `DIIGO_CACHE` service binding in potluck's `wrangler.jsonc`, in dev too: the plugin's `ctx.http.fetch` refuses localhost (EmDash's SSRF guard), and a binding names one worker, not a host.
- [x] 2-ii. The page's microformats are the contract: diigo-cache's tests parse it with microformats-parser; diigo-week's tests read fixtures in the same markup.
@@ -105,10 +99,14 @@ narrative.
- [ ] **4b. Consider scruffier tags.** EmDash tags are taxonomy terms (rows that must exist before use); diigo-week auto-creates them, so drafting feels scruffy, but the model is neat. Alternative: the inline `/tag/<tag>` links in issue bodies *are* the tags (matching the microformats `p-category` reading), and potluck's `/tag/<tag>` page finds issues by scanning bodies. Cost: no EmDash tag field or index; a scan over a few dozen issues a year is cheap. Open: does the admin's tag field let you type a new tag inline?
- [ ] **5. Deployed end-to-end**: on bldbox, tailnet only, not Cloudflare: diigo binds the cookie to the IP it was issued to ([operator docs](diigo-cache/doc/README.md)).
- [x] 5-i. webapp and diigo-cache in one workerd under systemd, via [the flake](diigo-cache/flake.nix); behind `tailscale serve` at `https://bldbox.tail09e44.ts.net/`. 2026-10-14.
- [x] 5-ii. Create against prod: cookie from a browser on bldbox, wired public, filled 168 pages. 2026-10-14. Rate limiting `/api` waits while only the tailnet reaches it ([open issue 4](diigo-cache/doc/open-issues.md)).
- [ ] 5-iii. madmode/potluck reads the public page from prod: no service binding off Cloudflare ([open issue 5](diigo-cache/doc/open-issues.md)).
- [ ] **5. Deployed end-to-end** (order matters):
- [ ] 5-i. webapp: `cd webapp && npx wrangler deploy`
- [ ] 5-ii. diigo-cache: rate-limit `/api` (and `/public/*`) first
(diigo-cache CONTRIBUTING, "Deployment concern"); deploy; create
against prod (ids → password manager; no worker secret);
run the fill job.
- [ ] 5-iii. madmode: deploy with the service binding; the
weekly page renders against prod.
- [ ] **6. Cookie expiry**: when diigo's session ends, head refreshes
fail; the public page keeps serving what's stored (say so on the
page, don't fail silently). Rotation is manual: re-mint via
@@ -220,8 +218,6 @@ to every goal in this tree.
pattern, abstracted from the E-on-Java sources (bearer secrets,
YURL32, secret≠address); the reason ids ride only fragments and POST
bodies
- [docs/learn-by-watching.md](docs/learn-by-watching.md) — an agent
watches me use a site, then writes policy-bounded code for its hidden API
- [the mm-diigo diigo-bak scripts](https://github.com/dckc/mm-diigo) —
provenance of the fluent client and dump generator (`projects/diigo-bak/`:
WebApp.js, diigo-dump.mjs, diigo-interact.mjs; mm-diigo commit 7dbb367,
-10
View File
@@ -47,7 +47,6 @@ flowchart LR
login["/cache/ login<br/>(password manager)"]
admin["webkey page<br/>/cache/ + key in fragment"]
public["/public/username<br/>(anyone)"]
search["/public/username?q=…&in=…<br/>search, date windows"]
home -->|create| connect
connect -->|"POST /_mint (cookie)"| wire
@@ -60,12 +59,8 @@ flowchart LR
home -->|"dump: POST / (cache id + page)"| home
admin -->|"api.cache(key) …"| admin
created -->|"link (public mode)"| public
public -->|"GET form"| search
search -->|"GET form"| search
```
Updated 2026-10-14. There's no edge from home to public: once the created page is gone, you reach your public page only by typing its URL.
| action | where | transport | authority |
|---|---|---|---|
| mint the diigo session | `/_connect` | HTTP `POST /_mint` (relays webapp's form) | the cookie |
@@ -78,9 +73,6 @@ Updated 2026-10-14. There's no edge from home to public: once the created page i
| …of the public companion | webkey page | RPC `publicCache().…` | cache key |
| invalidate the last N days | webkey page | RPC `invalidateRecent(days)` | cache key |
| read public bookmarks | `/public/<u>` | HTTP GET (HTML or JSON) ⚠ | none |
| search, date windows (1d) | `/public/<u>` | HTTP GET `q`, `days`, `in`, `after`, `before`, `by` | none |
| find your public page | — ⚠ | — | none (the username index knows it) |
| search private bookmarks | — ⚠ | — | cache key |
| bulk dump for another worker | — | service binding `DiigoBridge.dumpNdjson` | worker config |
⚠ misalignments:
@@ -89,8 +81,6 @@ Updated 2026-10-14. There's no edge from home to public: once the created page i
- ~~the public page can write~~ — resolved: it reads only through the
read-only `viewer()` facet; unfetched pages say so
- the webkey page has no dump or publish; the home page has no fill
- (2026-10-14, first use on bldbox) nothing links to `/public/<u>`: home doesn't list the username index, and the webkey page doesn't link its public companion's page
- search exists only on the public page; the private cache, which holds every item, has the raw page dump and nothing else. Private search belongs on the webkey page, held by the cache key (an RPC over the same `items` query `viewer()` runs)
## Native-plugin wiring (the part that took a while)
+1 -1
View File
@@ -69,4 +69,4 @@ Check a filled cache against a diigo RSS export: `node scripts/compare-export.ts
## Deploy
On bldbox, tailnet only, via [the flake](flake.nix): see [the operator docs](doc/README.md). Cloudflare is out while diigo binds the cookie to the IP it was issued to ([open issue 1](doc/open-issues.md#-1-how-does-diigo-see-the-cookie-come-from-the-ip-it-was-issued-to)).
Not deployed yet; the order matters (goal 5 in [the capsite checklist](../capsite-checklist.md)): webapp first (`cd ../webapp && npx wrangler deploy`), then diigo-cache, after rate-limiting `/api` (above).
+1 -1
View File
@@ -23,4 +23,4 @@ Then, in the browser:
- **Ids are capabilities:** the cache id is a bearer key you keep in your password manager. It rides URL fragments and POST bodies, never a path or query string, so it stays out of logs and history.
- **Cheap to read:** pages come from Durable Object SQLite storage, and a fill job in the background fetches each diigo page once.
Design and tests: [CONTRIBUTING](CONTRIBUTING.md). Running it on bldbox: [the operator docs](doc/README.md).
Design, tests, and deploying: [CONTRIBUTING](CONTRIBUTING.md).
-19
View File
@@ -1,19 +0,0 @@
# Operating diigo-cache on bldbox
diigo-cache and [webapp](../../webapp/README.md) run together in one workerd on bldbox, reachable only over the tailnet at `https://bldbox.tail09e44.ts.net/`. Cloudflare doesn't work: diigo binds the session cookie to the IP address it was issued to, and Cloudflare's egress IPs aren't that address (see [open issue 1](open-issues.md#-1-how-does-diigo-see-the-cookie-come-from-the-ip-it-was-issued-to)).
```
browser on the tailnet
→ tailscale serve (HTTPS, bldbox.tail09e44.ts.net:443)
→ diigo-cache.socket (127.0.0.1:8790)
→ diigo-cache.service: workerd, DynamicUser
diigo-cache worker → state in /var/lib/diigo-cache/cache
webapp worker → state in /var/lib/diigo-cache/webapp (holds the cookie)
→ diigo.com
```
- [Install, upgrade, roll back](install.md)
- [Day to day: create a cache, logs, backups](operate.md)
- [Open issues](open-issues.md), in IBIS style
The build is [the flake](../flake.nix): wrangler bundles each worker as `wrangler deploy` would, [gen-config.sh](../nix/gen-config.sh) fills [the workerd config](../nix/config.capnp.in), and the [socket](../nix/diigo-cache.socket) and [service](../nix/diigo-cache.service) units ship in the package. workerd comes from nixpkgs' `wrangler`, which bundles a patched one; nixpkgs has no standalone `workerd`.
-81
View File
@@ -1,81 +0,0 @@
# Install, upgrade, roll back
Everything below runs on bldbox. Neither unit has been run under the system manager yet; the flake's smoke check runs the same build under workerd directly.
## Once: tailnet HTTPS
In the [Tailscale admin console DNS page](https://login.tailscale.com/admin/dns), enable MagicDNS (on) and **HTTPS Certificates** (off as of 2026-10-14: `tailscale status --json | jq .CertDomains` is `null`). HTTPS matters: the "save to password manager" button uses `PasswordCredential`, which browsers offer only in a secure context.
## Build and check
```sh
cd ~/oros-bots/capsite/diigo-cache
nix flake check # builds, then serves the home page and mints a webapp instance
out=$(nix build --no-link --print-out-paths .#)
nix/probe-unit.sh "$out" # serves it under the unit's syscall filter: "probe: ok"
```
The probe catches what the smoke check can't: the nix sandbox has no systemd, so it doesn't apply the unit's `SystemCallFilter`. The flake only sees files git tracks: `git add` new files before building.
## Install
The service runs whatever `/nix/var/nix/profiles/diigo-cache` points at, so the profile is also the GC root and the rollback history.
nix-env is spelled out in full because sudo's `secure_path` leaves out nix's profile.
```sh
sudo /nix/var/nix/profiles/default/bin/nix-env -p /nix/var/nix/profiles/diigo-cache --set "$out"
sudo systemctl link /nix/var/nix/profiles/diigo-cache/lib/systemd/system/diigo-cache.{socket,service}
sudo systemctl enable --now diigo-cache.socket diigo-cache.service
sudo tailscale serve --bg --https=443 http://127.0.0.1:8790
```
`tailscale serve --bg` persists across reboots in tailscaled's state; `tailscale serve status` shows it.
## Verify
```sh
curl -sf https://bldbox.tail09e44.ts.net/ | grep -c _connect # 1+; first request starts workerd
systemctl status diigo-cache.service
```
On a 502, make sure `tailscale serve` finds something on 8790: `curl -sI http://127.0.0.1:8790/`. (The cache also answers 502 when it can't load a page from diigo; its body then says `could not load page`.) If workerd crashes on start, systemd stops retrying, then fails the socket too (`Result: service-start-limit-hit` in `systemctl status diigo-cache.socket`). After fixing the cause:
```sh
sudo systemctl reset-failed diigo-cache.socket diigo-cache.service
sudo systemctl start diigo-cache.socket
```
From another tailnet device, open `https://bldbox.tail09e44.ts.net/`. From off the tailnet, the name doesn't resolve and `100.89.146.23` doesn't route.
## Upgrade
```sh
out=$(nix build --no-link --print-out-paths .#)
nix/probe-unit.sh "$out"
sudo /nix/var/nix/profiles/default/bin/nix-env -p /nix/var/nix/profiles/diigo-cache --set "$out"
sudo systemctl daemon-reload # in case the units changed
sudo systemctl restart diigo-cache.service
```
Durable Object state outlives the code: an upgrade whose schema change existing state can't read is a breaking change (see [capsite AGENTS.md](../../AGENTS.md#durable-state-be-loud-and-conservative-about-breaking-changes)). Back up first ([operate](operate.md#backups)).
## Roll back
```sh
sudo /nix/var/nix/profiles/default/bin/nix-env -p /nix/var/nix/profiles/diigo-cache --list-generations
sudo /nix/var/nix/profiles/default/bin/nix-env -p /nix/var/nix/profiles/diigo-cache --rollback
sudo systemctl restart diigo-cache.service
```
## Update nixpkgs
`nix flake update` moves wrangler, and with it workerd. The flake names workerd's version (`version` in [flake.nix](../flake.nix)); if nixpkgs' wrangler bundles a different one, the build fails with `no workerd <version>`. Set it to the bundled version, which must be no older than the workers' `compatibility_date`.
## Remove
```sh
sudo tailscale serve --https=443 off
sudo systemctl disable --now diigo-cache.socket diigo-cache.service
sudo rm /nix/var/nix/profiles/diigo-cache* # state in /var/lib/private/diigo-cache stays
```
-173
View File
@@ -1,173 +0,0 @@
# Open issues
In [IBIS](https://github.com/dckc/vattr97/wiki/IBIS) notation: `?` issue, `?!` resolved, `?~` open with a fallback; `:` position, `:+` accepted, `:-` rejected, `:~+` fallback; `+` pro, `-` con; `!` to-do; `.` comment. Append; don't renumber.
### ?! 1. How does diigo see the cookie come from the IP it was issued to?
```
?! 1. How does diigo see the cookie come from the IP it was issued to?
. observed: minted from the browser, the cookie failed from Cloudflare
. unverified that IP is the only binding; the mint sends user-agent
"Mozilla/5.0", not the browser's, and that works in dev
: 1a. log in to diigo from a browser that shares bldbox's public IP
(same LAN, same NAT)
+ no setup if that's where the browser already is
- breaks when the browser roams (phone, laptop away from home)
! compare: curl https://ifconfig.me on bldbox and in the browser
: 1b. advertise bldbox as a tailnet exit node; route the browser through
it while logging in to diigo and copying the cookie
+ bldbox's IP by construction, from anywhere on the tailnet
- bldbox isn't an exit node (ExitNodeOption false, 2026-10-14);
needs `tailscale set --advertise-exit-node` and admin approval
:+ 1c. run the browser on bldbox
+ worked 2026-10-14: a cookie copied from Brave's devtools on bldbox
minted, wired public, and filled 168 pages
:- 1d. deploy to Cloudflare
- its egress IPs aren't the browser's (the failure that prompted this)
```
### ?~ 2. How is diigo-cache reachable only from the tailnet?
```
?~ 2. How is diigo-cache reachable only from the tailnet?
:~+ 2a. workerd on 127.0.0.1:8790; tailscale serve proxies
https://bldbox.tail09e44.ts.net/ to it
+ HTTPS with a real cert: PasswordCredential needs a secure context
+ tailscaled owns the tailnet address; no start-order dependency
- needs HTTPS certificates on in the tailnet (off as of 2026-10-14)
! enable in the admin console (install.md)
- every local user and process on bldbox reaches 127.0.0.1:8790 (see 3)
+ the cache id is still needed for anything private
: 2b. listen on 100.89.146.23 directly (ListenStream, FreeBind=yes)
- plain HTTP: the password-manager button fails
: 2c. tailscale serve to a unix socket only it can open
+ no loopback port
- unverified that tailscale 1.90.9 serve takes a unix socket target
? 2d. Which tailnet devices may reach it?
. today: every device on the tailnet (m5x, penguin, pixel-7, tiny-jwc)
: 2d-i. restrict to some devices with a tailnet ACL grant on bldbox:443
```
### ?~ 3. What account does the service run as?
```
?~ 3. What account does the service run as?
:~+ 3a. a system unit with DynamicUser=yes
+ the cookie's state is 0700 to a uid nothing else runs as; agents
and bots running as connolly can't read it
+ full sandboxing (systemd-analyze security: 2.2 OK)
- install and upgrade need sudo
: 3b. a user unit under connolly, with lingering
+ no sudo for upgrade; a ~/.local profile
- the cookie sits in connolly's files, readable by every process
connolly runs, Discord and opencode bots included
- Ubuntu's AppArmor userns restriction weakens user-manager sandboxing
- tailscale serve needs root (or `tailscale set --operator`) anyway
```
### ? 4. Does /api need a rate limit on the tailnet?
```
? 4. Does /api need a rate limit on the tailnet?
. CONTRIBUTING asks for one "before exposing a deployment"
:~+ 4a. not while only tailnet devices reach it (see 2)
: 4b. a rate limit in front of workerd before any funnel (see 5)
```
### ? 5. How does the weekly roundup read the public page?
```
? 5. How does the weekly roundup read the public page?
. the madmode blog build needs /public/<username>; where does it run?
: 5a. build on a tailnet device
: 5b. join CI to the tailnet (Tailscale's GitHub Action)
: 5c. tailscale funnel just /public/ to the internet
+ public pages are public by design
- exposes a guessable URL; needs 4b
```
### ? 6. How is state backed up?
```
? 6. How is state backed up?
:~+ 6a. by hand, service stopped (operate.md)
: 6b. a systemd timer
- backups hold the cookie: where do they go, encrypted how?
: 6c. none: the cache is a cache
- the ids people saved point at objects that would be gone
```
### ? 7. How does a cache get a fresh cookie?
```
? 7. How does a cache get a fresh cookie?
. a wired cache refuses a different webapp id
:~+ 7a. mint a fresh webapp instance and wire a new cache
- a new cache id to save
+ wiring public re-registers the username, so the public URL stays
: 7b. let webapp replace the cookie in an existing instance
+ cache ids stay put
```
### ? 8. Should `wrangler dev` state move to bldbox?
```
? 8. Should `wrangler dev` state move to bldbox?
. Durable Object unique keys follow miniflare's `<script>-<class>`,
so the per-object files may carry over; untested
:~+ 8a. start fresh on bldbox
+ dev cookies were minted for wherever dev ran (see 1)
: 8b. copy .wrangler/state/v3/do/<script>-<class>/ into the state dirs
```
### ? 9. What should we be able to observe, and how?
```
? 9. What should we be able to observe, and how?
. today: each worker console.logs objects ({event, ...}); workerd's
structuredLogging puts them in the journal (operate.md)
. gap: webapp logs only mint; a diigo request shows up only as the
cache's account of it ({event: "cache", outcome: "miss" | "refetch"}),
so no status, latency, or failure before the cache sees it
. the refresh (every 3h) is seen only by reading the journal
! survey practice before choosing: logs vs metrics vs traces, what to
alert on; Workers observability docs as a start
: 9a. log each diigo request in webapp: path, status, ms; no query
values or headers, so the cookie never appears
? 9b. how does anyone notice a refresh failing (expired cookie)?
```
### ? 10. Do we need to store diigo page numbers?
```
? 10. Do we need to store diigo page numbers?
. pages come from load_user_items with sort=updated, newest first; each
new or edited bookmark shifts the rest down one slot, a deletion up one
. only page 1 is refetched (every 3h, refetchThrough 1), so pages 2 and
on are snapshots from the first fill (2026-10-14)
. items are keyed by item_id; page_members records each page's positions
. consequences, seen 2026-10-29:
. k new bookmarks leave k items on no page: a gap in paged views
. an edited bookmark is listed on page 1 and at its stale position
. summing logged page items (16,767 private) counts snapshots, not items
. a deletion is never noticed; its row stays
. week views (?days=, ?in=) query items by date, so they're unaffected
: 10a. keep pages as stored snapshots (today)
+ read-through: viewing a page not yet filled fetches it
- the drift above
: 10b. store only items; a page number is just the fill's cursor
. each page-table read has a replacement:
. refresh depth (deepestPageSince): items updated since the cutoff,
/ 100, rounded up, + 1 page of slack for shifts
. invalidateRecent: not needed
. knownTotal: keep diigo's latest total as one kv value
. completeness (pagesThrough): a "full pass done" flag on the fill job
. paged public view: items order by updated desc, limit/offset
. page dump (HIT/MISS): fetch live; it's a debugging tool
+ paged views get no gaps or duplicates
+ last_seen per item: after a full pass, items not seen were deleted
or made private on diigo
+ fetched_at per item says more than pages.etched_at
- views past the filled part come back short until the fill gets there
- a schema migration
```
-48
View File
@@ -1,48 +0,0 @@
# Day to day
## Create a cache
As in [the README](../README.md#getting-started), at `https://bldbox.tail09e44.ts.net/` instead of localhost: mint, wire, save the ids, fill. Copy the cookie from a browser running on bldbox: diigo accepts it only from the IP it was issued to (see [issue 1](open-issues.md#-1-how-does-diigo-see-the-cookie-come-from-the-ip-it-was-issued-to)).
The public page is then `https://bldbox.tail09e44.ts.net/public/<diigo username>?days=7`, on the tailnet only.
## Logs
```sh
journalctl -u diigo-cache.service -f -o cat |
jq -Rr 'fromjson? | "\(.timestamp / 1000 | todate) \(.level) \(.message | gsub("\\s*\\n\\s*"; " "))"'
```
`fromjson?` skips lines that aren't JSON: systemd's own ("Started …") and entries from before `structuredLogging`.
workerd runs with `structuredLogging`: each entry is one line of JSON, `{timestamp, level, message}`. `message` is the logged object as `console.log` prints it, not JSON: on Cloudflare, Workers Logs indexes the fields of a logged object, so the workers log objects rather than strings.
workerd logs the workers' `console.*` output: `{event: "cache", kind, page, outcome}` per page read, `{event: "fill", state, …}` per fill step (a refresh logs `refetchThrough`), `{event: "mint"}`. Ids show only as fingerprints; the cookie never appears.
## State
With `DynamicUser=yes`, systemd keeps the state in `/var/lib/private/diigo-cache/` (`/var/lib/diigo-cache` is a symlink to it), mode 0700, owned by a uid that exists only while the service runs:
| Dir | Holds | Secret? |
| :--- | :--- | :--- |
| `cache/diigo-cache-DiigoCache/` | private caches: every bookmark | yes |
| `cache/diigo-cache-PublicCache/` | public caches and the username index | no |
| `webapp/webapp-WebAppDo/` | webapp instances: the diigo cookie | yes, a credential |
Each Durable Object is one `<id hash>.sqlite`. Read one with the service stopped, or copy it first: `sudo sqlite3 -readonly <file> .tables`.
## Backups
The private caches are refillable from diigo; the cookie can be re-minted. What's lost with the state is the binding from the ids people saved to these objects. Backups hold the cookie, so treat them as secret.
```sh
sudo systemctl stop diigo-cache.socket diigo-cache.service # the socket would restart it
sudo tar -C /var/lib/private -czf diigo-cache-$(date +%F).tgz diigo-cache
sudo systemctl start diigo-cache.socket
```
No backup is scheduled (see [open issue 6](open-issues.md#-6-how-is-state-backed-up)).
## The cookie expires
When fills log `{event: "fill", state: "failed"}` with a diigo auth error, mint a fresh webapp instance and wire a new cache. A wired cache refuses a different webapp id (`setup` in [cache.ts](../src/cache.ts)) (see [open issue 7](open-issues.md#-7-how-does-a-cache-get-a-fresh-cookie)).
-27
View File
@@ -1,27 +0,0 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1791734076,
"narHash": "sha256-i5qk1kLiit98rRbh1AXmWBNT9QXC/y4l5Wk/u5EdpDQ=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "7fd4004d0511991fff3a0524856a9be09e28c5f0",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}
-118
View File
@@ -1,118 +0,0 @@
{
description = "diigo-cache and webapp on workerd, outside Cloudflare";
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
outputs =
{ self, nixpkgs }:
let
system = "x86_64-linux";
pkgs = nixpkgs.legacyPackages.${system};
inherit (pkgs) lib;
# nixpkgs has no workerd of its own; wrangler carries a patched one
workerd =
pkgs.runCommand "workerd-${version}" { } ''
bin=${pkgs.wrangler}/lib/node_modules/.pnpm/@cloudflare+workerd-linux-64@${version}/node_modules/@cloudflare/workerd-linux-64/bin/workerd
test -x $bin || { echo "no workerd ${version} in ${pkgs.wrangler}" >&2; exit 1; }
mkdir -p $out/bin
ln -s $bin $out/bin/workerd
'';
# the workerd that nixpkgs' wrangler bundles; must be at least the
# workers' compatibility_date
version = "1.20261006.1";
# the flake's source is all of capsite; take what the two workers need
src = lib.fileset.toSource {
root = ./..;
fileset = lib.fileset.unions [
./package.json
./pnpm-lock.yaml
./wrangler.jsonc
./tsconfig.json
./src
../webapp/wrangler.jsonc
../webapp/tsconfig.json
../webapp/src
];
};
diigo-cache = pkgs.stdenv.mkDerivation (finalAttrs: {
pname = "diigo-cache";
version = "0.0.0";
inherit src;
sourceRoot = "${finalAttrs.src.name}/diigo-cache";
nativeBuildInputs = [
pkgs.nodejs
pkgs.pnpm_10
pkgs.pnpmConfigHook
pkgs.wrangler
];
pnpmDeps = pkgs.fetchPnpmDeps {
inherit (finalAttrs) pname version src sourceRoot;
pnpm = pkgs.pnpm_10;
fetcherVersion = 3;
hash = "sha256-sn/juOL2mhyy3i57GCUKA2X8SPyR9FwY4KoxdkgZa0M=";
};
buildPhase = ''
runHook preBuild
export HOME=$TMPDIR WRANGLER_SEND_METRICS=false
# wrangler writes .wrangler/tmp beside each config
chmod -R u+w ../webapp
wrangler deploy --dry-run --outdir $PWD/dist/cache -c wrangler.jsonc
wrangler deploy --dry-run --outdir $PWD/dist/webapp -c ../webapp/wrangler.jsonc
bash ${./nix/gen-config.sh} dist ${./nix/config.capnp.in} \
"$(sed -n 's/.*"compatibility_date": *"\([^"]*\)".*/\1/p' wrangler.jsonc)" \
"$(sed -n 's/.*"compatibility_date": *"\([^"]*\)".*/\1/p' ../webapp/wrangler.jsonc)" \
> dist/config.capnp
runHook postBuild
'';
installPhase = ''
runHook preInstall
share=$out/share/diigo-cache
mkdir -p $share $out/bin $out/lib/systemd/system
cp -r dist/cache dist/webapp dist/config.capnp $share/
rm -f $share/*/README.md $share/*/*.map
cat > $out/bin/diigo-cache-serve <<EOF
#!${pkgs.runtimeShell}
exec ${workerd}/bin/workerd serve $share/config.capnp "\$@"
EOF
chmod +x $out/bin/diigo-cache-serve
cp ${./nix/diigo-cache.socket} $out/lib/systemd/system/diigo-cache.socket
cp ${./nix/diigo-cache.service} $out/lib/systemd/system/diigo-cache.service
runHook postInstall
'';
});
in
{
packages.${system} = {
default = diigo-cache;
inherit diigo-cache workerd;
};
# the built config serves the home page, and mints a webapp instance
# through the WEBAPP binding into webapp's Durable Object storage;
# each log entry is one line of JSON
checks.${system}.smoke = pkgs.runCommand "diigo-cache-smoke" { nativeBuildInputs = [ pkgs.curl pkgs.jq ]; } ''
mkdir -p cache webapp
${diigo-cache}/bin/diigo-cache-serve -s http=127.0.0.1:18790 \
-d cache-state=$PWD/cache -d webapp-state=$PWD/webapp > log 2>&1 &
pid=$!
for i in $(seq 50); do curl -sf http://127.0.0.1:18790/ -o home.html && break; sleep 0.2; done
grep -q '/_connect' home.html
curl -sf -X POST http://127.0.0.1:18790/_mint \
--data-urlencode url=https://diigo.invalid/ --data-urlencode cookie=x \
-D headers -o /dev/null
grep -qi '^x-webapp-id: [A-Za-z0-9-]' headers
ls webapp/*/*.sqlite
kill $pid; wait $pid || true
cat log
grep -q "event: 'mint'" log
jq -e . log > /dev/null
touch $out
'';
};
}
-60
View File
@@ -1,60 +0,0 @@
# diigo-cache and the webapp it reads diigo through, in one workerd.
#
# The listening socket has no address here: systemd hands it in
# (-S http=3), so holding the socket is the authority to reach the cache.
# State directories likewise come from the command line:
# -d cache-state=<dir> -d webapp-state=<dir>.
#
# Durable Object unique keys follow miniflare's `<script>-<class>`, so a
# `wrangler dev` state directory names its objects the same way.
using Workerd = import "/workerd/workerd.capnp";
const config :Workerd.Config = (
services = [
(name = "diigo-cache", worker = .cache),
(name = "webapp", worker = .webapp),
(name = "nowhere", network = (allow = [])),
(name = "cache-state", disk = (path = "cache-state", writable = true)),
(name = "webapp-state", disk = (path = "webapp-state", writable = true)),
],
sockets = [
(name = "http", http = (), service = "diigo-cache"),
],
# one JSON object per line, console.* included: journald keeps an
# object in one entry rather than one entry per line of it
structuredLogging = true,
);
const cache :Workerd.Worker = (
compatibilityDate = "@CACHE_DATE@",
modules = [
@CACHE_MODULES@
],
durableObjectNamespaces = [
(className = "DiigoCache", uniqueKey = "diigo-cache-DiigoCache", enableSql = true),
(className = "PublicCache", uniqueKey = "diigo-cache-PublicCache", enableSql = true),
],
durableObjectStorage = (localDisk = "cache-state"),
bindings = [
(name = "CACHE_DO", durableObjectNamespace = "DiigoCache"),
(name = "PUBLIC_DO", durableObjectNamespace = "PublicCache"),
(name = "WEBAPP", service = (name = "webapp", entrypoint = "WebAppFactory")),
],
# diigo is reached only through WEBAPP
globalOutbound = "nowhere",
);
const webapp :Workerd.Worker = (
compatibilityDate = "@WEBAPP_DATE@",
modules = [
@WEBAPP_MODULES@
],
durableObjectNamespaces = [
(className = "WebAppDo", uniqueKey = "webapp-WebAppDo", enableSql = true),
],
durableObjectStorage = (localDisk = "webapp-state"),
bindings = [
(name = "WEBAPP_DO", durableObjectNamespace = "WebAppDo"),
],
# globalOutbound: workerd's default "internet", public addresses only
);
-31
View File
@@ -1,31 +0,0 @@
[Unit]
Description=diigo-cache and webapp (workerd)
Requires=diigo-cache.socket
[Service]
# the profile path survives upgrades; see doc/install.md
ExecStart=/nix/var/nix/profiles/diigo-cache/bin/diigo-cache-serve -S http=3 -d cache-state=/var/lib/diigo-cache/cache -d webapp-state=/var/lib/diigo-cache/webapp
DynamicUser=yes
StateDirectory=diigo-cache diigo-cache/cache diigo-cache/webapp
StateDirectoryMode=0700
# webapp fetches diigo.com; nothing else needs the network
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictNamespaces=yes
LockPersonality=yes
CapabilityBoundingSet=
SystemCallFilter=@system-service
# V8 uses memory protection keys; without these, SIGSYS at startup
SystemCallFilter=pkey_alloc pkey_mprotect pkey_free
# not MemoryDenyWriteExecute: V8's JIT needs W+X
[Install]
# started at boot, not only on the first request: workerd runs the
# caches' refresh alarms only while it is up
WantedBy=multi-user.target
-9
View File
@@ -1,9 +0,0 @@
[Unit]
Description=diigo-cache: loopback port behind tailscale serve
[Socket]
# tailscale serve proxies https://bldbox.<tailnet>.ts.net/ here
ListenStream=127.0.0.1:8790
[Install]
WantedBy=sockets.target
-41
View File
@@ -1,41 +0,0 @@
#!/usr/bin/env bash
# Fill config.capnp.in from `wrangler deploy --dry-run` outdirs.
# usage: gen-config.sh <dist> <template> <cache-date> <webapp-date> > config.capnp
# <dist>/cache and <dist>/webapp each hold index.js plus the text modules
# wrangler.jsonc's rules name (*.sql, capnweb's browser build); embed
# paths are relative to the config, which sits beside them.
set -euo pipefail
dist=$1 template=$2 cache_date=$3 webapp_date=$4
modules() {
local dir=$1
if [[ ! -f $dist/$dir/index.js ]]; then
echo "gen-config: $dist/$dir/index.js: missing" >&2
exit 1
fi
echo " (name = \"index.js\", esModule = embed \"$dir/index.js\"),"
for f in "$dist/$dir"/*; do
local name=${f##*/}
case $name in
index.js | README.md | *.map) ;;
*.sql | *-index.js) echo " (name = \"$name\", text = embed \"$dir/$name\")," ;;
*)
echo "gen-config: $dir/$name: no module type rule" >&2
exit 1
;;
esac
done
}
cache_modules=$(modules cache)
webapp_modules=$(modules webapp)
while IFS= read -r line; do
case $line in
@CACHE_MODULES@) echo "$cache_modules" ;;
@WEBAPP_MODULES@) echo "$webapp_modules" ;;
*)
line=${line//@CACHE_DATE@/$cache_date}
echo "${line//@WEBAPP_DATE@/$webapp_date}"
;;
esac
done <"$template"
-27
View File
@@ -1,27 +0,0 @@
#!/usr/bin/env bash
# Serve a built package under the service unit's syscall filter, as a
# transient user unit, on a scratch port and state; check the home page.
# The flake's smoke check can't: the nix sandbox has no systemd.
# usage: probe-unit.sh <package out path>
set -euo pipefail
out=$1
state=$(mktemp -d)
trap 'systemctl --user stop diigo-cache-probe 2>/dev/null; rm -rf "$state"' EXIT
mkdir "$state/cache" "$state/webapp"
props=()
while IFS= read -r line; do props+=(-p "$line"); done \
< <(grep '^SystemCallFilter=' "$out/lib/systemd/system/diigo-cache.service")
systemd-run --user -q --collect --unit=diigo-cache-probe "${props[@]}" \
"$out/bin/diigo-cache-serve" -s http=127.0.0.1:18791 \
-d cache-state="$state/cache" -d webapp-state="$state/webapp"
for _ in $(seq 30); do
if curl -sf -m 2 http://127.0.0.1:18791/ | grep -q _connect; then
echo "probe: ok"
exit 0
fi
sleep 0.3
done
echo "probe: no home page; see journalctl --user -u diigo-cache-probe and journalctl -k | grep syscall=" >&2
exit 1
+8 -55
View File
@@ -44,14 +44,6 @@ const LEGACY_FILL_PAGE_SIZE = 24;
* pages at MS_PER_CALL; this keeps steps from running back to back */
const FILL_STEP_DELAY_MS = 1000;
/** how long after a fill ends (done or failed) a refresh starts: a fill
* that refetches the recent pages, then ends and schedules the next */
const REFRESH_INTERVAL_MS = 3 * 60 * 60 * 1000;
/** a refresh refetches the pages holding anything updated this recently
* (and every page before them; page 1 at least, for new bookmarks) */
const REFRESH_DAYS = 2;
/**
* a fill job's progress (goal 1e; tests/fill.test.ts). Stored in the DO
* (new state, additive), so it survives eviction; advanced by alarms.
@@ -74,9 +66,6 @@ export type FillStatus = {
updatedAt: string;
/** why it failed: safe to show and log (no ids, no header values) */
error?: string;
/** pages numbered this or lower are fetched even when cached (a
* refresh); absent on plain fills */
refetchThrough?: number;
};
/** the page size a fill job counts in (old jobs didn't record it) */
@@ -150,11 +139,6 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
await null; // let the subclass constructor finish: `kind` is its field
const from = this.#writer.migrate();
if (from < SCHEMA_VERSION) console.log({ event: "schema", kind: this.kind, from, to: SCHEMA_VERSION });
// a fill that ended before refreshes existed has no alarm yet
const fill = await ctx.storage.get<FillStatus>("fill");
if (fill && fill.state !== "running" && fill.state !== "stopped" && (await ctx.storage.getAlarm()) === null) {
await ctx.storage.setAlarm(this.#clock.now() + REFRESH_INTERVAL_MS);
}
});
}
@@ -192,20 +176,12 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
* cache, `pagesPerStep` per alarm (default 20, 1–50). Starting while a
* job runs returns that job unchanged; a finished, stopped, or failed
* job is replaced by a fresh one (cached pages are skipped anyway).
* Once the job ends, a refresh follows every REFRESH_INTERVAL_MS until
* stopped.
*/
async startFill(opts: { pagesPerStep?: number } = {}): Promise<FillStatus> {
const current = await this.fillStatus();
if (current?.state === "running" && fillCountsAsNow(current)) return current;
const step = Math.trunc(opts.pagesPerStep ?? 20);
if (!(step >= 1 && step <= 50)) throw new Error("pagesPerStep: expected 1–50");
return this.#startJob(step);
}
/** a fresh fill job, first step in FILL_STEP_DELAY_MS; `refetchThrough`
* makes it a refresh */
async #startJob(step: number, refetchThrough?: number): Promise<FillStatus> {
const now = this.#iso();
const status: FillStatus = {
state: "running",
@@ -216,22 +192,13 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
fetched: 0,
startedAt: now,
updatedAt: now,
...(refetchThrough === undefined ? {} : { refetchThrough }),
};
await this.ctx.storage.put({ fill: status, fillStep: step });
await this.ctx.storage.setAlarm(this.#clock.now() + FILL_STEP_DELAY_MS);
console.log({ event: "fill", kind: this.kind, state: status.state, pagesPerStep: step, refetchThrough });
console.log({ event: "fill", kind: this.kind, state: status.state, pagesPerStep: step });
return status;
}
/** start a refresh: a fill that refetches the pages holding anything
* updated in the last REFRESH_DAYS days. Fetching overwrites a page in
* place, so a refresh that fails leaves the cache as it was. */
async #refresh(step: number): Promise<void> {
const cutoff = Math.floor(this.#clock.now() / 1000) - REFRESH_DAYS * 24 * 60 * 60;
await this.#startJob(step, Math.max(1, this.#reader.deepestPageSince(cutoff) ?? 1));
}
/** the fill job's progress, or undefined if none was ever started;
* the page count comes from any cached page until the job learns it */
async fillStatus(): Promise<FillStatus | undefined> {
@@ -239,12 +206,11 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
return fill && fill.pages === null ? { ...fill, pages: this.#knownPages() } : fill;
}
/** stop the fill job after its current step, and its refreshes;
* cached pages stay */
/** stop the fill job after its current step; cached pages stay */
async stopFill(): Promise<FillStatus> {
const current = await this.fillStatus();
if (!current) throw new Error("no fill job to stop");
if (current.state === "stopped") return current;
if (current.state !== "running") return current;
const stopped: FillStatus = { ...current, state: "stopped", updatedAt: this.#iso() };
await this.ctx.storage.put("fill", stopped);
await this.ctx.storage.deleteAlarm();
@@ -273,15 +239,10 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
}
/** one fill step: up to `fillStep` pages, progress saved after each,
* then the next step is scheduled (or the job ends, and the next
* refresh is). On a job that has ended, the refresh starts. */
* then the next step is scheduled (or the job ends) */
async alarm(): Promise<void> {
const step = (await this.ctx.storage.get<number>("fillStep")) ?? 20;
let status = await this.fillStatus();
if (status?.state === "done" || status?.state === "failed") {
await this.#refresh(step);
return;
}
// a job saved under another page size or numbering counts its pages
// differently: resuming it would skip or repeat items, so it fails
if (status?.state === "running" && !fillCountsAsNow(status)) {
@@ -292,7 +253,6 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
status = { ...status, state: "failed", error, updatedAt: this.#iso() };
console.error({ event: "fill", kind: this.kind, state: "failed", error });
await this.ctx.storage.put("fill", status);
await this.ctx.storage.setAlarm(this.#clock.now() + REFRESH_INTERVAL_MS);
return;
}
for (let i = 0; i < step && status?.state === "running"; i += 1) {
@@ -301,7 +261,7 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
break;
}
try {
const page = await this.#load(status.nextPage, PAGE_SIZE, status.nextPage <= (status.refetchThrough ?? 0));
const page = await this.page(status.nextPage, PAGE_SIZE);
const fetched = status.fetched + (page.cached ? 0 : 1);
// a page whose own total says the data ended before it (diigo
// answers total 0 past the end) ends the walk; the count is the
@@ -333,7 +293,6 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
await this.ctx.storage.put("fill", status);
console.log({ event: "fill", kind: this.kind, state: status.state, nextPage: status.nextPage, pages: status.pages, fetched: status.fetched });
if (status.state === "running") await this.ctx.storage.setAlarm(this.#clock.now() + FILL_STEP_DELAY_MS);
else await this.ctx.storage.setAlarm(this.#clock.now() + REFRESH_INTERVAL_MS);
}
/** diigo's page count, if any cached page recorded `total` (pages past
@@ -350,16 +309,10 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
* rides in the result (`cached`).
*/
async page(pageNum: number, count: number): Promise<CachePage> {
return this.#load(pageNum, count, false);
}
/** {@link page}, or with `fresh`, fetch even if cached (overwriting
* the stored page) */
async #load(pageNum: number, count: number, fresh: boolean): Promise<CachePage> {
const init = await this.wiring();
if (!init) throw new Error("not wired: this cache id was never set up");
const hit = fresh ? null : await this.#pageFromStorage(pageNum, count);
const hit = await this.#pageFromStorage(pageNum, count);
if (hit) {
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "hit", items: hit.items.length });
return hit;
@@ -376,7 +329,7 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
this.#step += 1;
this.#pause = this.#clock.sleep(MS_PER_CALL);
// a request ahead of us at the gate may have etched this page
const late = fresh ? null : await this.#pageFromStorage(pageNum, count);
const late = await this.#pageFromStorage(pageNum, count);
if (late) {
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "hit", items: late.items.length });
return late;
@@ -404,7 +357,7 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
}
const kept = this.keep(toRows(data.items, console));
// fetched vs kept: the public cache's drop of private rows shows here
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: fresh ? "refetch" : "miss", fetched: data.items.length, kept: kept.length });
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "miss", fetched: data.items.length, kept: kept.length });
return this.#etch(pageNum, count, data.total, kept);
}
+3 -70
View File
@@ -26,14 +26,10 @@ const wired = async (webappId = "fake-webapp-id") => {
return stub;
};
const HOUR = 60 * 60 * 1000;
/** run alarms until the job ends (bounded, so a runaway job fails); the
* refresh alarm an ended job leaves is not run */
const drain = async (stub: DurableObjectStub & { fillStatus(): Promise<{ state: string } | undefined> }, max = 20) => {
/** run alarms until none is scheduled (bounded, so a runaway job fails) */
const drain = async (stub: DurableObjectStub, max = 20) => {
let ran = 0;
const running = async () => (await stub.fillStatus())?.state === "running";
while (ran < max && (await running()) && (await runDurableObjectAlarm(stub))) ran += 1;
while (ran < max && (await runDurableObjectAlarm(stub))) ran += 1;
expect(ran).toBeLessThan(max);
return ran;
};
@@ -124,9 +120,6 @@ describe("fill job (goal 1e)", () => {
});
await drain(stub);
expect(await stub.fillStatus()).toMatchObject({ state: "done", updatedAt: at });
await runInDurableObject(stub, async (_obj, state) => {
expect(await state.storage.getAlarm()).toBe(FIXED_NOW + 3 * HOUR);
});
});
it("a capped page size fails the fill with the reason, instead of skipping items", async () => {
@@ -177,66 +170,6 @@ describe("fill job (goal 1e)", () => {
expect(await stub.startFill()).toMatchObject({ state: "running", nextPage: 1, pageSize: PAGE_SIZE });
});
it("refreshes 3 hours after a fill: refetches the pages updated in the last 2 days, skips the rest, then waits again", async () => {
// deep account: item n updated n-1 days + 1 hour ago, so items 1–2
// (both on page 1) are within 2 days
const stub = await wired("fake-deep-webapp");
await stub.startFill();
await drain(stub);
await runInDurableObject(stub, async (_obj, state) => {
const alarm = (await state.storage.getAlarm()) ?? 0;
expect(alarm - Date.now()).toBeGreaterThan(2.9 * HOUR);
expect(alarm - Date.now()).toBeLessThanOrEqual(3 * HOUR);
});
expect(await runDurableObjectAlarm(stub)).toBe(true);
expect(await stub.fillStatus()).toMatchObject({ state: "running", nextPage: 1, refetchThrough: 1 });
await drain(stub);
// fetched counts diigo calls; pages 2–3 were hits
expect(await stub.fillStatus()).toMatchObject({ state: "done", pages: 3, fetched: 1 });
await runInDurableObject(stub, async (_obj, state) => {
expect(await state.storage.getAlarm()).not.toBeNull();
});
});
it("a refresh refetches page 1 even when nothing cached is recent: new bookmarks land there", async () => {
const stub = await wired();
await stub.startFill();
await drain(stub);
await runDurableObjectAlarm(stub);
expect(await stub.fillStatus()).toMatchObject({ refetchThrough: 1 });
await drain(stub);
expect(await stub.fillStatus()).toMatchObject({ state: "done", fetched: 1 });
});
it("a failed fill is retried by the next refresh; a stopped one is not", async () => {
const failing = await wired("no-such-webapp");
await failing.startFill();
await drain(failing);
expect((await failing.fillStatus())?.state).toBe("failed");
expect(await runDurableObjectAlarm(failing)).toBe(true);
expect((await failing.fillStatus())?.state).toBe("running");
const stopped = await wired();
await stopped.startFill();
await drain(stopped);
expect((await stopped.stopFill()).state).toBe("stopped");
expect(await runDurableObjectAlarm(stopped)).toBe(false);
});
it("a fill that ended before refreshes existed gets one when the cache next wakes", async () => {
const stub = await wired();
await stub.startFill();
await drain(stub);
await runInDurableObject(stub, async (_obj, state) => {
await state.storage.deleteAlarm();
});
await evictDurableObject(stub);
await stub.fillStatus();
await runInDurableObject(stub, async (_obj, state) => {
expect(await state.storage.getAlarm()).not.toBeNull();
});
});
it("a public cache's fill stores no private rows", async () => {
const stub = testEnv.PUBLIC_DO.get(testEnv.PUBLIC_DO.newUniqueId());
await stub.setup({ webappId: "fake-webapp-id" });
Binary file not shown.

Before

Width:  |  Height:  |  Size: 113 KiB

-295
View File
@@ -1,295 +0,0 @@
---
title: Good Fences Make Good Agents
type: slide
slideOptions:
transition: slide
center: false
---
<style>
.reveal h1 { font-size: 1.8em; }
.reveal h2 { font-size: 1.2em; }
.reveal table { font-size: 0.6em; }
.reveal ul { font-size: 0.7em; }
.reveal pre { font-size: 0.45em; }
</style>
# Good Fences Make Good Agents
*with apologies to Robert Frost*
Dan Connolly · Oct 2026
---
## I bookmark on diigo all week…
<img src="tada-diigo-library.png" style="max-height: 45vh">
…and since Dec 2016 I've wanted them on my blog: [madmode-blog#23](https://github.com/dckc/madmode-blog/issues/23)
---
## 🎉 Monday's issue drafts itself
![tada-potluck-w40](tada-potluck-w40.png)
One click on potluck's EmDash dashboard; I cut, comment, and publish.
[the Loom](https://www.loom.com/share/191c7ad59660477a92d799906e93c4e9)
---
## POLA IO: diigo-cache gets limited fetch
- `makeWebApp().joinpath('diigo.com/api').withHeaders({cookie})`
<img src="weekly-roundup-wiring.png" style="max-height: 80vh">
---
## fluent builder API narrows
- `makeWebApp().joinpath('diigo.com/api').withHeaders({cookie})`
- ✨ diigo-week gets only read-only `viewer`: h-feed of public items
- ✨ the cache id is kept in my password manager
- ⏳ frozen `{ cookie }`
- fresh cookie needs a new access and a **new cache**
---
## ✨ Rotating with mutable cookie MapStore
<img src="cookie-rotation-wiring.png" style="max-height: 80vh">
---
## ✨ Rotating with cookie MapStore
- the cookie lives in Alice's store; `access` reads a read-only facet at every send
- Mallory, holding the instance id, can use the cookie but can't rotate it
---
## It's one piece of a toybox
| story | source | sink | trigger |
|---|---|---|---|
| S1 weekly roundup | diigo, public only | madmode draft | weekly, human edits |
| S2 album to album | **one** Google Photos album | **one** Amazon folder | each insert, nobody watching |
| S3 drag to archive.org | Google Photos | archive.org | drag-and-drop |
Recurring needs: **narrowed capabilities** and **confined generated code**.
---
## The toy version: lend a mower
```js
client.chat.completions.create({
messages: [{
role: 'user',
content: 'you can use this mower for the weekend',
things: { mower },
about: { mower: { ts: 'type Mower { start(), push(), turn(), stop() }' }}
}],
});
```
- the neighbor writes code; a **tenant** runs it in a dynamic worker, endowed with only `mower`
- I lend a **governed** mower: never more than 100 yards (10 cells) from where it started
---
## The fence
```mermaid
sequenceDiagram
participant T as tenant
participant G as governed mower
participant M as mower DO
T->>G: push()
G->>M: push()
T->>G: push()
G->>M: push()
T->>G: push()
G-->>T: throws 'fence: 2 cells from start'
```
⏳ _no governor code; just design: ([lend-the-mower](../good-fences/docs/lend-the-mower.md))
---
## ✨ The model writes code to mow
gpt-oss-120b on Workers AI, given `about.mower` and the story; the test reads the code it writes:
```js
async (env) => {
const { mower } = env;
mower.start(); // cuts the starting cell
for (let c = 0; c < cols; c++) {
for (let i = 0; i < rows - 1; i++) {
mower.push(); // cut next cell
}
...
}
await mower.stop(); // wait for the whole batch to finish
```
✨ no `await` per call: promise pipelining, after one `lamp` example in the prompt
---
## 🪄 A little tipsy
```js
if (c < cols - 1) {
calls.push(env.mower.turn()); // turn right
calls.push(env.mower.push()); // step into next column
calls.push(env.mower.turn()); // turn right again (now facing opposite way)
}
```
- going north: right, step east, right → facing south ✅
- going south: right, step **west**, right → facing north 🐛
- run, it would mow two columns, back and forth: "mowed 2401 cells"
---
## 🙌 Then: Project Think
| ours | [Project Think](https://blog.cloudflare.com/project-think/) |
|---|---|
| the neighbor's harness | a `Think` agent: a DO with sessions, model, prompt, tools |
| `code-mode.ts`, `about` | `@cloudflare/codemode`: the model writes code against types |
| tenants in dynamic workers | `DynamicWorkerExecutor`, `globalOutbound: null` |
"no ambient authority; capabilities granted explicitly via bindings"
---
## ✅ Green
```
⬜⬜⬜⬜⬜⬜⬜⬜
⬜🟩🟩🟩🟩🟩🟩⬜
⬜🟩⬜⬜⬜⬜🟩⬜
⬜🟩⬜⬜⬜⬜🟩⬜
⬜🟩⬜⬜⬜⬜🟩⬜
⬜🟩⬜⬜⬜⬜🟩⬜
⬜🟩⬜⬜⬜⬜🟩⬜
⬜🟩⬜⬜⬜⬜🟩⬜
⬜🟩⬜⬜⬜⬜🟩⬜
⬜🟩⬜⬜⬜⬜🟩⬜
⬜🟩⬜⬜⬜⬜🟩⬜
⬜🟩🟩🟩🟩🟩🟩⬜
⬜⬜⬜⬜⬜⬜⬜⬜
```
model → generated code → sandbox → mower: 36 calls, 30 cells
---
## 🧰 …with ceremony
The mower, as a codemode connector:
```ts
protected tools(): ConnectorTools {
const mower = this.#mower;
return {
start: { description: "put the mower down, facing north, and cut the cell under it", execute: () => mower.start() },
push: { description: "move forward one cell, cutting the cell it enters", execute: () => mower.push() },
turn: { description: "turn right 90 degrees, in place", execute: () => mower.turn() },
stop: { description: "park the mower", execute: () => mower.stop() },
};
}
```
What the model ran, 7 `execute` calls:
```js
await codemode.search('mower')
await state.readdir({ path: '/' })
await codemode.search('lawn')
await codemode.describe('mower.start')
await codemode.describe('mower.push')
await codemode.describe('mower.turn')
await mower.start({}); for (...) await mower.push({}); ...
```
---
## 🧱 Not methods on objects
[Code Mode](https://blog.cloudflare.com/code-mode-mcp/) turns **tools** into a TypeScript API.
- JSON in, JSON out: no reference goes in, no object comes back
- so a neighbor can't hand what it holds to the next neighbor
One floor down, Workers RPC and Cap'n Web do pass references and pipeline calls.
---
## 🧱 Identity, in two halves
| | durable | passable |
|---|---|---|
| Durable Object id | ✅ | ❌ a string plus a binding the receiver must already hold |
| Workers RPC / Cap'n Web stub | ❌ dies with its request or session | ✅ |
| Endo / OCapN reference | ✅ | ✅ |
> durable, passable object identity. I've been using endo for so long that it just feels like air to me.
---
## 🧱 Where it bites
- S2, album to album: **nobody watching**, so no session to keep a stub alive
- a scavenger hunt: a kid buys a Pete Rose card from the shopkeeper → it admits him to the clubhouse → Sam's telescope there reads a QR code a mile away → step 7 → he wins a bicycle
- every hop is a reference, held for years
- is the card genuine? the clubhouse has to ask its issuer
---
## The turn: Cloudflare as a netlayer
OCapN on top: sturdyrefs for durability, live refs within a session, third-party handoffs.
| their technique | ours, on references |
|---|---|
| code mode against generated types | code against `about` for the objects it holds |
| `search` / `describe` over many tools | a petname directory the model can browse |
| saved snippets | tenant code exported as an entrypoint, handed on |
| `runFiber` / `stash` | vat persistence |
| sub-agents as DO facets | tenants as child vats |
Still load-bearing: Worker Loader, Durable Objects and facets, Workers RPC, Cap'n Web, Workers AI.
---
## 🧮 Recap +
✅ the weekly roundup drafts in one click
✨ webkeys in a password field; a read-only facet for the plugin
✨ model-written code pipelines, in a confined dynamic worker
🙌 Project Think: a green spike in an evening
---
## 🧮 Recap -
⏳ nothing deployed; the governor not built
🪄 tipsy tenants: always turn right
🧰 codemode ceremony: `{ description, execute }`, `search`, `describe`
🧱 no durable, passable references: an OCapN layer to build
---
## Sources
- [Good Fences Make Good Agents: design story and IBIS](good-fences-make-good-agents.md)
- [toybox user stories](../toybox-stories.md)
- [Project Think](https://blog.cloudflare.com/project-think/) · [Code Mode](https://blog.cloudflare.com/code-mode-mcp/)
- [OCapN](https://ocapn.org/) · [Cap'n Web](https://github.com/cloudflare/capnweb)
-29
View File
@@ -1,29 +0,0 @@
# learn by watching: an agent that finds a site's hidden API
social.coop and zotero publish nice APIs. diigo doesn't: for [diigo-cache](../diigo-cache/README.md) we opened browser devtools, watched the requests the web app made, and wrote a client for them by hand ([the mm-diigo diigo-bak scripts](https://github.com/dckc/mm-diigo)). What if a bot did that part?
## the workflow
1. **I log in, by hand.** Whatever site: diigo, my bank. The password never leaves me; the session lives in the browser.
2. **I grab a debug capability** on that browser: a [PinchTab](https://github.com/pinchtab/pinchtab) token, or a Chrome DevTools Protocol / WebDriver BiDi endpoint.
3. **I hand it to a smart coding agent** (e.g. Opus) and say what I'm about to do: "get last month's transactions."
4. **It watches me** navigate and do the task, recording the proceedings: network requests and responses, plus my clicks.
5. **It sanitizes the recording** into fixtures for unit tests: cookies, auth headers, account numbers, and names replaced with stand-ins.
6. **It writes code** that later uses the debug capability deterministically, with no model in the loop, tested against those fixtures.
## small steps within a policy
The generated code only does small steps, such as `listTransactions({ from, to })` or `bookmarksPage(n)`. More sophisticated code (a scheduler, another agent) can drive them, but the steps themselves must clearly stay within a policy:
> I'm only downloading my bank transactions, not paying bills.
The policy is code, not a prompt: a facet in front of the debug capability that allows only the requests the recording justified (method + URL pattern, e.g. `GET /accounts/*/transactions`) and refuses everything else. The driver holds only the facet, never the raw capability, so a confused or compromised driver still can't reach `POST /payments`. This is the [governed mower](good-fences-make-good-agents.md) again: I attenuate before I hand it over.
Raw CDP is nearly unlimited authority (it can evaluate arbitrary JS in the page), which is why only the watching phase, with me present, uses it directly.
## open questions
- **Replay or drive?** If the recorded API is plain HTTP, extract the session and replay it with `fetch`, as diigo-cache does; the facet then wraps `fetch`, not a browser. Sites that need in-page JS (anti-bot tokens, signed requests) have to be driven through the browser.
- **Who reviews the policy?** The agent proposes the allowlist from the recording; I approve it. Is a diff of URL patterns reviewable enough?
- **Drift:** sites change their private APIs. The fixtures make breakage loud; re-watching should be cheap.
- **Session lifetime:** the facet is only as durable as the login. Re-login stays manual.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 240 KiB

-148
View File
@@ -1,148 +0,0 @@
<!doctype html>
<html><head><meta charset="utf-8">
<title>weekly roundup on main: who holds what</title>
<!-- drawn after the style of MarkM's ERTP slides, as cookie-rotation-wiring.html on the webapp-cookie-rotation branch; weekly-roundup-wiring.png is a headless-Chromium screenshot of this page -->
<style>
html, body { margin: 0; background: #fff; }
.sans { font-family: "Helvetica Neue", "DejaVu Sans", sans-serif; }
.obj { font-family: "DejaVu Serif", serif; font-style: italic; }
.mono { font-family: "DejaVu Sans Mono", monospace; }
</style></head>
<body>
<svg id="c" xmlns="http://www.w3.org/2000/svg" width="1120" height="820" viewBox="0 0 1120 820"
role="img" aria-labelledby="title desc">
<title id="title">weekly roundup on main: who holds what</title>
<desc id="desc">Three actors and two makers. Alice holds a cache id, saved in her
password manager, which refers to a DiigoCache. Each DiigoCache refers to its
wiring table: webappId and publicId. webappId refers to an access object made
by makeWebApp; publicId refers to a PublicCache, which refers to the same
access. Each access refers to its init table: url and headers, and the
headers hold the diigo session cookie. A viewer facet reads the PublicCache
and can't fetch or write; diigo-week, the potluck plugin, reaches only the
viewer, as the public page's h-feed. Mallory, who learned the instance id,
also refers to access, so she can use the cookie. The wiring is set once, so
when Alice logs in again she has to mint a new access and a new cache.</desc>
<defs>
<radialGradient id="ball" cx="40%" cy="35%" r="70%">
<stop offset="0%" stop-color="#7cc8f8"/>
<stop offset="100%" stop-color="#3aa6ee"/>
</radialGradient>
<linearGradient id="objfill" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#6cbcf4"/>
<stop offset="100%" stop-color="#4aa8ec"/>
</linearGradient>
<marker id="head" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="9" markerHeight="9" orient="auto-start-reverse">
<path d="M0,0 L10,5 L0,10 z" fill="#1d4f7a"/>
</marker>
</defs>
</svg>
<script>
const svg = document.getElementById("c");
const NS = "http://www.w3.org/2000/svg";
const el = (name, attrs, parent = svg) => {
const e = document.createElementNS(NS, name);
for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v);
parent.appendChild(e);
return e;
};
const text = (x, y, s, cls, attrs = {}) => {
const t = el("text", { x, y, class: cls, "text-anchor": "middle", fill: "#1d3550", ...attrs });
t.textContent = s;
return t;
};
const INK = "#1d4f7a";
const dot = (x, y) => el("circle", { cx: x, cy: y, r: 4.5, fill: INK });
/** a reference: dot at the holder, arrowhead at the target */
const ref = (x1, y1, x2, y2, bend = 0, extra = {}) => {
dot(x1, y1);
const mx = (x1 + x2) / 2 - (y2 - y1) * bend, my = (y1 + y2) / 2 + (x2 - x1) * bend;
el("path", { d: `M${x1},${y1} Q${mx},${my} ${x2},${y2}`, fill: "none", stroke: INK, "stroke-width": 2, "marker-end": "url(#head)", ...extra });
};
// maker box: a pale rounded region, with stacked instances inside
function maker(x, y, w, h, label) {
el("rect", { x, y, width: w, height: h, rx: 26, fill: "#d6ecfb", stroke: "#b5dbf5", "stroke-width": 1.5 });
text(x + 18, y + 30, label, "obj", { "text-anchor": "start", "font-size": 20 });
for (let i = 2; i >= 0; i -= 1) {
el("rect", {
x: x + 18 + i * 9, y: y + 48 + i * 9, width: w - 52, height: h - 82, rx: 22,
fill: "#c8e5fa", stroke: "#8ec9f2", "stroke-width": 1.5, "fill-opacity": 0.9,
});
}
}
// an object: rounded square, optionally stacked (several made)
function obj(x, y, w, h, label, stacked = false) {
const n = stacked ? 3 : 1;
for (let i = n - 1; i >= 0; i -= 1) {
el("rect", { x: x + i * 7, y: y - i * 7, width: w, height: h, rx: 12, fill: "url(#objfill)", stroke: "#2f8fd6", "stroke-width": 1.5 });
}
text(x + w / 2, y + h / 2 + 7, label, "obj", { "font-size": 19 });
}
function actor(cx, cy, label) {
el("circle", { cx, cy, r: 52, fill: "url(#ball)", stroke: "#2f8fd6", "stroke-width": 1.5 });
text(cx, cy + 6, label, "sans", { "font-size": label.length > 8 ? 15 : 17 });
}
// a table like the ERTP ledger
function table(x, y, title, rows, colW) {
const rowH = 28, w = colW[0] + colW[1];
el("rect", { x, y, width: w, height: 36 + rowH * rows.length, fill: "#5fb5f2", stroke: "#2f8fd6", "stroke-width": 1.5 });
text(x + w / 2, y + 25, title, "obj", { "font-size": 18 });
rows.forEach(([k, v], i) => {
const ry = y + 36 + i * rowH;
el("line", { x1: x, y1: ry, x2: x + w, y2: ry, stroke: "#2f8fd6", "stroke-width": 1.2 });
text(x + 10, ry + 19, k, "mono", { "text-anchor": "start", "font-size": 14 });
if (v) text(x + colW[0] + 10, ry + 19, v, "mono", { "text-anchor": "start", "font-size": 14 });
});
el("line", { x1: x + colW[0], y1: y + 36, x2: x + colW[0], y2: y + 36 + rowH * rows.length, stroke: "#1d4f7a", "stroke-width": 1.5 });
return { rowY: (i) => y + 36 + i * rowH + rowH / 2, x, w, colX: x + colW[0] };
}
// speech bubble (Alice, after logging in to diigo again)
el("path", {
d: "M30,22 h470 a16,16 0 0 1 16,16 v34 a16,16 0 0 1 -16,16 h-330 l-38,48 l6,-48 h-102 a16,16 0 0 1 -16,-16 v-34 a16,16 0 0 1 16,-16 z",
fill: "#d9d9d9", stroke: "#555", "stroke-width": 2,
});
text(46, 62, "fresh cookie? mint a new access, a new cache", "mono", { "text-anchor": "start", "font-size": 16, fill: "#222" });
// actors
actor(150, 200, "Alice");
actor(560, 200, "diigo-week");
actor(930, 200, "Mallory");
// makers
maker(30, 320, 500, 470, "diigo-cache");
maker(590, 320, 500, 470, "makeWebApp");
// diigo-cache insides
obj(70, 410, 150, 80, "DiigoCache", true);
const wiring = table(270, 410, "wiring", [["webappId", "…"], ["publicId", "…"]], [110, 90]);
obj(70, 610, 150, 80, "PublicCache", true);
obj(300, 640, 120, 60, "viewer", true);
// makeWebApp insides
obj(640, 560, 140, 90, "access", true);
const init = table(840, 420, "init", [["url", "diigo…"], ["headers", "{cookie}"]], [100, 105]);
// references
ref(140, 228, 130, 403, 0.03); // Alice → DiigoCache (cache id)
ref(560, 228, 380, 627, -0.04); // diigo-week → viewer
ref(930 - 14, 200 + 20, 740, 553, -0.08); // Mallory → access
ref(160, 450, wiring.x - 2, wiring.rowY(0), 0.05); // DiigoCache → wiring
ref(wiring.colX + 40, wiring.rowY(0), 646, 580, -0.12); // webappId → access
ref(wiring.colX + 40, wiring.rowY(1), 165, 598, -0.08); // publicId → PublicCache
ref(200, 688, 632, 640, 0.25); // PublicCache → access
ref(306, 675, 232, 668, 0.1); // viewer → PublicCache (read)
ref(780, 600, init.x - 2, init.rowY(1), -0.1); // access → init
// captions
const cap = (x, y, s, attrs = {}) => text(x, y, s, "sans", { "font-size": 14, fill: "#33536f", ...attrs });
cap(270, 286, "cache id, in the password manager", {});
cap(560, 120, "potluck plugin: /public/<user>, an h-feed;", {});
cap(560, 138, "reaches only the viewer", {});
cap(930, 118, "holds the instance id:", {});
cap(930, 136, "uses the cookie", {});
cap(280, 806, "setup(wiring) is one-shot: different values are refused", {});
cap(840, 806, "the cookie rides in init.headers, fixed at mint", {});
</script>
</body></html>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 125 KiB

-185
View File
@@ -1,185 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Lend the Mower</title>
<style>
:root {
--bg: #f7f7f2; --fg: #1d2318; --muted: #6b7262; --line: #d9dccf;
--grass: #e4e8d6; --cut: #3f9b3f; --mower: #c0392b; --card: #fff;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #15180f; --fg: #e8ecdc; --muted: #9aa38c; --line: #2e3426;
--grass: #262c1d; --cut: #4cb84c; --mower: #ff6b5b; --card: #1d2116;
}
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--fg); font: 15px/1.45 system-ui, sans-serif; }
header { padding: 12px 16px; border-bottom: 1px solid var(--line); display: flex; gap: 12px; align-items: baseline; flex-wrap: wrap; }
header h1 { font-size: 18px; margin: 0; }
header .muted { color: var(--muted); font-size: 13px; }
main { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 16px; padding: 16px; max-width: 1200px; margin: 0 auto; }
@media (max-width: 800px) { main { grid-template-columns: 1fr; } }
#chat { display: flex; flex-direction: column; min-height: 60vh; }
#log { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; padding-bottom: 8px; }
.msg { padding: 8px 12px; border-radius: 8px; background: var(--card); border: 1px solid var(--line); white-space: pre-wrap; overflow-wrap: anywhere; }
.msg.user { align-self: flex-end; background: var(--cut); color: #fff; border: none; max-width: 85%; }
.msg.error { border-color: var(--mower); color: var(--mower); }
details { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: 6px 12px; }
details summary { cursor: pointer; color: var(--muted); font-size: 13px; }
pre { margin: 6px 0 0; overflow-x: auto; font-size: 12.5px; }
form { display: flex; gap: 8px; }
input[type=text] { flex: 1; padding: 10px; border-radius: 8px; border: 1px solid var(--line); background: var(--card); color: var(--fg); font: inherit; }
button { padding: 10px 16px; border-radius: 8px; border: none; background: var(--cut); color: #fff; font: inherit; cursor: pointer; }
button:disabled { opacity: .5; cursor: default; }
#yard-box { display: flex; flex-direction: column; gap: 8px; }
#yard { width: 100%; aspect-ratio: 1; image-rendering: pixelated; border-radius: 8px; border: 1px solid var(--line); background: var(--grass); }
#stats { color: var(--muted); font-size: 13px; }
a { color: var(--cut); }
</style>
</head>
<body>
<header>
<h1>Lend the Mower</h1>
<span class="muted">yard <b id="yard-name"></b> · <a id="new-yard" href="#">new yard</a> · <span id="status">connecting…</span></span>
</header>
<main>
<section id="chat">
<div id="log"></div>
<form id="send">
<input id="text" type="text" autocomplete="off" value="you can use this mower for the weekend">
<button id="go" disabled>Send</button>
</form>
</section>
<section id="yard-box">
<canvas id="yard" width="400" height="400"></canvas>
<div id="stats"></div>
</section>
</main>
<script type="module">
const $ = (id) => document.getElementById(id);
const name = location.hash.slice(1) || crypto.randomUUID().slice(0, 8);
if (!location.hash) history.replaceState(null, "", `#${name}`);
$("yard-name").textContent = name;
$("new-yard").href = `#${crypto.randomUUID().slice(0, 8)}`;
addEventListener("hashchange", () => location.reload());
const css = (v) => getComputedStyle(document.documentElement).getPropertyValue(v).trim();
const arrows = ["▲", "▶", "▼", "◀"];
/** draws the yard: cut cells green, the mower an arrow for its heading */
const drawYard = ({ width, height, x, y, heading, cut }) => {
const canvas = $("yard");
const cell = Math.floor(canvas.width / Math.max(width, height));
const g = canvas.getContext("2d");
g.fillStyle = css("--grass");
g.fillRect(0, 0, canvas.width, canvas.height);
g.fillStyle = css("--cut");
for (const c of cut) {
const [cx, cy] = c.split(",").map(Number);
g.fillRect(cx * cell, cy * cell, cell, cell);
}
g.fillStyle = css("--mower");
g.font = `${cell}px system-ui`;
g.textAlign = "center";
g.textBaseline = "middle";
g.fillText(arrows[heading] ?? "●", x * cell + cell / 2, y * cell + cell / 2 + 1);
$("stats").textContent = `${cut.length} of ${width * height} cells cut · mower at (${x}, ${y}) facing ${["north", "east", "south", "west"][heading]}`;
};
const log = $("log");
const scroll = () => (log.scrollTop = log.scrollHeight);
const say = (text, cls = "") => {
const div = document.createElement("div");
div.className = `msg ${cls}`;
div.textContent = text;
log.append(div);
scroll();
return div;
};
const summarize = (output) => {
if (!output || typeof output !== "object") return JSON.stringify(output);
const calls = output.calls?.length;
return [output.status, calls !== undefined ? `${calls} mower calls` : "", output.error ?? ""].filter(Boolean).join(" · ");
};
/** one code run: the code the model wrote, and what came of it */
const codeBlock = (code) => {
const d = document.createElement("details");
const s = document.createElement("summary");
s.textContent = "code: running…";
const pre = document.createElement("pre");
pre.textContent = code;
d.append(s, pre);
log.append(d);
scroll();
return { done: (text) => (s.textContent = `code: ${text}`) };
};
/** renders a stored message, e.g. history sent on connect */
const renderMessage = ({ role, parts = [] }) => {
for (const p of parts) {
if (p.type === "text" && p.text) say(p.text, role === "user" ? "user" : "");
else if (p.type?.startsWith("tool-") && p.input?.code !== undefined) {
const b = codeBlock(p.input.code);
b.done(p.state === "output-error" ? `error: ${p.errorText}` : summarize(p.output));
}
}
};
const ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/agents/neighbor/${encodeURIComponent(name)}`);
let reply = null;
const blocks = new Map();
const setBusy = (busy) => ($("go").disabled = busy || ws.readyState !== WebSocket.OPEN);
ws.addEventListener("open", () => { $("status").textContent = "connected"; setBusy(false); });
ws.addEventListener("close", () => { $("status").textContent = "disconnected; reload to reconnect"; setBusy(true); });
ws.addEventListener("message", ({ data }) => {
let msg;
try { msg = JSON.parse(data); } catch (e) { console.warn("unparsed message", data, e); return; }
if (msg.type === "cf_agent_state" && msg.state) drawYard(msg.state);
else if (msg.type === "cf_agent_chat_messages" && Array.isArray(msg.messages)) {
log.replaceChildren();
msg.messages.forEach(renderMessage);
} else if (msg.type === "cf_agent_use_chat_response") {
if (msg.error) say(String(msg.body), "error");
for (const line of String(msg.body ?? "").split("\n").filter(Boolean)) {
let c;
try { c = JSON.parse(line.replace(/^data: /, "")); } catch { continue; }
if (c.type === "text-delta") {
reply ??= say("");
reply.textContent += c.delta;
scroll();
} else if (c.type === "tool-input-available") {
reply = null;
blocks.set(c.toolCallId, codeBlock(c.input?.code ?? JSON.stringify(c.input)));
} else if (c.type === "tool-output-available") blocks.get(c.toolCallId)?.done(summarize(c.output));
else if (c.type === "tool-output-error") blocks.get(c.toolCallId)?.done(`error: ${c.errorText}`);
else if (c.type === "error") say(c.errorText ?? JSON.stringify(c), "error");
}
if (msg.done) { reply = null; setBusy(false); }
}
});
$("send").addEventListener("submit", (e) => {
e.preventDefault();
const text = $("text").value.trim();
if (!text) return;
say(text, "user");
$("text").value = "";
setBusy(true);
reply = null;
const id = crypto.randomUUID();
ws.send(JSON.stringify({
type: "cf_agent_use_chat_request",
id,
init: { method: "POST", body: JSON.stringify({
trigger: "submit-message",
messages: [{ id: `u-${id}`, role: "user", parts: [{ type: "text", text }] }],
}) },
}));
});
</script>
</body>
</html>
+7 -22
View File
@@ -21,27 +21,13 @@ const headings = [
[-1, 0], // west
] as const;
/** where a mower is and what it has cut, as `"x,y"` cells; `heading` indexes north, east, south, west */
export type Yard = Readonly<{
width: number;
height: number;
x: number;
y: number;
heading: number;
cut: readonly string[];
}>;
/** a mower on a yard, picking up where `yard` left off; pushing past an
* edge wraps to the other side (6d). `onMove` hears each move. */
export const makeMower = (yard: Yard, onMove: (yard: Yard) => void = () => {}) => {
const { width, height } = yard;
let { x, y, heading } = yard;
const cut = new Set(yard.cut);
const view = (): Yard => ({ width, height, x, y, heading, cut: [...cut] });
const cutHere = () => {
cut.add(`${x},${y}`);
onMove(view());
};
/** a mower on a `width` × `height` yard, starting at `at`; pushing past an
* edge wraps to the other side (6d) */
export const makeMower = ({ width, height, at }: { width: number; height: number; at: { x: number; y: number } }) => {
let { x, y } = at;
let heading = 0;
const cut = new Set<string>();
const cutHere = () => cut.add(`${x},${y}`);
return {
start() {
heading = 0;
@@ -55,7 +41,6 @@ export const makeMower = (yard: Yard, onMove: (yard: Yard) => void = () => {}) =
},
turn() {
heading = (heading + 1) % headings.length;
onMove(view());
},
stop() {},
cutCells: () => [...cut],
+5 -33
View File
@@ -1,44 +1,16 @@
/** @file The neighbor's harness as a Project Think agent, lent a mower. */
import { Think } from "@cloudflare/think";
import type { Connection } from "agents";
import { createExecuteTool } from "@cloudflare/think/tools/execute";
import { createWorkersAI } from "workers-ai-provider";
import { MAX_TOKENS, MODEL } from "./model.ts";
import { MowerConnector } from "./mower-connector.ts";
import { makeMower, type Mower, type Yard } from "./mower.ts";
import { makeMower } from "./mower.ts";
type Env = { AI: Ai; LOADER: WorkerLoader };
/** how often, at most, a mowing yard goes out to the page */
const PUBLISH_MS = 200;
export class Neighbor extends Think<Env, Yard> {
initialState: Yard = { width: 40, height: 40, x: 20, y: 20, heading: 0, cut: [] };
#mower: Mower | undefined;
#pending: Yard | undefined;
/** the mower, back where the saved yard left it; its moves are saved and
* broadcast at most every PUBLISH_MS */
get #lent(): Mower {
this.#mower ??= makeMower(this.state, (yard) => {
const idle = this.#pending === undefined;
this.#pending = yard;
if (!idle) return;
setTimeout(() => {
const latest = this.#pending;
this.#pending = undefined;
if (latest) this.setState(latest);
}, PUBLISH_MS);
});
return this.#mower;
}
/** the yard is the mower's to change; pages only watch */
validateStateChange(_next: Yard, source: Connection | "server") {
if (source !== "server") throw Error("the yard changes only by mowing");
}
export class Neighbor extends Think<Env> {
#mower = makeMower({ width: 40, height: 40, at: { x: 20, y: 20 } });
getModel() {
return createWorkersAI({ binding: this.env.AI })(MODEL);
@@ -60,13 +32,13 @@ lend you something, put it to use, then tell me what you did.`;
getTools() {
return {
execute: createExecuteTool(this, {
connectors: [new MowerConnector(this.ctx, this.env, this.#lent)],
connectors: [new MowerConnector(this.ctx, this.env, this.#mower)],
}),
};
}
/** the cells the mower has cut, as `"x,y"` */
cutCells() {
return this.#lent.cutCells();
return this.#mower.cutCells();
}
}
-20
View File
@@ -1,20 +0,0 @@
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "good-fences3",
"main": "./src/worker.ts",
"compatibility_date": "2026-10-01",
"compatibility_flags": ["nodejs_compat"],
// the chat page; other paths fall through to the Worker
"assets": { "directory": "./public" },
"ai": { "binding": "AI" },
// Dynamic Workers: deploying this binding takes the Workers Paid plan
"worker_loaders": [{ "binding": "LOADER" }],
"durable_objects": {
"bindings": [{ "name": "Neighbor", "class_name": "Neighbor" }]
},
"exports": {
"Neighbor": { "type": "durable-object", "storage": "sqlite" },
// codemode's runtime, a facet of the agent's DO
"CodemodeRuntime": { "type": "durable-object", "storage": "sqlite" }
}
}
+4
View File
@@ -0,0 +1,4 @@
state/
admin.sock
switchboard-*.sock
dist/
+68
View File
@@ -0,0 +1,68 @@
# toybox
Vats whose code is installed at runtime: each vat is a Durable Object whose app runs as a [facet](https://developers.cloudflare.com/dynamic-workers/usage/durable-object-facets/) on code loaded through workerd's Worker Loader. Think `vatAdmin.createVat(bundle)`, with a supervisor per vat. Vats have no names: creating one returns its id, which addresses it only on the admin socket. Everything else a vat can do or be reached by is granted explicitly: egress by labels it may fetch within, ingress by labels it is mounted at.
- [supervisor.js](supervisor.js): `Vat` stores code by SHA-256 and runs the app on it; `Directory` holds the mounts; `Public` (the ingress) and `Admin` are the two entrypoints; `Egress` is an egress grant.
- [switchboard.js](switchboard.js): a separate workerd process, the vats' only way out, after [Flower](https://github.com/NuxiNL/flower)'s switchboard: each of its sockets serves a Cap'n Web `Handle` with fixed labels, and `constrain(labels)` returns a narrower one.
- [labels.js](labels.js): Flower's label rule, shared by both: labels only accumulate, a missing key matches anything, and a key both sides set must agree. Ingress lookup is stricter (below).
- [config.capnp](config.capnp): the sockets have no addresses; whoever starts workerd hands them in, so holding a socket is the authority it grants.
| socket | reaches | what its holder can do |
|---|---|---|
| `http` | `Public` | reach the vat mounted at labels the request carries |
| `admin` | `Admin` | `POST /` with an ES module body: create a vat and start it; the reply is `{"vat": <id>, "hash": <code hash>}`. `PUT /<id>` with a body: upgrade it; its storage carries over. `PUT /by-name/<name>`: the same, for a vat from before ids. |
Every start states the vat's grants, as JSON labels in query parameters; absent means none:
- `?egress=<labels>`: what the app may fetch (below).
- `?mount=<labels>`: where the ingress finds it. A mount must conflict with every other one (some shared key, different values), so no request can carry two mounts' labels; an overlapping mount is a 409.
## Ingress
A request's labels are its query parameters; a key given twice is a 400. Routing carries no secrets: a URL ends up in logs and `Referer`s. A secret travels in-band, as on a webkey page: the page keeps it in its fragment, reaches the vat by public labels, and sends it in the body of a call, which the vat checks like a swissnum.
The request reaches the vat whose mount labels it carries, every one with the same value. That is stricter than Flower's match (no conflicting key): an ingress client holds no constrained handle that supplies labels for it, so it reaches a vat only by naming every label of its mount. The path is the app's own. The app sees the mount's and the request's labels together in `Toybox-Connection-Labels` (JSON), as a Flower server gets its connection labels. Responses carry `Referrer-Policy: no-referrer`.
## Egress
An app must export `class App extends DurableObject` (see [apps/](apps/)). Its global `fetch` always throws: nothing in a vat is ambient. A grant arrives as `env.egress`, an `Egress` with the labels in `ctx.props`. Its `fetch`, WebSocket upgrades included, goes through a switchboard handle constrained to those labels; the switchboard refuses the rest, which comes back as a 403. `env.egress.constrain(labels)` returns a narrower `Egress`. It is an object, so the app can pass it to whichever of its parts should have it.
| label | constrains |
|---|---|
| `scheme` | `http` or `https` |
| `host` | host name or address, no port |
| `port` | explicit, or the scheme's default |
| `network` | set by the switchboard socket: `public` or `local` |
The switchboard has two sockets, so two root handles: `public` (no loopback or private addresses) and `local`. toybox holds one, as an external service (`-e switchboard=unix:…`): `pnpm start` and the systemd units give it `public`; the tests give theirs `local` to reach an echo server.
## Run it
```sh
pnpm install
pnpm test # real workerds: createVat, upgrade, mounts, egress grants and constrain, fetch and WebSocket out, crash and restart
pnpm switchboard # systemd-socket-activate on ./switchboard-public.sock and ./switchboard-local.sock
pnpm start # likewise on 127.0.0.1:8787 and ./admin.sock; state in ./state
```
Then, in a third terminal:
```sh
admin() { curl -sg --unix-socket admin.sock "$@"; }
alice=$(admin -X POST --data-binary @apps/counter-v1.js 'http://toybox/?mount={"vat":"alice"}' | jq -r .vat)
curl 'localhost:8787/?vat=alice' # v1 count 1
admin -X PUT --data-binary @apps/counter-v2.js "http://toybox/$alice?mount={\"vat\":\"alice\"}"
curl 'localhost:8787/?vat=alice' # v2 count 2
admin -X POST --data-binary @apps/egress-probe.js 'http://toybox/?mount={"vat":"erin"}&egress={"host":"example.com"}'
curl 'localhost:8787/?vat=erin&url=https://example.com/' # got: <!doctype html>…
curl 'localhost:8787/?vat=erin&url=https://example.org/' # got: egress refused: egress to example.org not granted
```
## Under systemd
[systemd/](systemd/) has socket and service pairs for toybox and its switchboard, assuming this directory is installed at `/opt/toybox`. toybox gets no network of its own (`PrivateNetwork=yes`): only the two sockets it is handed and the switchboard's `public` socket, which only members of the `toybox` group can open. The switchboard binds its `local` socket in its own 0700 runtime directory, so no other unit holds that handle.
Neither unit has been run under the system manager yet.
`PrivateNetwork=` needs the system manager; as a `systemd-run --user` unit, systemd logs "lack privileges for network namespace, proceeding without".
+8
View File
@@ -0,0 +1,8 @@
import { DurableObject } from "cloudflare:workers";
export class App extends DurableObject {
fetch() {
const n = (this.ctx.storage.kv.get("n") ?? 0) + 1;
this.ctx.storage.kv.put("n", n);
return new Response(`v1 count ${n}\n`);
}
}
+8
View File
@@ -0,0 +1,8 @@
import { DurableObject } from "cloudflare:workers";
export class App extends DurableObject {
fetch() {
const n = (this.ctx.storage.kv.get("n") ?? 0) + 1;
this.ctx.storage.kv.put("n", n);
return new Response(`v2 count ${n}\n`);
}
}
+27
View File
@@ -0,0 +1,27 @@
import { DurableObject } from "cloudflare:workers";
/** `?url=<target>` fetches it through `env.egress` (narrowed by `&constrain=<labels as JSON>`, if given); with `&ws=1`, opens a WebSocket there and reports the echo of "hello". */
export class App extends DurableObject {
async fetch(request) {
const params = new URL(request.url).searchParams;
const target = params.get("url");
if (!this.env.egress) return new Response("no egress granted\n");
try {
const egress = params.has("constrain")
? await this.env.egress.constrain(JSON.parse(params.get("constrain")))
: this.env.egress;
if (!params.has("ws")) return new Response(`got: ${await (await egress.fetch(target)).text()}\n`);
const resp = await egress.fetch(target, { headers: { Upgrade: "websocket" } });
const ws = resp.webSocket;
if (!ws) return new Response(`no websocket: ${resp.status} ${await resp.text()}`);
ws.accept();
const reply = new Promise((resolve) => ws.addEventListener("message", (e) => resolve(e.data)));
ws.send("hello");
const got = await reply;
ws.close();
return new Response(`echo: ${got}\n`);
} catch (e) {
return new Response(`refused: ${e.message}\n`);
}
}
}
+9
View File
@@ -0,0 +1,9 @@
import { DurableObject } from "cloudflare:workers";
/** Reports its path and its connection labels. */
export class App extends DurableObject {
fetch(request) {
const { pathname } = new URL(request.url);
return new Response(`${pathname} ${request.headers.get("Toybox-Connection-Labels")}\n`);
}
}
+7
View File
@@ -0,0 +1,7 @@
import { DurableObject } from "cloudflare:workers";
export class App extends DurableObject {
async fetch() {
try { await fetch("https://example.com/"); return new Response("fetch ALLOWED\n"); }
catch (e) { return new Response(`fetch refused: ${e.message}\n`); }
}
}
+16
View File
@@ -0,0 +1,16 @@
/** @file Bundle the supervisor and the OCapN vat runtime for workerd (see config.capnp). */
import { build } from "esbuild";
const common = {
bundle: true,
format: "esm",
platform: "neutral",
mainFields: ["module", "main"],
conditions: ["workerd", "import"],
external: ["cloudflare:workers", "node:*"],
logLevel: "warning",
};
await build({ ...common, entryPoints: ["supervisor.js"], outfile: "dist/supervisor.js", external: [...common.external, "vat-runtime.txt"] });
// loaded as text, beside the vat's own module (vat.js)
await build({ ...common, entryPoints: ["vat-runtime.js"], outfile: "dist/vat-runtime.js", external: [...common.external, "./vat.js"] });
+33
View File
@@ -0,0 +1,33 @@
/**
* @file An OCapN client for the admin socket, from Node: it registers its
* own gateway with the router there and reaches every other peer through
* it. Run under SES (see test/lockdown.js).
*/
import { makeClient, swissnumFromBytes } from "@endo/ocapn";
import { newWebSocketRpcSession } from "capnweb";
import WebSocket from "ws";
import { locationOf, makeRpcNetLayer } from "./netlayer.js";
/**
* An OCapN client on the admin socket: registers its own gateway with the
* router there, and reaches every other peer through it.
*
* @param {string} adminSock
* @param {string} designator
* @param {{ verbose?: boolean }} [opts] OCapN logging
*/
export const connectClient = async (adminSock, designator, { verbose = false } = {}) => {
const ws = new WebSocket(`ws+unix:${adminSock}:/`);
await new Promise((resolve, reject) => (ws.once("open", resolve), ws.once("error", reject)));
const session = newWebSocketRpcSession(ws);
const ocapn = makeClient({ debugLabel: designator, verbose });
const netlayer = await ocapn.registerNetlayer(
makeRpcNetLayer({ designator, openGateway: (d) => session.gateway(d) }),
);
await session.register(designator, netlayer.gateway);
const vatAdmin = await ocapn.enlivenSturdyRef(
ocapn.makeSturdyRef(locationOf("vatAdmin"), swissnumFromBytes(new TextEncoder().encode("vatAdmin"))),
);
return { vatAdmin, close: () => (ocapn.shutdown(), ws.close()) };
};
+46
View File
@@ -0,0 +1,46 @@
# toybox: vats whose code is installed at runtime, each a Durable Object facet.
#
# Sockets have no address here: whoever starts workerd hands them in
# (-S name=fd from systemd, or -s name=addr), so holding a socket is the
# authority it grants. `state` is likewise overridden with -d state=<dir>,
# and the switchboard's address with -e switchboard=<addr>.
using Workerd = import "/workerd/workerd.capnp";
const config :Workerd.Config = (
services = [
(name = "main", worker = .supervisor),
(name = "nowhere", network = (allow = [])),
# the way out: one switchboard socket, i.e. one handle (see switchboard.capnp)
(name = "switchboard", external = (address = "unix:switchboard.sock", http = ())),
(name = "state", disk = (path = "state", writable = true)),
],
sockets = [
# the ingress: reach the vat mounted at a request's labels
(name = "http", http = (), service = (name = "main", entrypoint = "Public")),
# create vats, install code, grant egress and ingress
(name = "admin", http = (), service = (name = "main", entrypoint = "Admin")),
],
);
const supervisor :Workerd.Worker = (
compatibilityDate = "2026-10-01",
# bundled by build.js
modules = [
(name = "supervisor.js", esModule = embed "dist/supervisor.js"),
(name = "vat-runtime.txt", text = embed "dist/vat-runtime.js"),
],
durableObjectNamespaces = [
(className = "Vat", uniqueKey = "toybox-vat", enableSql = true),
(className = "Directory", uniqueKey = "toybox-directory", enableSql = true),
(className = "VatAdmin", uniqueKey = "toybox-vat-admin", enableSql = true),
],
durableObjectStorage = (localDisk = "state"),
bindings = [
(name = "VATS", durableObjectNamespace = "Vat"),
(name = "DIRECTORY", durableObjectNamespace = "Directory"),
(name = "VAT_ADMIN", durableObjectNamespace = "VatAdmin"),
(name = "LOADER", workerLoader = ()),
(name = "SWITCHBOARD", service = "switchboard"),
],
globalOutbound = "nowhere",
);
+53
View File
@@ -0,0 +1,53 @@
/**
* @file Egress labels, after [Flower](https://github.com/NuxiNL/flower)'s
* switchboard: string key-value pairs that only accumulate. A missing key
* matches anything; a key present on both sides must agree.
*
* Keys that constrain a URL: `scheme` (`http`, `https`), `host` (name or
* address, no port), `port` (explicit or the scheme's default). The
* switchboard sets `network` per socket; it constrains no URL.
*/
const DEFAULT_PORT = { http: "80", https: "443" };
/**
* Union of two label sets; throws on a key they give different values,
* naming the key but not the values (they may end up in logs).
*
* @param {Record<string, string>} held
* @param {Record<string, string>} more
*/
export const mergeLabels = (held, more) => {
const merged = { ...held };
for (const [k, v] of Object.entries(more)) {
if (typeof v !== "string") throw new TypeError(`label ${k} is not a string`);
if (k in merged && merged[k] !== v) throw new Error(`label ${k} is already set to a different value`);
merged[k] = v;
}
return Object.freeze(merged);
};
/**
* The labels a URL carries.
*
* @param {string} url
*/
export const urlLabels = (url) => {
const u = new URL(url);
const scheme = u.protocol.replace(/:$/, "");
return { scheme, host: u.hostname, port: u.port || DEFAULT_PORT[scheme] || "" };
};
/**
* Throws unless `url` is within `labels`.
*
* @param {Record<string, string>} labels
* @param {string} url
*/
export const checkUrl = (labels, url) => {
const actual = urlLabels(url);
for (const [k, v] of Object.entries(actual)) {
if (k in labels && labels[k] !== v) throw new Error(`egress to ${actual.host} not granted`);
}
};
+53
View File
@@ -0,0 +1,53 @@
/**
* @file The ingress's mounts, in SQL: which vat serves which label set.
*
* Labels sit one per row, so a lookup can use an index; `mount.labels`
* keeps the whole set as JSON. Request and mount labels arrive as JSON
* objects, split into rows by `json_each`.
*/
export const MOUNT_SCHEMA = [
"CREATE TABLE IF NOT EXISTS mount (vat TEXT PRIMARY KEY, labels TEXT)",
"CREATE TABLE IF NOT EXISTS mount_label (vat TEXT, key TEXT, value TEXT, PRIMARY KEY (vat, key))",
"CREATE INDEX IF NOT EXISTS mount_label_kv ON mount_label (key, value)",
// mounts made before mount_label existed
`INSERT OR IGNORE INTO mount_label
SELECT m.vat, j.key, j.value FROM mount m, json_each(m.labels) j
WHERE NOT EXISTS (SELECT 1 FROM mount_label l WHERE l.vat = m.vat)`,
];
/**
* Another mount (than ?2's) whose labels conflict with none of ?1's.
* Flower's registration rule: every mount must conflict with every other.
*/
export const OVERLAP = `
SELECT 1 FROM mount m WHERE m.vat != ?2 AND NOT EXISTS (
SELECT 1 FROM mount_label l JOIN json_each(?1) r ON r.key = l.key
WHERE l.vat = m.vat AND l.value != r.value)
LIMIT 1`;
export const MOUNT = "INSERT OR REPLACE INTO mount VALUES (?1, ?2)";
export const MOUNT_LABELS = "INSERT INTO mount_label SELECT ?1, key, value FROM json_each(?2)";
export const UNMOUNT = "DELETE FROM mount WHERE vat = ?1";
export const UNMOUNT_LABELS = "DELETE FROM mount_label WHERE vat = ?1";
/**
* The mount whose every label ?1 (the request's labels) carries, with the
* same value: the labels that match, counted per vat, against how many
* the vat has. A mount with no labels matches any request.
*
* Stricter than Flower's match (no conflict): an ingress client holds no
* constrained handle that supplies labels for it, so a request reaches a
* vat only by naming every label of its mount.
*/
export const LOOKUP = `
SELECT m.vat, m.labels FROM mount m JOIN (
SELECT l.vat, count(*) AS hits
FROM json_each(?1) r JOIN mount_label l ON l.key = r.key AND l.value = r.value
GROUP BY l.vat
) h ON h.vat = m.vat
WHERE h.hits = (SELECT count(*) FROM mount_label WHERE vat = m.vat)
UNION ALL
SELECT m.vat, m.labels FROM mount m
WHERE NOT EXISTS (SELECT 1 FROM mount_label l WHERE l.vat = m.vat)
LIMIT 1`;
+133
View File
@@ -0,0 +1,133 @@
/**
* @file An OCapN netlayer whose transport is an RPC session: Cap'n Web, or
* Workers RPC, or one proxied through the other.
*
* Each OCapN connection is a pair of {@link ByteInbox}es, one per
* direction, exchanged through a gateway; each `deliver` call carries
* exactly one OCapN message, so no framing is needed. The RPC session
* provides ordering and only-the-peer-can-inject; OCapN does the rest.
*
* After vattr97's ertp-clerk (`ocapn-capnweb-netlayer.ts`), with the stub
* methods only Cap'n Web has (`onRpcBroken`) made optional.
*
* @see https://github.com/ocapn/ocapn/blob/main/draft-specifications/Netlayers.md
*/
import { RpcTarget } from "capnweb";
export const TRANSPORT = "capnweb";
/**
* A peer's location, by designator alone: a router finds the peer.
*
* @param {string} designator
*/
export const locationOf = (designator) => ({ type: "ocapn-peer", transport: TRANSPORT, designator, hints: false });
/** Same as `locationToLocationId` in `@endo/ocapn`, which its exports map doesn't expose. */
const locationId = ({ designator, transport }) => `ocapn://${designator}.${transport}`;
/** Receives one direction of an OCapN connection, one message per call. */
export class ByteInbox extends RpcTarget {
#onMessage;
constructor(onMessage) {
super();
this.#onMessage = onMessage;
}
/** @param {Uint8Array} bytes */
deliver(bytes) {
// OCapN's syrup reader needs offset 0; a pooled Buffer view may not have it.
this.#onMessage(bytes.byteOffset === 0 ? bytes : new Uint8Array(bytes));
}
}
const dispose = (stub) => stub?.[Symbol.dispose]?.();
/** Write to a remote inbox, discarding each result at once so the session retains none. */
const makeSocket = (inbox, close) => ({
write: (bytes) => dispose(inbox.deliver(bytes)),
end: close,
});
/**
* A remote inbox reached through a gateway that is only a promise (a
* local async call, not a pipelining stub): writes queue in order behind it.
*/
const deferredInbox = (gatewayP, myInbox) => {
const inboxP = Promise.resolve(gatewayP).then((gateway) => gateway.connect(myInbox));
return {
deliver: (bytes) => void inboxP.then((inbox) => dispose(inbox.deliver(bytes))),
onRpcBroken: (cb) => void inboxP.then((inbox) => inbox.onRpcBroken?.(cb), cb),
};
};
/**
* Make an OCapN netlayer for `client.registerNetlayer`.
*
* @param {object} opts
* @param {string} opts.designator this peer's designator
* @param {(designator: string) => any} opts.openGateway the gateway of
* the peer with this designator: a stub or pipelining promise
* (`openGateway(d).connect(...)`), or a plain promise for one
* @returns a netlayer maker; the netlayer has a `gateway` that accepts
* incoming connections
*/
export const makeRpcNetLayer = ({ designator, openGateway }) => {
const location = locationOf(designator);
const connections = new Set();
return (handlers, logger) => {
const track = (connection, inbox) => {
connections.add(connection);
inbox.onRpcBroken?.((reason) => {
if (connections.delete(connection)) logger.log("rpc netlayer: connection broken", reason);
handlers.handleConnectionClose(connection, reason);
});
};
const netlayer = {
location,
locationId: locationId(location),
connect: (peer) => {
const gateway = openGateway(peer.designator);
let connection;
const myInbox = new ByteInbox((bytes) => handlers.handleMessageData(connection, bytes));
// Pipelined: writes before the peer answers queue in order.
const peerInbox =
typeof gateway.connect === "function" ? gateway.connect(myInbox) : deferredInbox(gateway, myInbox);
connection = handlers.makeConnection(
netlayer,
true,
makeSocket(peerInbox, () => {
connections.delete(connection);
dispose(gateway);
}),
);
track(connection, peerInbox);
return connection;
},
shutdown: () => {
for (const connection of [...connections]) connection.end();
},
};
class Gateway extends RpcTarget {
connect(peerInbox) {
const peer = peerInbox.dup?.() ?? peerInbox;
const connection = handlers.makeConnection(
netlayer,
false,
makeSocket(peer, () => {
connections.delete(connection);
dispose(peer);
}),
);
track(connection, peer);
return new ByteInbox((bytes) => handlers.handleMessageData(connection, bytes));
}
}
return Object.assign(netlayer, { gateway: new Gateway() });
};
};
+24
View File
@@ -0,0 +1,24 @@
{
"name": "toybox",
"version": "0.0.1",
"private": true,
"type": "module",
"scripts": {
"start": "node build.js && mkdir -p state && rm -f admin.sock && systemd-socket-activate -l 127.0.0.1:8787 -l \"$PWD/admin.sock\" -- node_modules/workerd/bin/workerd serve --experimental config.capnp -S http=3 -S admin=4 -d state=state -e \"switchboard=unix:$PWD/switchboard-public.sock\"",
"switchboard": "rm -f switchboard-public.sock switchboard-local.sock && systemd-socket-activate -l \"$PWD/switchboard-public.sock\" -l \"$PWD/switchboard-local.sock\" -- node_modules/workerd/bin/workerd serve --experimental switchboard.capnp -S public=3 -S local=4",
"test": "node build.js && node --import ./test/lockdown.js --test test/*.test.js",
"build": "node build.js",
"hello": "node --import ./test/lockdown.js scripts/hello.js"
},
"devDependencies": {
"esbuild": "^0.28.2",
"workerd": "1.20261006.1",
"ws": "8.22.0"
},
"dependencies": {
"@endo/far": "^1.1.14",
"@endo/init": "^1.1.13",
"@endo/ocapn": "1.1.1",
"capnweb": "0.12.0"
}
}
+578
View File
@@ -0,0 +1,578 @@
lockfileVersion: '9.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
importers:
.:
dependencies:
'@endo/far':
specifier: ^1.1.14
version: 1.1.14
'@endo/init':
specifier: ^1.1.13
version: 1.1.13
'@endo/ocapn':
specifier: 1.1.1
version: 1.1.1
capnweb:
specifier: 0.12.0
version: 0.12.0
devDependencies:
esbuild:
specifier: ^0.28.2
version: 0.28.2
workerd:
specifier: 1.20261006.1
version: 1.20261006.1
ws:
specifier: 8.22.0
version: 8.22.0
packages:
'@cloudflare/workerd-darwin-64@1.20261006.1':
resolution: {integrity: sha512-lCX6avJO2It9AyDEYitjmOtJRVp/xmaW0TziyoLAnfxlzozyyRbSFfIIMMCiDx/sTP1++E4VLbV+7BHSD33f0Q==}
engines: {node: '>=16'}
cpu: [x64]
os: [darwin]
'@cloudflare/workerd-darwin-arm64@1.20261006.1':
resolution: {integrity: sha512-PyFGjOaldtppnLuKsdkoYWXfLVpDjuf8u+uoykX+1Xvxo2EPmCVViq0iDKm+U7c7PRno85ehS3/MPVXyk2HwHw==}
engines: {node: '>=16'}
cpu: [arm64]
os: [darwin]
'@cloudflare/workerd-linux-64@1.20261006.1':
resolution: {integrity: sha512-Ntf9S8eesmVufdjaT2kzWlz6Ng9XGYTc6cHQVRKAg59lFufwsIabGeMT6U4KkrpEeSIxgHq8aPtuLbZXE19tCA==}
engines: {node: '>=16'}
cpu: [x64]
os: [linux]
'@cloudflare/workerd-linux-arm64@1.20261006.1':
resolution: {integrity: sha512-JyeDBymVWw5tVRebSsVE8ojDYxd6UlZrAseHU8G+NpIyd5wF61tXlF/axLeCUqu0pOhBFHb8I5QKi0jwrCK41Q==}
engines: {node: '>=16'}
cpu: [arm64]
os: [linux]
'@cloudflare/workerd-windows-64@1.20261006.1':
resolution: {integrity: sha512-nWP0URNqOBN9fa/gZ7eh/w051DwjOXN8j4lDZDYVXyQPsux6sV3DfyYZT+CjR/rt9nKBSmJT9QE9/bWT18+84w==}
engines: {node: '>=16'}
cpu: [x64]
os: [win32]
'@endo/base64@1.1.1':
resolution: {integrity: sha512-6Aiy5oU/5/LYrHLbEPz0OWQ+CQsnAOC3qQYQ3nlwWi2JsU8fIZWjwfa+/+MSx8LTzITC250ZnMvtR0y/FIOQKw==}
'@endo/bytes@1.0.2':
resolution: {integrity: sha512-gKG8v4c7SD/QzULlFl1OKBuUCCy+9H78xsCL40hZn1q2/hVCNAHrxPJFO6VbA8Nk8UJP6P+NjvZY+xdrfwytMQ==}
'@endo/cache-map@1.1.0':
resolution: {integrity: sha512-owFGshs/97PDw9oguZqU/px8Lv1d0KjAUtDUiPwKHNXRVUE/jyettEbRoTbNJR1OaI8biMn6bHr9kVJsOh6dXw==}
'@endo/common@1.4.0':
resolution: {integrity: sha512-+d0CCzEYUP4PZDVGAUHMNfCEBn/GOyq/39y33N4FFUb6VPNJosfKFK5bI38mTaqwr6gxLGbzm8aeiElz+NaSDQ==}
'@endo/env-options@1.1.11':
resolution: {integrity: sha512-p9OnAPsdqoX4YJsE98e3NBVhIr2iW9gNZxHhAI2/Ul5TdRfoOViItzHzTqrgUVopw6XxA1u1uS6CykLMDUxarA==}
'@endo/errors@1.3.1':
resolution: {integrity: sha512-AmR2DSiahQR66SHlEczNWe0eUotMYE2uDwxPj9fAY2l2lovwHWGzZKXNXdQP/u62c8vetU8mG98Mh5vRZEvFTg==}
'@endo/eventual-send@1.5.0':
resolution: {integrity: sha512-mIRewS15mk+oV8y7kszyE0KWHZAlVoe98bEo/WJFJvBv1Rd83IjnofbuZcyWToWd70vgCxfkutWRJBK2Xtwd5A==}
'@endo/far@1.1.14':
resolution: {integrity: sha512-OlM+yCNWVqhwSZa6MyjkVB0oQSTAQ15KoiDGL1qowtnTnhuGUbOXuaUAsDf4eAJZ4L+h2KsJOUdyYEuhNsDPLg==}
'@endo/harden@1.1.0':
resolution: {integrity: sha512-d0CF7EVqymx9YUbkRI2sj10NrMLhrpmsaq5aBbEEbWDFxNe7F/mM8Gv8zT+iHErKEfeMCId90n5mk665SnxrRA==}
'@endo/hex@1.1.1':
resolution: {integrity: sha512-I2Q7roaHk0fE4JTj2GXfxHPR14qTFK9bOvp3nKf2Fk0r/CjgL4zFcHYolvqY15SRNmZDcywnQ+MBTW82b7BUpQ==}
'@endo/immutable-arraybuffer@2.0.0':
resolution: {integrity: sha512-xvfJvo4CgETh6UjSKwhNsFLZrqrTf2k4ZFpcprEN2UtCQRSOk+CcLP70kFbrOesB2Z/c1z9MaUZDS1JY6IlnUg==}
'@endo/init@1.1.13':
resolution: {integrity: sha512-7I94pHD0ax+WDj5dP1MKgzgSY6/GsdwCc/Ap2zFY4lzhCO944zQ4MChAW2yX28QKJK80VyJzqoW5BQ56ngEHHA==}
'@endo/lockdown@1.0.19':
resolution: {integrity: sha512-pcc6TqTBlx43422gHFzS+FrUfyJlbDoWUrynp78Mv+FrIZv4947FPcfjlXolgwvO00alMlSYxfXrrXUV93ywaA==}
'@endo/marshal@1.10.0':
resolution: {integrity: sha512-1ny6r0+XFpkpJNJEOApZQlFNB8FsDxzU2oCv1hpN1HjpszsKcTiyfXU/n/cJIs3KOOS06Tkt72pgPlasHpsVGA==}
'@endo/nat@5.2.0':
resolution: {integrity: sha512-yTNaysErNbrAWV8H2oC4e83nytG8Vzcu6VrxOkSIJQt+IVS9BUlSa1KkiKrVwu2IcIC67gJIkolPq3SgMGDjfQ==}
'@endo/ocapn@1.1.1':
resolution: {integrity: sha512-3VtHmyMsHwDPwcVusCTgtb8VXr539iZk+r8vzzOU6/cWyMhJuxRGOKR3r5EzDHVG4tY/R6tihoGt7QLnNDuceQ==}
'@endo/pass-style@1.8.2':
resolution: {integrity: sha512-63kbFNT+mropjQ0wzCkjSR5uEOT8FAIk16qHqrE+ciqSjMVd2hsW6vx10dbyo1s2xtmvXduUiTl+LqtnPa2oSw==}
'@endo/promise-kit@1.2.1':
resolution: {integrity: sha512-1nyXBOuUnVo/i47On8RCXPaT/1RIsSpJ1sGBClfZrcTtnsJfj8fElEVlJIE8NFsQiZPLNANYI+i/NYi837+s0Q==}
engines: {node: '>=11.0'}
'@endo/stream@1.3.1':
resolution: {integrity: sha512-v21VRzo5wjzw7XMHCWAmDS50hkUQi/m9C0MQTIAAqLm6w9+/Er9AEXl8FGIbz+VjtJWk5SNVbuqA51N7oBaLDQ==}
'@endo/syrup-frame@0.1.1':
resolution: {integrity: sha512-+uha+zI05RHPlSNVI7uaB2KD1EQ9gKAMcOzj1eT3y7Ng/vcW1bo7clCVVo3t+dOFOc6vYSsXgKufi40qxXRgYQ==}
'@esbuild/aix-ppc64@0.28.2':
resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==}
engines: {node: '>=18'}
cpu: [ppc64]
os: [aix]
'@esbuild/android-arm64@0.28.2':
resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==}
engines: {node: '>=18'}
cpu: [arm64]
os: [android]
'@esbuild/android-arm@0.28.2':
resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==}
engines: {node: '>=18'}
cpu: [arm]
os: [android]
'@esbuild/android-x64@0.28.2':
resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==}
engines: {node: '>=18'}
cpu: [x64]
os: [android]
'@esbuild/darwin-arm64@0.28.2':
resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==}
engines: {node: '>=18'}
cpu: [arm64]
os: [darwin]
'@esbuild/darwin-x64@0.28.2':
resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==}
engines: {node: '>=18'}
cpu: [x64]
os: [darwin]
'@esbuild/freebsd-arm64@0.28.2':
resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==}
engines: {node: '>=18'}
cpu: [arm64]
os: [freebsd]
'@esbuild/freebsd-x64@0.28.2':
resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==}
engines: {node: '>=18'}
cpu: [x64]
os: [freebsd]
'@esbuild/linux-arm64@0.28.2':
resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==}
engines: {node: '>=18'}
cpu: [arm64]
os: [linux]
'@esbuild/linux-arm@0.28.2':
resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==}
engines: {node: '>=18'}
cpu: [arm]
os: [linux]
'@esbuild/linux-ia32@0.28.2':
resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==}
engines: {node: '>=18'}
cpu: [ia32]
os: [linux]
'@esbuild/linux-loong64@0.28.2':
resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==}
engines: {node: '>=18'}
cpu: [loong64]
os: [linux]
'@esbuild/linux-mips64el@0.28.2':
resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==}
engines: {node: '>=18'}
cpu: [mips64el]
os: [linux]
'@esbuild/linux-ppc64@0.28.2':
resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==}
engines: {node: '>=18'}
cpu: [ppc64]
os: [linux]
'@esbuild/linux-riscv64@0.28.2':
resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==}
engines: {node: '>=18'}
cpu: [riscv64]
os: [linux]
'@esbuild/linux-s390x@0.28.2':
resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==}
engines: {node: '>=18'}
cpu: [s390x]
os: [linux]
'@esbuild/linux-x64@0.28.2':
resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==}
engines: {node: '>=18'}
cpu: [x64]
os: [linux]
'@esbuild/netbsd-arm64@0.28.2':
resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==}
engines: {node: '>=18'}
cpu: [arm64]
os: [netbsd]
'@esbuild/netbsd-x64@0.28.2':
resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==}
engines: {node: '>=18'}
cpu: [x64]
os: [netbsd]
'@esbuild/openbsd-arm64@0.28.2':
resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==}
engines: {node: '>=18'}
cpu: [arm64]
os: [openbsd]
'@esbuild/openbsd-x64@0.28.2':
resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==}
engines: {node: '>=18'}
cpu: [x64]
os: [openbsd]
'@esbuild/openharmony-arm64@0.28.2':
resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==}
engines: {node: '>=18'}
cpu: [arm64]
os: [openharmony]
'@esbuild/sunos-x64@0.28.2':
resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==}
engines: {node: '>=18'}
cpu: [x64]
os: [sunos]
'@esbuild/win32-arm64@0.28.2':
resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==}
engines: {node: '>=18'}
cpu: [arm64]
os: [win32]
'@esbuild/win32-ia32@0.28.2':
resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==}
engines: {node: '>=18'}
cpu: [ia32]
os: [win32]
'@esbuild/win32-x64@0.28.2':
resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==}
engines: {node: '>=18'}
cpu: [x64]
os: [win32]
'@noble/curves@1.9.7':
resolution: {integrity: sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==}
engines: {node: ^14.21.3 || >=16}
'@noble/hashes@1.8.0':
resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==}
engines: {node: ^14.21.3 || >=16}
capnweb@0.12.0:
resolution: {integrity: sha512-jgZ/LMtMVTi+RVlooIslH78Gg23XbDTdvcLghWx3oz17D6u5GuJARt+uhZk/wcTo+f81eeabfnow4d3zLBj+JQ==}
esbuild@0.28.2:
resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==}
engines: {node: '>=18'}
hasBin: true
ses@2.3.0:
resolution: {integrity: sha512-qd3iWzDqGKllI2FmExKsWLrJwt+6COWb8jUdzaCn8Cq5OTeoXdQ62Gn/xLy0GWLORC3du6yBAVe/V0B0dLVKew==}
workerd@1.20261006.1:
resolution: {integrity: sha512-8MadBuffZ5NdpLwZjUmsqT5QlaKXq4gjgT6wzcKeynZTICNXyePhc+5QVoKiK7+MMhFTLNrRO2KXLlpk8Q6BkA==}
engines: {node: '>=16'}
hasBin: true
ws@8.22.0:
resolution: {integrity: sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==}
engines: {node: '>=10.0.0'}
peerDependencies:
bufferutil: ^4.0.1
utf-8-validate: '>=5.0.2'
peerDependenciesMeta:
bufferutil:
optional: true
utf-8-validate:
optional: true
snapshots:
'@cloudflare/workerd-darwin-64@1.20261006.1':
optional: true
'@cloudflare/workerd-darwin-arm64@1.20261006.1':
optional: true
'@cloudflare/workerd-linux-64@1.20261006.1':
optional: true
'@cloudflare/workerd-linux-arm64@1.20261006.1':
optional: true
'@cloudflare/workerd-windows-64@1.20261006.1':
optional: true
'@endo/base64@1.1.1': {}
'@endo/bytes@1.0.2':
dependencies:
'@endo/harden': 1.1.0
'@endo/immutable-arraybuffer': 2.0.0
'@endo/cache-map@1.1.0': {}
'@endo/common@1.4.0':
dependencies:
'@endo/errors': 1.3.1
'@endo/eventual-send': 1.5.0
'@endo/harden': 1.1.0
'@endo/promise-kit': 1.2.1
'@endo/env-options@1.1.11': {}
'@endo/errors@1.3.1':
dependencies:
'@endo/harden': 1.1.0
ses: 2.3.0
'@endo/eventual-send@1.5.0':
dependencies:
'@endo/env-options': 1.1.11
'@endo/harden': 1.1.0
'@endo/far@1.1.14':
dependencies:
'@endo/errors': 1.3.1
'@endo/eventual-send': 1.5.0
'@endo/pass-style': 1.8.2
'@endo/harden@1.1.0': {}
'@endo/hex@1.1.1':
dependencies:
'@endo/harden': 1.1.0
'@endo/immutable-arraybuffer@2.0.0': {}
'@endo/init@1.1.13':
dependencies:
'@endo/base64': 1.1.1
'@endo/eventual-send': 1.5.0
'@endo/harden': 1.1.0
'@endo/lockdown': 1.0.19
'@endo/promise-kit': 1.2.1
'@endo/lockdown@1.0.19':
dependencies:
ses: 2.3.0
'@endo/marshal@1.10.0':
dependencies:
'@endo/common': 1.4.0
'@endo/env-options': 1.1.11
'@endo/errors': 1.3.1
'@endo/eventual-send': 1.5.0
'@endo/harden': 1.1.0
'@endo/nat': 5.2.0
'@endo/pass-style': 1.8.2
'@endo/nat@5.2.0': {}
'@endo/ocapn@1.1.1':
dependencies:
'@endo/bytes': 1.0.2
'@endo/eventual-send': 1.5.0
'@endo/harden': 1.1.0
'@endo/hex': 1.1.1
'@endo/init': 1.1.13
'@endo/marshal': 1.10.0
'@endo/nat': 5.2.0
'@endo/pass-style': 1.8.2
'@endo/promise-kit': 1.2.1
'@endo/stream': 1.3.1
'@endo/syrup-frame': 0.1.1
'@noble/curves': 1.9.7
'@noble/hashes': 1.8.0
ws: 8.22.0
transitivePeerDependencies:
- bufferutil
- utf-8-validate
'@endo/pass-style@1.8.2':
dependencies:
'@endo/common': 1.4.0
'@endo/env-options': 1.1.11
'@endo/errors': 1.3.1
'@endo/eventual-send': 1.5.0
'@endo/harden': 1.1.0
'@endo/promise-kit': 1.2.1
'@endo/promise-kit@1.2.1':
dependencies:
'@endo/harden': 1.1.0
'@endo/stream@1.3.1':
dependencies:
'@endo/eventual-send': 1.5.0
'@endo/harden': 1.1.0
'@endo/promise-kit': 1.2.1
ses: 2.3.0
'@endo/syrup-frame@0.1.1':
dependencies:
'@endo/harden': 1.1.0
'@endo/init': 1.1.13
'@endo/promise-kit': 1.2.1
'@endo/stream': 1.3.1
'@esbuild/aix-ppc64@0.28.2':
optional: true
'@esbuild/android-arm64@0.28.2':
optional: true
'@esbuild/android-arm@0.28.2':
optional: true
'@esbuild/android-x64@0.28.2':
optional: true
'@esbuild/darwin-arm64@0.28.2':
optional: true
'@esbuild/darwin-x64@0.28.2':
optional: true
'@esbuild/freebsd-arm64@0.28.2':
optional: true
'@esbuild/freebsd-x64@0.28.2':
optional: true
'@esbuild/linux-arm64@0.28.2':
optional: true
'@esbuild/linux-arm@0.28.2':
optional: true
'@esbuild/linux-ia32@0.28.2':
optional: true
'@esbuild/linux-loong64@0.28.2':
optional: true
'@esbuild/linux-mips64el@0.28.2':
optional: true
'@esbuild/linux-ppc64@0.28.2':
optional: true
'@esbuild/linux-riscv64@0.28.2':
optional: true
'@esbuild/linux-s390x@0.28.2':
optional: true
'@esbuild/linux-x64@0.28.2':
optional: true
'@esbuild/netbsd-arm64@0.28.2':
optional: true
'@esbuild/netbsd-x64@0.28.2':
optional: true
'@esbuild/openbsd-arm64@0.28.2':
optional: true
'@esbuild/openbsd-x64@0.28.2':
optional: true
'@esbuild/openharmony-arm64@0.28.2':
optional: true
'@esbuild/sunos-x64@0.28.2':
optional: true
'@esbuild/win32-arm64@0.28.2':
optional: true
'@esbuild/win32-ia32@0.28.2':
optional: true
'@esbuild/win32-x64@0.28.2':
optional: true
'@noble/curves@1.9.7':
dependencies:
'@noble/hashes': 1.8.0
'@noble/hashes@1.8.0': {}
capnweb@0.12.0: {}
esbuild@0.28.2:
optionalDependencies:
'@esbuild/aix-ppc64': 0.28.2
'@esbuild/android-arm': 0.28.2
'@esbuild/android-arm64': 0.28.2
'@esbuild/android-x64': 0.28.2
'@esbuild/darwin-arm64': 0.28.2
'@esbuild/darwin-x64': 0.28.2
'@esbuild/freebsd-arm64': 0.28.2
'@esbuild/freebsd-x64': 0.28.2
'@esbuild/linux-arm': 0.28.2
'@esbuild/linux-arm64': 0.28.2
'@esbuild/linux-ia32': 0.28.2
'@esbuild/linux-loong64': 0.28.2
'@esbuild/linux-mips64el': 0.28.2
'@esbuild/linux-ppc64': 0.28.2
'@esbuild/linux-riscv64': 0.28.2
'@esbuild/linux-s390x': 0.28.2
'@esbuild/linux-x64': 0.28.2
'@esbuild/netbsd-arm64': 0.28.2
'@esbuild/netbsd-x64': 0.28.2
'@esbuild/openbsd-arm64': 0.28.2
'@esbuild/openbsd-x64': 0.28.2
'@esbuild/openharmony-arm64': 0.28.2
'@esbuild/sunos-x64': 0.28.2
'@esbuild/win32-arm64': 0.28.2
'@esbuild/win32-ia32': 0.28.2
'@esbuild/win32-x64': 0.28.2
ses@2.3.0:
dependencies:
'@endo/cache-map': 1.1.0
'@endo/env-options': 1.1.11
'@endo/immutable-arraybuffer': 2.0.0
workerd@1.20261006.1:
optionalDependencies:
'@cloudflare/workerd-darwin-64': 1.20261006.1
'@cloudflare/workerd-darwin-arm64': 1.20261006.1
'@cloudflare/workerd-linux-64': 1.20261006.1
'@cloudflare/workerd-linux-arm64': 1.20261006.1
'@cloudflare/workerd-windows-64': 1.20261006.1
ws@8.22.0: {}
+20
View File
@@ -0,0 +1,20 @@
/**
* @file Create the hello-world vat on a running toybox and mount it.
*
* Usage: node --import ./test/lockdown.js scripts/hello.js [name]
* then visit http://127.0.0.1:8787/?vat=<name> (default name: hello).
*/
import { readFile } from "node:fs/promises";
import { E } from "@endo/far";
import { connectClient } from "../client.js";
const name = process.argv[2] ?? "hello";
const client = await connectClient("admin.sock", `hello-script-${process.pid}`);
try {
const ingress = await E(client.vatAdmin).makeIngress({ vat: name });
const { id, root } = await E(client.vatAdmin).createVat(await readFile("vats/hello.js", "utf8"), { ingress });
await root; // its handoff, settled before the client goes
console.log(`vat ${id}\nhttp://127.0.0.1:8787/?vat=${name}`);
} finally {
client.close();
}
+575
View File
@@ -0,0 +1,575 @@
/** @file toybox supervisor: vats with code installed at runtime, each app a facet; ingress by mount, egress by grant. */
import "@endo/init";
import { DurableObject, WorkerEntrypoint } from "cloudflare:workers";
import { RpcTarget, newWebSocketRpcSession, newWorkersRpcResponse } from "capnweb";
import { E, Far, passStyleOf } from "@endo/far";
import { makeClient, swissnumFromBytes } from "@endo/ocapn";
import { mergeLabels, urlLabels } from "./labels.js";
import { LOOKUP, MOUNT, MOUNT_LABELS, MOUNT_SCHEMA, OVERLAP, UNMOUNT, UNMOUNT_LABELS } from "./mounts-sql.js";
import { locationOf, makeRpcNetLayer } from "./netlayer.js";
import VAT_RUNTIME from "vat-runtime.txt";
/**
* A stored grant: labels as JSON, or (before labels) a bare `host[:port]`.
*
* @param {string} stored
*/
const grantLabels = (stored) => {
if (stored.startsWith("{")) return JSON.parse(stored);
const { host, port } = urlLabels(`http://${stored}`);
return stored.includes(":") ? { host, port } : { host };
};
const hex = (buf) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
/**
* One vat, by DO id: holds its installed code and egress grant; the app
* facet holds the app's state. Its mount, if any, is in the {@link Directory}.
*
* Code is stored by hash so the facet can be rebuilt after hibernation or a
* restart. The app's global `fetch` throws; a granted host arrives as
* `env.egress`, an {@link Egress} the app can pass along like any object.
*
* Each `start` begins a new incarnation, which names the loaded Worker: the
* same code with a different grant must not share a Worker.
*/
export class Vat extends DurableObject {
constructor(ctx, env) {
super(ctx, env);
ctx.storage.sql.exec("CREATE TABLE IF NOT EXISTS bundle (hash TEXT PRIMARY KEY, src TEXT)");
ctx.storage.sql.exec("CREATE TABLE IF NOT EXISTS current (k INTEGER PRIMARY KEY CHECK (k = 0), hash TEXT)");
ctx.storage.sql.exec(
"CREATE TABLE IF NOT EXISTS incarnation (k INTEGER PRIMARY KEY CHECK (k = 0), n INTEGER, egress TEXT)",
);
// absent: an app vat (exports class App), from before OCapN vats
ctx.storage.sql.exec("CREATE TABLE IF NOT EXISTS kind (k INTEGER PRIMARY KEY CHECK (k = 0), kind TEXT)");
}
/**
* Install `src` and run the app on it; the app's storage carries over.
*
* @param {string} src an ES module exporting `class App extends DurableObject`
* @param {string | null} egress the app's grant: egress labels as JSON (see labels.js), or none
* @param {"app" | "ocapn"} kind `app`: `src` exports `class App`; `ocapn`:
* `src` exports `buildRootObject`, run by vat-runtime.js
* @returns {Promise<string>} the code's SHA-256, hex
*/
async start(src, egress, kind = "app") {
const hash = hex(await crypto.subtle.digest("SHA-256", encodeUtf8(src)));
const { sql } = this.ctx.storage;
sql.exec("INSERT OR IGNORE INTO bundle VALUES (?, ?)", hash, src);
sql.exec("INSERT OR REPLACE INTO current VALUES (0, ?)", hash);
const [prev] = sql.exec("SELECT n FROM incarnation").toArray();
sql.exec("INSERT OR REPLACE INTO incarnation VALUES (0, ?, ?)", (prev?.n ?? 0) + 1, egress);
sql.exec("INSERT OR REPLACE INTO kind VALUES (0, ?)", kind);
this.ctx.facets.abort("app", new Error("upgraded"));
return hash;
}
#app({ src, n, egress, kind }) {
return this.ctx.facets.get("app", () => {
const env = egress ? { egress: this.ctx.exports.Egress({ props: { labels: grantLabels(egress) } }) } : {};
const code =
kind === "ocapn"
? {
mainModule: "runtime.js",
modules: { "runtime.js": VAT_RUNTIME, "vat.js": src },
env: { ...env, vatId: this.ctx.id.toString(), router: this.ctx.exports.Router({ props: {} }) },
}
: { mainModule: "app.js", modules: { "app.js": src }, env };
const worker = this.env.LOADER.get(`${this.ctx.id}:${n}`, () => ({
compatibilityDate: "2026-10-01",
...code,
globalOutbound: null,
}));
return { class: worker.getDurableObjectClass("App") };
});
}
#current() {
const [row] = this.ctx.storage.sql
.exec(
`SELECT b.hash, b.src, coalesce(i.n, 0) AS n, i.egress, coalesce(k.kind, 'app') AS kind
FROM current c JOIN bundle b USING (hash)
LEFT JOIN incarnation i ON i.k = 0 LEFT JOIN kind k ON k.k = 0`,
)
.toArray();
return row;
}
fetch(request) {
const row = this.#current();
if (!row) return new Response("no code installed\n", { status: 404 });
return this.#app(row).fetch(request);
}
/** An OCapN vat's gateway, for the router. */
gateway() {
const row = this.#current();
if (row?.kind !== "ocapn") throw new Error("not an OCapN vat");
return this.#app(row).gateway();
}
}
/**
* A vat's egress grant: a switchboard handle constrained to the labels in
* `ctx.props`, which no holder can change. The switchboard enforces them;
* a refusal comes back as a 403.
*/
export class Egress extends WorkerEntrypoint {
/** A narrower grant: these labels too (conflicting ones throw). */
constrain(more) {
return this.ctx.exports.Egress({ props: { labels: mergeLabels(this.ctx.props.labels, more) } });
}
async #handle() {
const resp = await this.env.SWITCHBOARD.fetch("http://switchboard/", { headers: { Upgrade: "websocket" } });
const ws = resp.webSocket;
if (!ws) throw new Error(`switchboard refused a session: ${resp.status}`);
ws.accept();
return newWebSocketRpcSession(ws).constrain(this.ctx.props.labels);
}
async fetch(request) {
try {
const handle = await this.#handle();
if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") return await handle.fetch(request);
const protocols = (request.headers.get("Sec-WebSocket-Protocol") ?? "").split(",").map((p) => p.trim()).filter(Boolean);
const { readable, writable, protocol } = await handle.webSocket(request.url, protocols);
return this.#bridge(readable, writable, protocol);
} catch (e) {
return new Response(`egress refused: ${e.message}\n`, { status: 403 });
}
}
/** A WebSocket for the vat whose messages travel the switchboard's streams. */
#bridge(readable, writable, protocol) {
const [client, server] = Object.values(new WebSocketPair());
server.accept();
const writer = writable.getWriter();
server.addEventListener("message", (e) => writer.write(e.data).catch(() => server.close(1011)));
server.addEventListener("close", () => writer.close().catch(() => {}));
this.ctx.waitUntil(
(async () => {
for await (const m of readable) server.send(m);
server.close();
})().catch(() => server.close(1011)),
);
const headers = protocol ? { "Sec-WebSocket-Protocol": protocol } : {};
return new Response(null, { status: 101, webSocket: client, headers });
}
}
/** The vatAdmin's designator, and the swissnum of its bootstrap object. */
const VAT_ADMIN = "vatAdmin";
/** The swissnum of an OCapN vat's bootstrap (see vat-runtime.js). */
const VAT_SWISSNUM = "vat";
/** UTF-8 bytes of a string: the method alone, so no encoder object is in module scope. */
const encodeUtf8 = harden(TextEncoder.prototype.encode.bind(new TextEncoder()));
/**
* The vatAdmin: an OCapN peer, and the router through which every OCapN
* peer here reaches every other. One instance, by name.
*
* Peers find each other by designator: the vatAdmin's is `vatAdmin`, a
* vat's is its id, and a client registers its own when it connects to
* the admin socket. Nothing here can dial out, so a handoff's receiver
* reaches the exporter through this router.
*/
export class VatAdmin extends DurableObject {
#clients = new Map();
/** mount key → the handler serving it: live, so lost when this object is evicted */
#handlers = new Map();
/** mount key → resolvers waiting for a handler */
#waiting = new Map();
/** mount key ↔ its ingress object, made again as needed */
#ingresses = new Map();
#ingressKeys = new WeakMap();
#reviving = new Map();
#ready;
constructor(ctx, env) {
super(ctx, env);
const { sql } = ctx.storage;
// a vat's params, encoded (see #encode); a vat absent here can't be restarted
sql.exec("CREATE TABLE IF NOT EXISTS vat_params (vat TEXT PRIMARY KEY, params TEXT)");
// which vat was given which ingress, so a request can restart it
sql.exec("CREATE TABLE IF NOT EXISTS ingress_vat (key TEXT PRIMARY KEY, vat TEXT)");
this.#ready = this.#boot();
}
/** @param {string} key */
#ingressFor(key) {
let ingress = this.#ingresses.get(key);
if (!ingress) {
ingress = Far("ingress", {
/** @param {{ handle: (request: object) => object }} handler */
serve: (handler) => {
this.#handlers.set(key, handler);
for (const resolve of this.#waiting.get(key) ?? []) resolve();
this.#waiting.delete(key);
},
});
this.#ingresses.set(key, ingress);
this.#ingressKeys.set(ingress, key);
}
return ingress;
}
/**
* `params` as JSON, an ingress by its key; `null` if anything in it can't
* be made again here (a remote object of another peer, say).
*/
#encode(params) {
const keys = [];
const walk = (v) => {
const style = passStyleOf(v);
if (style === "remotable") {
const key = this.#ingressKeys.get(v);
if (!key) throw new Error("not restartable");
keys.push(key);
return { "@ingress": key };
}
if (style === "copyArray") return v.map(walk);
if (style === "copyRecord") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x)]));
if (["string", "number", "boolean", "null"].includes(style)) return v;
throw new Error("not restartable");
};
try {
return { json: JSON.stringify(walk(params)), keys };
} catch {
return null;
}
}
#decode(json) {
const walk = (v) => {
if (Array.isArray(v)) return v.map(walk);
if (v && typeof v === "object") {
if ("@ingress" in v) return this.#ingressFor(v["@ingress"]);
return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x)]));
}
return v;
};
return harden(walk(JSON.parse(json)));
}
/** (Re)start a vat's code with `params`: it rebuilds its root. */
async #startVat(vat, params) {
const vatBootstrap = await this.#enliven(vat, VAT_SWISSNUM);
return E(vatBootstrap).start(params);
}
/**
* The handler for a mount whose handler went with an evicted instance:
* restart the vat given its ingress, and wait for it to serve again.
*
* @param {string} key
*/
#revive(key) {
let reviving = this.#reviving.get(key);
if (!reviving) {
reviving = (async () => {
const [row] = this.ctx.storage.sql
.exec("SELECT i.vat, p.params FROM ingress_vat i JOIN vat_params p USING (vat) WHERE i.key = ?", key)
.toArray();
if (!row) return null;
const served = new Promise((resolve) => this.#waiting.set(key, [...(this.#waiting.get(key) ?? []), resolve]));
await this.#startVat(row.vat, this.#decode(row.params));
await Promise.race([served, new Promise((resolve) => setTimeout(resolve, 5000))]);
return this.#handlers.get(key) ?? null;
})().finally(() => this.#reviving.delete(key));
this.#reviving.set(key, reviving);
}
return reviving;
}
async #boot() {
const vatAdmin = Far("vatAdmin", {
/**
* Create an OCapN vat running `src`; `params` (any passable,
* remote objects included) reach its `buildRootObject`.
*
* If `params` holds only data and ingresses, they are kept, and the
* vat is restarted with them when a request needs it after an
* eviction or a restart.
*
* @param {string} src an ES module exporting `buildRootObject(vatPowers, params)`
*/
createVat: async (src, params = {}) => {
const id = this.env.VATS.newUniqueId();
const vat = id.toString();
await this.env.VATS.get(id).start(src, null, "ocapn");
const encoded = this.#encode(params);
if (encoded) {
const { sql } = this.ctx.storage;
sql.exec("INSERT INTO vat_params VALUES (?, ?)", vat, encoded.json);
for (const key of encoded.keys) sql.exec("INSERT OR REPLACE INTO ingress_vat VALUES (?, ?)", key, vat);
}
const root = await this.#startVat(vat, params);
return harden({ id: vat, root });
},
/**
* Reserve a mount at `labels` and return the ingress for it: whoever
* holds the ingress (a vat it is passed to, say) serves requests
* that carry those labels.
*
* @param {Record<string, string>} labels
*/
makeIngress: async (labels) => {
const key = `ingress:${crypto.randomUUID()}`;
await this.env.DIRECTORY.getByName("directory").mount(key, harden({ ...labels }));
return this.#ingressFor(key);
},
});
// workerd runs FinalizationRegistry callbacks outside any request, where
// sending the resulting GC message is forbidden I/O. So imports are
// never collected here; they go when their session does.
this.ocapn = makeClient({
debugLabel: VAT_ADMIN,
swissnumTable: new Map([[VAT_ADMIN, vatAdmin]]),
enableImportCollection: false,
});
const netlayer = await this.ocapn.registerNetlayer(
makeRpcNetLayer({ designator: VAT_ADMIN, openGateway: (designator) => this.gateway(designator) }),
);
this.own = netlayer.gateway;
}
#enliven(designator, swissnum) {
return this.ocapn.enlivenSturdyRef(
this.ocapn.makeSturdyRef(locationOf(designator), swissnumFromBytes(encodeUtf8(swissnum))),
);
}
/**
* The gateway of the peer with this designator.
*
* @param {string} designator
*/
async gateway(designator) {
await this.#ready;
if (designator === VAT_ADMIN) return this.own;
const client = this.#clients.get(designator);
if (client) return client;
let id;
try {
id = this.env.VATS.idFromString(designator);
} catch {
throw new Error("no such peer");
}
return this.env.VATS.get(id).gateway();
}
/**
* One HTTP request, as passable data, for the handler serving `key`;
* `null` when nothing serves it.
*
* @param {string} key
* @param {object} request
*/
async serveHttp(key, request) {
await this.#ready;
const handler = this.#handlers.get(key) ?? (await this.#revive(key));
return handler ? E(handler).handle(harden(request)) : null;
}
/** A WebSocket here starts a Cap'n Web session whose main object is an {@link AdminSession}. */
fetch(request) {
return newWorkersRpcResponse(request, new AdminSession(this, this.#clients));
}
}
/**
* What an OCapN client on the admin socket gets: register its own
* gateway under a designator, and reach any peer's.
*/
class AdminSession extends RpcTarget {
#vatAdmin;
#clients;
constructor(vatAdmin, clients) {
super();
this.#vatAdmin = vatAdmin;
this.#clients = clients;
}
/** @param {string} designator @param {any} gateway */
register(designator, gateway) {
if (designator === VAT_ADMIN || /^[0-9a-f]{64}$/.test(designator) || this.#clients.has(designator)) {
throw new Error("designator taken");
}
this.#clients.set(designator, gateway.dup?.() ?? gateway);
}
/** @param {string} designator */
gateway(designator) {
return this.#vatAdmin.gateway(designator);
}
}
/** A vat's way to the router: `env.router` in an OCapN vat. */
export class Router extends WorkerEntrypoint {
gateway(designator) {
return this.env.VAT_ADMIN.getByName(VAT_ADMIN).gateway(designator);
}
}
/**
* Mounts: which vat serves which label set. One instance, by name.
*
* Registration follows Flower: a mount must conflict with every other, so
* no request can carry two mounts' labels. Lookup is stricter than
* Flower's: the request must carry all of a mount's labels.
*/
export class Directory extends DurableObject {
constructor(ctx, env) {
super(ctx, env);
for (const statement of MOUNT_SCHEMA) ctx.storage.sql.exec(statement);
}
/**
* Mount `vat` at `labels`, replacing its mount; `null` unmounts it.
*
* @param {string} vat a Vat's DO id, hex
* @param {Record<string, string> | null} labels
*/
mount(vat, labels) {
const { sql } = this.ctx.storage;
this.ctx.storage.transactionSync(() => {
sql.exec(UNMOUNT_LABELS, vat);
if (!labels) return void sql.exec(UNMOUNT, vat);
const json = JSON.stringify(labels);
if (sql.exec(OVERLAP, json, vat).toArray().length) {
throw new Error("mount overlaps another: add a label whose value tells them apart");
}
sql.exec(MOUNT, vat, json);
sql.exec(MOUNT_LABELS, vat, json);
});
}
/**
* The mount whose labels `request` carries, if any. Registration keeps
* mounts pairwise conflicting, so at most one can match.
*
* @param {Record<string, string>} request
*/
lookup(request) {
const [row] = this.ctx.storage.sql.exec(LOOKUP, JSON.stringify(request)).toArray();
return row ? { vat: row.vat, labels: JSON.parse(row.labels) } : null;
}
}
/**
* A request's labels: its query parameters.
*
* Routing carries no secrets: a URL ends up in logs and `Referer`s. A
* secret travels in-band instead, as on a webkey page: the page keeps it
* in its fragment, reaches the vat by public labels, and sends it in the
* body of a call, which the vat checks like a swissnum.
*
* @param {Request} request
*/
const requestLabels = (request) => {
const labels = {};
for (const [k, v] of new URL(request.url).searchParams) {
if (k in labels) throw new Error(`label ${k} given twice`);
labels[k] = v;
}
return Object.freeze(labels);
};
/**
* The http socket: the ingress. A request reaches the vat mounted at labels
* it carries, which sees the mount's and the request's labels together in
* a `Toybox-Connection-Labels` header (JSON), as a Flower server gets its
* connection labels.
*/
export class Public extends WorkerEntrypoint {
async fetch(request) {
let labels;
try {
labels = requestLabels(request);
} catch (e) {
return new Response(`bad labels: ${e.message}\n`, { status: 400 });
}
const mount = await this.env.DIRECTORY.getByName("directory").lookup(labels);
if (!mount) return new Response("nothing mounted here\n", { status: 404 });
if (mount.vat.startsWith("ingress:")) return this.#serveOcapn(mount, labels, request);
const forwarded = new Request(request);
forwarded.headers.set("Toybox-Connection-Labels", JSON.stringify(mergeLabels(mount.labels, labels)));
const resp = await this.env.VATS.get(this.env.VATS.idFromString(mount.vat)).fetch(forwarded);
if (resp.webSocket) return resp;
const sealed = new Response(resp.body, resp);
sealed.headers.set("Referrer-Policy", "no-referrer");
return sealed;
}
/** A mount made by `makeIngress`: the request goes, as data, to whoever serves it. */
async #serveOcapn(mount, labels, request) {
const { pathname } = new URL(request.url);
const body = ["GET", "HEAD"].includes(request.method) ? "" : await request.text();
const req = { method: request.method, path: pathname, labels: mergeLabels(mount.labels, labels), body };
const res = await this.env.VAT_ADMIN.getByName(VAT_ADMIN).serveHttp(mount.vat, req);
if (!res) return new Response("mounted, but nothing serves it now\n", { status: 503 });
const resp = new Response(res.body ?? "", { status: res.status ?? 200, headers: res.headers ?? {} });
resp.headers.set("Referrer-Policy", "no-referrer");
return resp;
}
}
/**
* Grants in a query parameter, as JSON labels; absent means none.
*
* @param {URL} url
* @param {string} name
*/
const grantParam = (url, name) => {
const v = url.searchParams.get(name);
return v ? JSON.parse(v) : null;
};
/**
* The admin socket: a WebSocket upgrade reaches the {@link VatAdmin} (OCapN
* over Cap'n Web); otherwise, app vats over HTTP:
*
* - `POST /` with an ES module body creates a vat and starts it; the reply
* is `{"vat": <id>, "hash": <code hash>}`, and the id addresses it here.
* - `PUT /<id>` with a body upgrades it; its storage carries over.
* - `PUT /by-name/<name>` does the same for a vat from before ids, when
* vats were named.
*
* Every start states the vat's grants, absent meaning none:
* `?egress=<labels>` (see {@link Egress}) and `?mount=<labels>` (ingress:
* see {@link Public}).
*/
export class Admin extends WorkerEntrypoint {
async fetch(request) {
if (request.headers.get("Upgrade")?.toLowerCase() === "websocket") {
return this.env.VAT_ADMIN.getByName(VAT_ADMIN).fetch(request);
}
const url = new URL(request.url);
const [, first, second] = url.pathname.split("/");
let id;
if (request.method === "POST" && !first) id = this.env.VATS.newUniqueId();
else if (request.method === "PUT" && first === "by-name" && second) id = this.env.VATS.idFromName(second);
else if (request.method === "PUT" && first && !second) {
try {
id = this.env.VATS.idFromString(first);
} catch {
return new Response("no such vat\n", { status: 404 });
}
} else return new Response("POST / or PUT /<id> or PUT /by-name/<name>, with code\n", { status: 405 });
const vat = id.toString();
try {
await this.env.DIRECTORY.getByName("directory").mount(vat, grantParam(url, "mount"));
} catch (e) {
return new Response(`${e.message}\n`, { status: 409 });
}
const egress = url.searchParams.get("egress");
const hash = await this.env.VATS.get(id).start(await request.text(), egress);
return Response.json({ vat, hash });
}
}
export default Public;
+34
View File
@@ -0,0 +1,34 @@
# switchboard: toybox's only way out, after Flower's switchboard.
#
# Each socket is a handle with fixed labels: a WebSocket upgrade starts a
# Cap'n Web session whose main object is that handle (see switchboard.js).
# Whoever starts workerd hands the sockets in (-S/-s), so whoever holds a
# socket's fd holds that handle and no other.
using Workerd = import "/workerd/workerd.capnp";
const config :Workerd.Config = (
services = [
(name = "main", worker = .switchboard),
(name = "nowhere", network = (allow = [])),
(name = "public-net", network = (allow = ["public"], tlsOptions = (trustBrowserCas = true))),
(name = "local-net", network = (allow = ["local"], tlsOptions = (trustBrowserCas = true))),
],
sockets = [
(name = "public", http = (), service = (name = "main", props = (json = "{\"network\":\"public\"}"))),
(name = "local", http = (), service = (name = "main", props = (json = "{\"network\":\"local\"}"))),
],
);
const switchboard :Workerd.Worker = (
compatibilityDate = "2026-10-01",
modules = [
(name = "switchboard.js", esModule = embed "switchboard.js"),
(name = "labels.js", esModule = embed "labels.js"),
(name = "capnweb", esModule = embed "node_modules/capnweb/dist/index-workers.js"),
],
bindings = [
(name = "PUBLIC", service = "public-net"),
(name = "LOCAL", service = "local-net"),
],
globalOutbound = "nowhere",
);
+81
View File
@@ -0,0 +1,81 @@
/** @file switchboard: Flower-style egress handles, served over Cap'n Web. */
import { WorkerEntrypoint } from "cloudflare:workers";
import { RpcTarget, newWorkersRpcResponse } from "capnweb";
import { checkUrl, mergeLabels } from "./labels.js";
/**
* One egress handle: reaches only URLs within its labels, through the
* network its `network` label names. Like a Flower switchboard handle, it
* can only be narrowed; unlike one, it is a Cap'n Web stub, not an fd.
*/
export class Handle extends RpcTarget {
#labels;
#net;
/**
* @param {Record<string, string>} labels
* @param {Fetcher} net
*/
constructor(labels, net) {
super();
this.#labels = labels;
this.#net = net;
}
/** @param {Record<string, string>} more */
constrain(more) {
return new Handle(mergeLabels(this.#labels, more), this.#net);
}
labels() {
return this.#labels;
}
/** @param {Request} request */
fetch(request) {
checkUrl(this.#labels, request.url);
return this.#net.fetch(request);
}
/**
* Open a WebSocket to `url`; its messages cross the session as streams.
*
* @param {string} url `http:` or `https:`, as for a `fetch` upgrade
* @param {string[]} [protocols]
*/
async webSocket(url, protocols = []) {
checkUrl(this.#labels, url);
const headers = { Upgrade: "websocket" };
if (protocols.length) headers["Sec-WebSocket-Protocol"] = protocols.join(", ");
const resp = await this.#net.fetch(url, { headers });
const ws = resp.webSocket;
if (!ws) throw new Error(`no websocket: ${resp.status}`);
ws.accept();
const readable = new ReadableStream({
start(controller) {
ws.addEventListener("message", (e) => controller.enqueue(e.data));
ws.addEventListener("close", () => controller.close());
ws.addEventListener("error", () => controller.error(new Error("websocket error")));
},
});
const writable = new WritableStream({
write: (chunk) => ws.send(chunk),
close: () => ws.close(),
abort: () => ws.close(1011),
});
return { readable, writable, protocol: resp.headers.get("Sec-WebSocket-Protocol") ?? "" };
}
}
/**
* A switchboard socket: a WebSocket upgrade here starts a Cap'n Web
* session whose main object is a {@link Handle} with this socket's labels.
*/
export default class Root extends WorkerEntrypoint {
fetch(request) {
const labels = Object.freeze({ ...this.ctx.props });
const net = { public: this.env.PUBLIC, local: this.env.LOCAL }[labels.network];
if (!net) return new Response("socket has no network\n", { status: 500 });
return newWorkersRpcResponse(request, new Handle(labels, net));
}
}
+15
View File
@@ -0,0 +1,15 @@
[Unit]
Description=toybox switchboard (workerd, Cap'n Web egress handles)
Requires=toybox-switchboard.socket
[Service]
# the local (localhost) handle goes where no other unit can open it;
# hand it out deliberately, if ever
ExecStart=/opt/toybox/node_modules/workerd/bin/workerd serve --experimental /opt/toybox/switchboard.capnp -S public=3 -s local=unix:/run/toybox-switchboard/local.sock
RuntimeDirectory=toybox-switchboard
RuntimeDirectoryMode=0700
DynamicUser=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
SystemCallFilter=@system-service
+11
View File
@@ -0,0 +1,11 @@
[Unit]
Description=toybox switchboard: the public egress handle
[Socket]
ListenStream=/run/toybox/switchboard-public.sock
# only toybox holds this handle: its service joins this group
SocketGroup=toybox
SocketMode=0660
[Install]
WantedBy=sockets.target
+19
View File
@@ -0,0 +1,19 @@
[Unit]
Description=toybox vats (workerd)
Requires=toybox.socket toybox-switchboard.socket
After=toybox-switchboard.socket
[Service]
ExecStart=/opt/toybox/node_modules/workerd/bin/workerd serve --experimental /opt/toybox/config.capnp -S http=3 -S admin=4 -d state=/var/lib/toybox -e switchboard=unix:/run/toybox/switchboard-public.sock
DynamicUser=yes
# to open the public switchboard socket
SupplementaryGroups=toybox
StateDirectory=toybox
# no network but the sockets handed in, and the switchboard's
PrivateNetwork=yes
RestrictAddressFamilies=AF_UNIX
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
SystemCallFilter=@system-service
# not MemoryDenyWriteExecute: V8's JIT needs W+X
+13
View File
@@ -0,0 +1,13 @@
[Unit]
Description=toybox vats: public port and admin socket
[Socket]
# order sets the fds: http=3, admin=4 (see toybox.service)
ListenStream=127.0.0.1:8787
ListenStream=/run/toybox/admin.sock
# whoever can open admin.sock can install code
SocketUser=root
SocketMode=0600
[Install]
WantedBy=sockets.target
+10
View File
@@ -0,0 +1,10 @@
// @endo/init/debug.js, but with `overrideTaming: 'moderate'`: Node 24's
// undici assigns `message` to its errors (ClientDestroyedError when a
// WebSocket closes), which 'min' makes a TypeError.
import '@endo/init/pre-remoting.js';
lockdown({
errorTaming: 'unsafe',
overrideTaming: 'moderate',
domainTaming: 'unsafe',
});
+53
View File
@@ -0,0 +1,53 @@
/** @file The ingress's mount SQL, on node:sqlite: lookup, overlap, and mounts stored before mount_label. */
import { DatabaseSync } from "node:sqlite";
import { test } from "node:test";
import assert from "node:assert/strict";
import { LOOKUP, MOUNT, MOUNT_LABELS, MOUNT_SCHEMA, OVERLAP } from "../mounts-sql.js";
const makeDb = () => {
const db = new DatabaseSync(":memory:");
for (const statement of MOUNT_SCHEMA) db.exec(statement);
const mount = (vat, labels) => {
const json = JSON.stringify(labels);
db.prepare(MOUNT).run(vat, json);
db.prepare(MOUNT_LABELS).run(vat, json);
};
const lookup = (request) => db.prepare(LOOKUP).get(JSON.stringify(request))?.vat ?? null;
const overlaps = (vat, labels) => !!db.prepare(OVERLAP).get(JSON.stringify(labels), vat);
return { db, mount, lookup, overlaps };
};
test("a request reaches the mount whose every label it carries", () => {
const { mount, lookup } = makeDb();
mount("a", { vat: "alice", flavor: "plain" });
mount("b", { vat: "bob" });
assert.equal(lookup({ vat: "alice", flavor: "plain", page: "2" }), "a");
assert.equal(lookup({ vat: "alice" }), null);
assert.equal(lookup({ vat: "alice", flavor: "fancy" }), null);
assert.equal(lookup({ vat: "bob" }), "b");
assert.equal(lookup({}), null);
});
test("a mount with no labels matches any request", () => {
const { mount, lookup } = makeDb();
mount("only", {});
assert.equal(lookup({ anything: "x" }), "only");
});
test("overlap: a mount must conflict with every other", () => {
const { mount, overlaps } = makeDb();
mount("a", { vat: "alice" });
assert.equal(overlaps("b", { vat: "alice", n: "2" }), true);
assert.equal(overlaps("b", { app: "x" }), true);
assert.equal(overlaps("b", { vat: "bob" }), false);
assert.equal(overlaps("a", { vat: "alice", n: "2" }), false, "a vat's own mount doesn't count");
});
test("mounts stored before mount_label are filled in when the schema runs", () => {
const db = new DatabaseSync(":memory:");
db.exec("CREATE TABLE mount (vat TEXT PRIMARY KEY, labels TEXT)");
db.prepare("INSERT INTO mount VALUES (?, ?)").run("old", JSON.stringify({ vat: "old" }));
for (const statement of MOUNT_SCHEMA) db.exec(statement);
assert.equal(db.prepare(LOOKUP).get(JSON.stringify({ vat: "old" }))?.vat, "old");
assert.equal(db.prepare(LOOKUP).get(JSON.stringify({ vat: "other" })), undefined);
});
+105
View File
@@ -0,0 +1,105 @@
/** @file OCapN vats: a client on the admin socket creates a vat and passes it a remote object. */
import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, test } from "node:test";
import assert from "node:assert/strict";
import { E, Far } from "@endo/far";
import { connectClient } from "../client.js";
import { freePort, here, startWorkerd } from "./workerd.js";
const vatSrc = (name) => readFile(join(here, "vats", name), "utf8");
let dir, port, server, client;
const startToybox = () =>
startWorkerd(
"config.capnp",
[
"-s", `http=127.0.0.1:${port}`, "-s", `admin=unix:${join(dir, "admin.sock")}`,
"-d", `state=${join(dir, "state")}`, "-e", `switchboard=unix:${join(dir, "no-switchboard.sock")}`,
],
{ port, host: "127.0.0.1" },
[join(dir, "admin.sock")],
);
before(async () => {
dir = await mkdtemp(join(tmpdir(), "toybox-ocapn-"));
await mkdir(join(dir, "state"));
port = await freePort();
server = await startToybox();
client = await connectClient(join(dir, "admin.sock"), "client-1", { verbose: !!process.env.OCAPN_LOG });
});
after(async () => {
client?.close();
await server?.stop();
await rm(dir, { recursive: true, force: true });
});
test("createVat passes a remote object in; the vat's root comes back", async () => {
const carol = Far("carol", { greet: (name) => `hi ${name}, from carol` });
const { id, root } = await E(client.vatAdmin).createVat(await vatSrc("greeter.js"), { carol });
assert.match(id, /^[0-9a-f]{64}$/);
assert.equal(await E(root).hello(), "hello from the vat");
assert.equal(await E(root).greetVia("vat"), "hi vat, from carol");
});
test("a counter vat counts; two counter vats count apart", async () => {
const src = await vatSrc("counter.js");
const { root: a } = await E(client.vatAdmin).createVat(src);
const { root: b } = await E(client.vatAdmin).createVat(src);
assert.equal(await E(a).increment(), 1);
assert.equal(await E(a).increment(), 2);
assert.equal(await E(b).increment(), 1);
assert.equal(await E(a).read(), 2);
assert.equal(await E(b).read(), 1);
});
test("a vat serves the web through the ingress it is given", async () => {
const ingress = await E(client.vatAdmin).makeIngress({ vat: "hello" });
await E(client.vatAdmin).createVat(await vatSrc("hello.js"), { ingress });
const resp = await fetch(`http://127.0.0.1:${port}/greet?vat=hello`);
assert.equal(resp.status, 200);
assert.equal(resp.headers.get("content-type"), "text/html; charset=utf-8");
assert.match(await resp.text(), /<h1>Hello, world<\/h1><p>from a toybox vat, at \/greet<\/p>/);
});
test("an ingress nobody serves is a 503", async () => {
await E(client.vatAdmin).makeIngress({ vat: "idle" });
assert.equal((await fetch(`http://127.0.0.1:${port}/?vat=idle`)).status, 503);
});
test("after a crash, a request restarts the vat that serves it", async () => {
// its own toybox: a crash breaks every session to it, the shared client's too
const home = await mkdtemp(join(tmpdir(), "toybox-phoenix-"));
await mkdir(join(home, "state"));
const port2 = await freePort();
const start = () =>
startWorkerd(
"config.capnp",
[
"-s", `http=127.0.0.1:${port2}`, "-s", `admin=unix:${join(home, "admin.sock")}`,
"-d", `state=${join(home, "state")}`, "-e", `switchboard=unix:${join(home, "no-switchboard.sock")}`,
],
{ port: port2, host: "127.0.0.1" },
[join(home, "admin.sock")],
);
let toybox = await start();
try {
const creator = await connectClient(join(home, "admin.sock"), "creator");
const ingress = await E(creator.vatAdmin).makeIngress({ vat: "phoenix" });
const { root } = await E(creator.vatAdmin).createVat(await vatSrc("hello.js"), { ingress });
assert.equal((await fetch(`http://127.0.0.1:${port2}/?vat=phoenix`)).status, 200);
await root; // its handoff, settled before the client goes
creator.close();
await toybox.stop();
toybox = await start();
const resp = await fetch(`http://127.0.0.1:${port2}/again?vat=phoenix`);
assert.equal(resp.status, 200);
assert.match(await resp.text(), /Hello, world.*at \/again/);
} finally {
await toybox.stop();
await rm(home, { recursive: true, force: true });
}
});
+266
View File
@@ -0,0 +1,266 @@
/** @file toybox end to end: a real workerd, an admin socket, a public port, a switchboard with two handles. */
import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
import { createServer as createHttpServer, request } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, test } from "node:test";
import assert from "node:assert/strict";
import { WebSocketServer } from "ws";
import { freePort, here, startWorkerd } from "./workerd.js";
const app = (name) => readFile(join(here, "apps", name), "utf8");
/**
* The admin socket: holding it is the authority to create and upgrade vats.
*
* @param {string} socketPath
*/
const makeAdmin = (socketPath) => {
const send = (method, path, src, { egress, mount } = {}) =>
new Promise((resolve, reject) => {
const q = new URLSearchParams();
if (egress) q.set("egress", typeof egress === "string" ? egress : JSON.stringify(egress));
if (mount) q.set("mount", JSON.stringify(mount));
const req = request({ socketPath, path: `${path}?${q}`, method, agent: false }, (res) => {
let body = "";
res.on("data", (c) => (body += c));
res.on("end", () => resolve(res.statusCode === 200 ? JSON.parse(body) : { status: res.statusCode, body }));
});
req.on("error", reject);
req.end(src);
});
return {
/** `createVat`: a new vat, reachable only by its id here, and by its mount */
create: (src, grants) => send("POST", "/", src, grants),
upgrade: (vat, src, grants) => send("PUT", `/${vat}`, src, grants),
/** a vat from before ids */
byName: (name, src, grants) => send("PUT", `/by-name/${name}`, src, grants),
};
};
/** @param {string} base the public origin */
const makePublic = (base) => ({
get: async (pathAndQuery, headers = {}) => {
const resp = await fetch(`${base}${pathAndQuery}`, { headers });
return { status: resp.status, text: await resp.text(), referrerPolicy: resp.headers.get("Referrer-Policy") };
},
text: async (pathAndQuery) => (await fetch(`${base}${pathAndQuery}`)).text(),
put: async (pathAndQuery, src) => (await fetch(`${base}${pathAndQuery}`, { method: "PUT", body: src })).status,
});
/** An HTTP server that answers GET with "plain ok", echoes WebSocket messages, and counts requests. */
const startEcho = async () => {
let hits = 0;
const server = createHttpServer((_req, res) => (hits++, res.end("plain ok")));
const wss = new WebSocketServer({ server });
wss.on("connection", (ws) => ws.on("message", (m) => ws.send(String(m))));
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
return {
host: `127.0.0.1:${server.address().port}`,
hits: () => hits,
stop: () => new Promise((resolve) => (wss.close(), server.closeAllConnections(), server.close(resolve))),
};
};
let dir, port, server, switchboard, echo, echoLabels, admin, pub;
/**
* A toybox in `dir/<name>` that holds one switchboard handle.
*
* @param {string} name
* @param {number} port
* @param {"public" | "local"} handle which switchboard socket it gets
*/
const startToybox = async (name, port, handle) => {
const home = join(dir, name);
await mkdir(join(home, "state"), { recursive: true });
return startWorkerd(
"config.capnp",
[
"-s", `http=127.0.0.1:${port}`, "-s", `admin=unix:${join(home, "admin.sock")}`,
"-d", `state=${join(home, "state")}`, "-e", `switchboard=unix:${join(dir, `sb-${handle}.sock`)}`,
],
{ port, host: "127.0.0.1" },
[join(home, "admin.sock")],
);
};
before(async () => {
dir = await mkdtemp(join(tmpdir(), "toybox-"));
port = await freePort();
echo = await startEcho();
echoLabels = { host: "127.0.0.1", port: echo.host.split(":")[1] };
switchboard = await startWorkerd(
"switchboard.capnp",
["-s", `public=unix:${join(dir, "sb-public.sock")}`, "-s", `local=unix:${join(dir, "sb-local.sock")}`],
{ path: join(dir, "sb-local.sock") },
[join(dir, "sb-public.sock"), join(dir, "sb-local.sock")],
);
// the tests' echo server is on localhost, so this toybox holds the local handle
server = await startToybox("main", port, "local");
admin = makeAdmin(join(dir, "main", "admin.sock"));
pub = makePublic(`http://127.0.0.1:${port}`);
});
after(async () => {
await server?.stop();
await switchboard?.stop();
await echo?.stop();
await rm(dir, { recursive: true, force: true });
});
const at = (name) => ({ mount: { vat: name } });
test("nothing mounted: 404", async () => {
assert.equal((await pub.get("/?vat=nobody")).status, 404);
});
test("createVat returns an id and a code hash; unmounted, the vat is unreachable", async () => {
const { vat, hash } = await admin.create(await app("counter-v1.js"));
assert.match(vat, /^[0-9a-f]{64}$/);
assert.match(hash, /^[0-9a-f]{64}$/);
assert.equal((await pub.get("/")).status, 404);
});
test("install, run, upgrade: the app's state carries over; every start states its grants", async () => {
const { vat } = await admin.create(await app("counter-v1.js"), at("alice"));
assert.equal(await pub.text("/?vat=alice"), "v1 count 1\n");
assert.equal(await pub.text("/?vat=alice"), "v1 count 2\n");
await admin.upgrade(vat, await app("counter-v2.js"), at("alice"));
assert.equal(await pub.text("/?vat=alice"), "v2 count 3\n");
await admin.upgrade(vat, await app("counter-v2.js"));
assert.equal((await pub.get("/?vat=alice")).status, 404);
await admin.upgrade(vat, await app("counter-v2.js"), at("alice"));
assert.equal(await pub.text("/?vat=alice"), "v2 count 4\n");
});
test("vats don't share state", async () => {
await admin.create(await app("counter-v1.js"), at("bob"));
await admin.create(await app("counter-v1.js"), at("carol"));
assert.equal(await pub.text("/?vat=bob"), "v1 count 1\n");
assert.equal(await pub.text("/?vat=carol"), "v1 count 1\n");
});
test("an app gets no fetch", async () => {
await admin.create(await app("try-fetch.js"), at("bob-fetch"));
assert.match(await pub.text("/?vat=bob-fetch"), /^fetch refused: This worker is not permitted to access the internet/);
});
test("the public port can't install code", async () => {
assert.equal(await pub.put("/", "export class App {}"), 404);
});
test("the path is the app's; its labels are the mount's and the request's together", async () => {
await admin.create(await app("show-labels.js"), at("lab"));
const got = await pub.get("/a/b?vat=lab&page=2");
assert.equal(got.text, `/a/b ${JSON.stringify({ vat: "lab", page: "2" })}\n`);
assert.equal(got.referrerPolicy, "no-referrer");
});
test("a label given twice is a 400", async () => {
assert.equal((await pub.get("/?vat=lab&vat=lab")).status, 400);
});
test("mounts that could both match a request are refused", async () => {
const src = await app("show-labels.js");
await admin.create(src, at("x"));
const narrower = await admin.create(src, { mount: { vat: "x", n: "2" } });
assert.equal(narrower.status, 409);
assert.match(narrower.body, /overlaps another/);
// no key in common with the {vat} mounts: ?vat=x&app=x would carry both
assert.equal((await admin.create(src, { mount: { app: "x" } })).status, 409);
assert.match((await admin.create(src, { mount: { vat: "y", n: "2" } })).vat, /^[0-9a-f]{64}$/);
});
test("a request reaches a vat only by naming every label of its mount", async () => {
await admin.create(await app("show-labels.js"), { mount: { vat: "both", flavor: "plain" } });
assert.equal((await pub.get("/?vat=both")).status, 404);
assert.equal((await pub.get("/?vat=both&flavor=fancy")).status, 404);
assert.equal((await pub.get("/?vat=both&flavor=plain")).status, 200);
});
test("routing reads no labels from headers", async () => {
const got = await pub.get("/?vat=both", { "Toybox-Labels": JSON.stringify({ flavor: "plain" }) });
assert.equal(got.status, 404);
});
test("code, state, and mount survive a restart", async () => {
await admin.create(await app("counter-v1.js"), at("dave"));
assert.equal(await pub.text("/?vat=dave"), "v1 count 1\n");
await server.stop();
server = await startToybox("main", port, "local");
assert.equal(await pub.text("/?vat=dave"), "v1 count 2\n");
});
test("a vat from before ids is unreachable until the admin mounts it by its old name", async () => {
await admin.byName("old", await app("counter-v1.js"));
assert.equal((await pub.get("/?vat=old")).status, 404);
await admin.byName("old", await app("counter-v1.js"), at("old"));
assert.equal(await pub.text("/?vat=old"), "v1 count 1\n");
});
const probe = (vat, target, { ws, constrain } = {}) =>
pub.text(
`/?vat=${vat}&url=${encodeURIComponent(`http://${target}/`)}` +
(ws ? "&ws=1" : "") +
(constrain ? `&constrain=${encodeURIComponent(JSON.stringify(constrain))}` : ""),
);
test("a vat granted a host reaches it through the switchboard: fetch and WebSocket", async () => {
await admin.create(await app("egress-probe.js"), { ...at("erin"), egress: echoLabels });
assert.equal(await probe("erin", echo.host), "got: plain ok\n");
assert.equal(await probe("erin", echo.host, { ws: true }), "echo: hello\n");
});
test("same code, no grant: no egress", async () => {
await admin.create(await app("egress-probe.js"), at("frank"));
assert.equal(await probe("frank", echo.host), "no egress granted\n");
});
test("a grant is an object, not ambient: the global fetch still throws", async () => {
await admin.create(await app("try-fetch.js"), { ...at("heidi"), egress: echoLabels });
assert.match(await pub.text("/?vat=heidi"), /^fetch refused: This worker is not permitted to access the internet/);
});
test("the switchboard refuses what a grant doesn't cover", async () => {
await admin.create(await app("egress-probe.js"), { ...at("grace"), egress: { host: "127.0.0.1", port: "1" } });
assert.match(await probe("grace", echo.host), /^got: egress refused: .*egress to 127\.0\.0\.1 not granted/);
assert.match(await probe("grace", echo.host, { ws: true }), /^no websocket: 403 egress refused: .*not granted/);
});
test("a vat can narrow its grant, but not contradict it", async () => {
await admin.create(await app("egress-probe.js"), { ...at("ivan"), egress: { scheme: "http" } });
assert.equal(await probe("ivan", echo.host, { constrain: echoLabels }), "got: plain ok\n");
assert.match(
await probe("ivan", echo.host, { constrain: { scheme: "https" } }),
/^refused: label scheme is already set to a different value/,
);
});
test("a grant stored before labels, a bare host:port, still works", async () => {
await admin.create(await app("egress-probe.js"), { ...at("kim"), egress: echo.host });
assert.equal(await probe("kim", echo.host), "got: plain ok\n");
});
test("a grant survives a restart", async () => {
await server.stop();
server = await startToybox("main", port, "local");
assert.equal(await probe("erin", echo.host, { ws: true }), "echo: hello\n");
});
test("a toybox holding only the public handle can't reach localhost, whatever the grant", async () => {
const port2 = await freePort();
const other = await startToybox("public-only", port2, "public");
try {
const admin2 = makeAdmin(join(dir, "public-only", "admin.sock"));
await admin2.create(await app("egress-probe.js"), { ...at("judy"), egress: echoLabels });
const before = echo.hits();
const got = await (
await fetch(`http://127.0.0.1:${port2}/?vat=judy&url=${encodeURIComponent(`http://${echo.host}/`)}`)
).text();
// workerd reports the public network's refusal (restrictPeers) to JS only as "internal error"
assert.match(got, /^got: egress refused: /);
assert.equal(echo.hits(), before);
} finally {
await other.stop();
}
});
+51
View File
@@ -0,0 +1,51 @@
/** @file Run real workerd processes for tests. */
import { spawn } from "node:child_process";
import { rm } from "node:fs/promises";
import { connect, createServer } from "node:net";
import { join } from "node:path";
export const here = new URL("..", import.meta.url).pathname;
// the package binary, not the .bin shim: the shim forks it, so a kill would orphan workerd
const workerd = join(here, "node_modules/workerd/bin/workerd");
export const freePort = () =>
new Promise((resolve) => {
const s = createServer().listen(0, "127.0.0.1", () => {
const { port } = s.address();
s.close(() => resolve(port));
});
});
/** Resolves once something accepts connections at `opts` (a port or a socket path). */
export const accepting = (opts) =>
new Promise((resolve) => {
const s = connect(opts, () => (s.end(), resolve(true)));
s.on("error", () => resolve(false));
});
/**
* Run workerd on `config` until `stop()`; resolves once `listening` accepts.
*
* @param {string} config
* @param {string[]} args socket, directory, and external overrides
* @param {{ port: number } | { path: string }} listening
* @param {string[]} stale socket files a crash leaves behind; bind() would fail on them
*/
export const startWorkerd = async (config, args, listening, stale = []) => {
for (const f of stale) await rm(f, { force: true });
const child = spawn(workerd, ["serve", "--experimental", join(here, config), ...args], {
stdio: ["ignore", process.env.WORKERD_LOG ? "inherit" : "ignore", "pipe"],
});
let log = "";
// WORKERD_LOG=1 echoes workerd's stderr, for debugging
child.stderr.on("data", (c) => (process.env.WORKERD_LOG ? process.stderr.write(c) : (log += c)));
const exited = new Promise((resolve) => child.on("exit", resolve));
for (let i = 0; i < 100; i++) {
// SIGKILL: a crash is the harder durability test
if (await accepting(listening)) return { stop: () => (child.kill("SIGKILL"), exited) };
await new Promise((r) => setTimeout(r, 50));
}
child.kill("SIGKILL");
throw new Error(`workerd did not start: ${log}`);
};
+59
View File
@@ -0,0 +1,59 @@
/**
* @file The runtime of an OCapN vat: SES, an OCapN peer, and the vat's own
* module (`vat.js`), which exports `buildRootObject(vatPowers, params)`.
*
* Bundled (see build.js) and loaded as the facet's main module beside the
* vat's code. The vat's designator is its id; it reaches other peers, and
* they reach it, through the vatAdmin's router (`env.router`).
*/
import "@endo/init";
import { DurableObject } from "cloudflare:workers";
import { E, Far } from "@endo/far";
import { makeClient } from "@endo/ocapn";
import { makeRpcNetLayer } from "./netlayer.js";
import * as vat from "./vat.js";
/**
* The swissnum of a vat's bootstrap: the vatAdmin starts the vat through it.
* Not exported: workerd takes every export of a main module for an entrypoint.
*/
const VAT_SWISSNUM = "vat";
export class App extends DurableObject {
#gateway;
constructor(ctx, env) {
super(ctx, env);
this.#gateway = this.#boot();
}
async #boot() {
const { vatId, router } = this.env;
let root;
const vatPowers = Object.freeze({ E, Far, storage: this.ctx.storage.kv });
const bootstrap = Far("vatBootstrap", {
/** (Re)build the root: on creation, and when the vatAdmin restarts the vat. */
start: (params) => {
root = vat.buildRootObject(vatPowers, params);
return root;
},
});
// workerd runs FinalizationRegistry callbacks outside any request, where
// sending the resulting GC message is forbidden I/O. So imports are
// never collected here; they go when their session does.
const ocapn = makeClient({
debugLabel: vatId.slice(0, 8),
swissnumTable: new Map([[VAT_SWISSNUM, bootstrap]]),
enableImportCollection: false,
});
const netlayer = await ocapn.registerNetlayer(
makeRpcNetLayer({ designator: vatId, openGateway: (designator) => router.gateway(designator) }),
);
return netlayer.gateway;
}
/** This vat's OCapN gateway, for the router. */
gateway() {
return this.#gateway;
}
}
+15
View File
@@ -0,0 +1,15 @@
/**
* A counter whose count lives in the vat's storage.
*
* TODO: a durable Exo once vatPowers offers a zone, e.g.
* `zone.exoClass("Counter", undefined, () => ({ count: 0 }), { incr() { this.state.count += 1; return this.state.count; } })`
*/
export const buildRootObject = ({ Far, storage }) =>
Far("counterRoot", {
increment: () => {
const n = (storage.get("count") ?? 0) + 1;
storage.put("count", n);
return n;
},
read: () => storage.get("count") ?? 0,
});
+6
View File
@@ -0,0 +1,6 @@
/** A vat that greets through the `carol` it was created with. */
export const buildRootObject = ({ E, Far }, { carol }) =>
Far("greeterRoot", {
greetVia: (name) => E(carol).greet(name),
hello: () => "hello from the vat",
});
+12
View File
@@ -0,0 +1,12 @@
/** Hello, world, served through the `ingress` it was created with. */
export const buildRootObject = ({ E, Far }, { ingress }) => {
const handler = Far("helloHandler", {
handle: ({ path }) => ({
status: 200,
headers: { "content-type": "text/html; charset=utf-8" },
body: `<!doctype html><title>hello</title><h1>Hello, world</h1><p>from a toybox vat, at ${path}</p>\n`,
}),
});
E(ingress).serve(handler);
return Far("helloRoot", {});
};