Compare commits

..
9 Commits
Author SHA1 Message Date
dckc ff2e7841f2 capsite/webapp: postForm, a multipart POST that can echo a cookie into a field
Some sites check a double-submit token: the session value sent as a
cookie and again in the form body. postForm(fields, echoCookies) builds
a multipart body and copies the named cookies (from the header store,
at send time) into fields, so the caller never sees the value.

It returns a Reply instead of throwing on non-OK: status, content type,
content-disposition, the redirect location with its query stripped, and
the body as bytes (the caller decodes, e.g. per a charset the body
declares). Redirects are not followed, so an expired session shows up
as a 3xx. Set-Cookie is not passed back. Errors name keys, never values.

Generated-by: Claude Opus 5.5
2026-10-11 14:22:09 -05:00
dckc 7876938f3e capsite/docs: describe the wiring diagram for screen readers
The SVG gets role="img" with a <title> and a <desc> that says in prose
who refers to what, since the arrows carry the meaning and are invisible
to assistive tech. The rendered PNG is unchanged.

Generated-by: Claude Opus 5.5
2026-10-09 02:32:22 -05:00
dckc a921d65021 capsite/docs: cookie-rotation wiring diagram (PNG)
A headless-Chromium screenshot of docs/cookie-rotation-wiring.html.

Generated-by: Claude Opus 5.5
2026-10-09 02:32:22 -05:00
dckc 055b572297 capsite/docs: cookie-rotation wiring diagram (source)
Who holds what after mint: Alice holds the store id (rotate, revoke),
diigo-cache and a leaked-id Mallory hold only the instance, whose
init.headerStore reaches the store's read-only facet. Drawn as an SVG
page in the style of MarkM's ERTP slides.

Generated-by: Claude Opus 5.5
2026-10-09 02:32:22 -05:00
dckc 4dd3fe6bde capsite/diigo-cache: the wire page hands the owner the store id
webapp's mint now answers a store id (x-webapp-store-id) beside the
instance id: authority to rotate or revoke the diigo cookie. The wire
page shows it apart from the instance id, with its own copy button,
petname, and password-manager save; the cache never gets it. A webapp
that sends none gets a note on the page and a warning in the log.

Generated-by: Claude Opus 5.5
2026-10-09 02:32:22 -05:00
dckc 3f711a5f4b capsite/webapp: the cookie's store is the owner's, apart from the instance
Letting the instance id rotate the cookie let its holder (the cache, or
whoever learns the id) swap in another account's session, which the
owner's logout would not stop. Now mint makes two things: the instance,
and a header store (lib's MapStoreDo, shaped ("cookie", { keyShape:
"cookie", valueShape: M.string() })). The instance id is authority to
use the cookie; the store id, for the account owner, to rotate (PUT
/store/<storeId>/cookie, or WebAppFactory.store) or revoke (DELETE).
Instances read the store's read-only view at every send, via init's new
headerStore.

This replaces the in-instance cookie store and its migration: instances
minted earlier keep their cookie in init.headers, untouched, and simply
cannot rotate. The MapStoreDo class arrives as wrangler migration v2
(additive).

Generated-by: Claude Opus 5.5
2026-10-09 02:32:22 -05:00
dckc 357e4561c4 capsite/lib: endo's own matcher data, smallcaps, and MapStoreDo
Matchers are now exactly what @endo/patterns makes: tagged records as
from pass-style's makeTagged (M.string() is match:string with payload
[], M.any() is match:any with payload undefined). Structured clone drops
their symbol-keyed and non-enumerable properties, so they cross DO
storage and Workers RPC in marshal's smallcaps encoding (the subset
patterns need).

MapStoreDo is a MapStore as a DO of its own: its creator fixes label and
(encoded) shapes once; its id is full authority, and readOnly() hands
out the queries alone.

Generated-by: Claude Opus 5.5
2026-10-09 02:32:22 -05:00
dckc 10414c2ce6 capsite/webapp: rotate the cookie in place
The cookie moves out of the immutable init into a MapStore (key shape
"cookie", value M.string()) in the instance's DO storage. Handles get
its read-only view via the new WebApp.withHeaderMap, which reads at
every send, so a rotation reaches handles already out and the webapp
id, and with it the cache's wiring, stays put (checklist goal 6).

Whoever holds the id can rotate, by RPC (WebAppFactory.cookies(id)) or
POST /at/<id>/cookie; the diigo account owner revokes by logging out.

Durable state: instances minted earlier keep the cookie in
init.headers. The first handle() moves it to the store and rewrites
init without it, in one transaction. Code from before this commit
would then see no cookie, so rolling back past it needs the reverse
move.

webapp gains a package.json and a vitest workerd pool for the tests.

Generated-by: Claude Opus 5.5
2026-10-09 02:32:22 -05:00
dckc 9179bdbf38 capsite/lib: MapStore and patterns work-alikes
Enough of @agoric/store's MapStore and @endo/patterns' M for the
credential-rotation design: makeMapStore(label, { keyShape, valueShape },
kv) keeps entries in a DO's sync KV under store:<label>:, and readOnly()
hands out the queries alone. Facets are workerd RpcTargets in place of
endo's Far.

Unlike endo, error messages never include keys or values: the values
here are credentials, and messages cross RPC into logs.

Generated-by: Claude Opus 5.5
2026-10-09 02:32:22 -05:00
51 changed files with 5717 additions and 1486 deletions

No files matched your search

-1
View File
@@ -10,4 +10,3 @@ dist/
worker-configuration.d.ts worker-configuration.d.ts
emdash-env.d.ts# diigo exports: personal data emdash-env.d.ts# diigo exports: personal data
export/ export/
result
+13 -16
View File
@@ -89,12 +89,6 @@ narrative.
[the issues sketch](potluck/issues-sketch.md))? If the policy [the issues sketch](potluck/issues-sketch.md))? If the policy
changes, stripping stored rows is a durable-state migration. 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. - [ ] **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-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. - [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,16 +99,21 @@ 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? - [ ] **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)). - [ ] **5. Deployed end-to-end** (order matters):
- [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. - [ ] 5-i. webapp: `cd webapp && npx wrangler deploy`
- [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-ii. diigo-cache: rate-limit `/api` (and `/public/*`) first
- [ ] 5-iii. madmode/potluck reads the public page from prod: no service binding off Cloudflare ([open issue 5](diigo-cache/doc/open-issues.md)). (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 - [ ] **6. Cookie expiry**: when diigo's session ends, head refreshes
fail; the public page keeps serving what's stored (say so on the fail; the public page keeps serving what's stored (say so on the
page, don't fail silently). Rotation is manual: re-mint via page, don't fail silently). Rotation is in place, keeping the
`/_connect`. Open question: can an existing cache be re-wired to webapp id (so the cache's wiring and ids hold), by the store id
a new webapp id (keeping its cache id and public username), or minted alongside it and kept by the account owner: `PUT
does re-mint mean a new cache? Prefer re-wire — durable ids. /store/<storeId>/cookie` (webapp README, "The header store").
Still open: a rotate form in diigo-cache's UI.
- [ ] **7. bib sync #195**: repeat the pattern for the next - [ ] **7. bib sync #195**: repeat the pattern for the next
read-access need (webapp mints for any origin; the cache's read-access need (webapp mints for any origin; the cache's
item shape is diigo-specific): [the zotero goal tree](zotero-checklist.md). item shape is diigo-specific): [the zotero goal tree](zotero-checklist.md).
@@ -220,8 +219,6 @@ to every goal in this tree.
pattern, abstracted from the E-on-Java sources (bearer secrets, pattern, abstracted from the E-on-Java sources (bearer secrets,
YURL32, secret≠address); the reason ids ride only fragments and POST YURL32, secret≠address); the reason ids ride only fragments and POST
bodies 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) — - [the mm-diigo diigo-bak scripts](https://github.com/dckc/mm-diigo) —
provenance of the fluent client and dump generator (`projects/diigo-bak/`: provenance of the fluent client and dump generator (`projects/diigo-bak/`:
WebApp.js, diigo-dump.mjs, diigo-interact.mjs; mm-diigo commit 7dbb367, 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)"] login["/cache/ login<br/>(password manager)"]
admin["webkey page<br/>/cache/ + key in fragment"] admin["webkey page<br/>/cache/ + key in fragment"]
public["/public/username<br/>(anyone)"] public["/public/username<br/>(anyone)"]
search["/public/username?q=…&in=…<br/>search, date windows"]
home -->|create| connect home -->|create| connect
connect -->|"POST /_mint (cookie)"| wire connect -->|"POST /_mint (cookie)"| wire
@@ -60,12 +59,8 @@ flowchart LR
home -->|"dump: POST / (cache id + page)"| home home -->|"dump: POST / (cache id + page)"| home
admin -->|"api.cache(key) …"| admin admin -->|"api.cache(key) …"| admin
created -->|"link (public mode)"| public 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 | | action | where | transport | authority |
|---|---|---|---| |---|---|---|---|
| mint the diigo session | `/_connect` | HTTP `POST /_mint` (relays webapp's form) | the cookie | | 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 | | …of the public companion | webkey page | RPC `publicCache().…` | cache key |
| invalidate the last N days | webkey page | RPC `invalidateRecent(days)` | 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 | | 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 | | bulk dump for another worker | — | service binding `DiigoBridge.dumpNdjson` | worker config |
⚠ misalignments: ⚠ 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 - ~~the public page can write~~ — resolved: it reads only through the
read-only `viewer()` facet; unfetched pages say so read-only `viewer()` facet; unfetched pages say so
- the webkey page has no dump or publish; the home page has no fill - 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) ## 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 ## 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. - **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. - **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
}
-134
View File
@@ -1,134 +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;
# the commit a build came from; a dirty tree's ends in -dirty
shortRev = self.shortRev or self.dirtyShortRev or "unknown";
# a clean tree's commit, whose source anyone can read; systemctl
# status lists it under Docs:
sourceUrl = lib.optionalString (self ? rev) "https://git.inference.coop/dckc/captoys/src/commit/${self.rev}/diigo-cache";
# 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-${shortRev}";
inherit src;
sourceRoot = "${finalAttrs.src.name}/diigo-cache";
nativeBuildInputs = [
pkgs.nodejs
pkgs.pnpm_10
pkgs.pnpmConfigHook
pkgs.wrangler
];
pnpmDeps = pkgs.fetchPnpmDeps {
inherit (finalAttrs) pname src sourceRoot;
# not the rev: the deps don't change with each commit
version = "0.0.0";
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
substitute ${./nix/diigo-cache.service} $out/lib/systemd/system/diigo-cache.service \
--replace-fail '@source@' '${sourceUrl}'
# the docs, at a path the profile keeps across upgrades
doc=$out/share/doc/diigo-cache
mkdir -p $doc
cp ${./README.md} $doc/README.md
cp ${./CONTRIBUTING.md} $doc/CONTRIBUTING.md
cp -r ${./doc} $doc/doc
echo ${self.rev or self.dirtyRev or "unknown"} > $doc/REVISION
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
);
-33
View File
@@ -1,33 +0,0 @@
[Unit]
Description=diigo-cache and webapp (workerd)
# the profile's README, and the commit's source (a clean build's only)
Documentation=file:///nix/var/nix/profiles/diigo-cache/share/doc/diigo-cache/README.md @source@
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 */ * pages at MS_PER_CALL; this keeps steps from running back to back */
const FILL_STEP_DELAY_MS = 1000; 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 * 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. * (new state, additive), so it survives eviction; advanced by alarms.
@@ -74,9 +66,6 @@ export type FillStatus = {
updatedAt: string; updatedAt: string;
/** why it failed: safe to show and log (no ids, no header values) */ /** why it failed: safe to show and log (no ids, no header values) */
error?: string; 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) */ /** 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 await null; // let the subclass constructor finish: `kind` is its field
const from = this.#writer.migrate(); const from = this.#writer.migrate();
if (from < SCHEMA_VERSION) console.log({ event: "schema", kind: this.kind, from, to: SCHEMA_VERSION }); 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 * cache, `pagesPerStep` per alarm (default 20, 1–50). Starting while a
* job runs returns that job unchanged; a finished, stopped, or failed * job runs returns that job unchanged; a finished, stopped, or failed
* job is replaced by a fresh one (cached pages are skipped anyway). * 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> { async startFill(opts: { pagesPerStep?: number } = {}): Promise<FillStatus> {
const current = await this.fillStatus(); const current = await this.fillStatus();
if (current?.state === "running" && fillCountsAsNow(current)) return current; if (current?.state === "running" && fillCountsAsNow(current)) return current;
const step = Math.trunc(opts.pagesPerStep ?? 20); const step = Math.trunc(opts.pagesPerStep ?? 20);
if (!(step >= 1 && step <= 50)) throw new Error("pagesPerStep: expected 1–50"); 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 now = this.#iso();
const status: FillStatus = { const status: FillStatus = {
state: "running", state: "running",
@@ -216,22 +192,13 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
fetched: 0, fetched: 0,
startedAt: now, startedAt: now,
updatedAt: now, updatedAt: now,
...(refetchThrough === undefined ? {} : { refetchThrough }),
}; };
await this.ctx.storage.put({ fill: status, fillStep: step }); await this.ctx.storage.put({ fill: status, fillStep: step });
await this.ctx.storage.setAlarm(this.#clock.now() + FILL_STEP_DELAY_MS); 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; 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 fill job's progress, or undefined if none was ever started;
* the page count comes from any cached page until the job learns it */ * the page count comes from any cached page until the job learns it */
async fillStatus(): Promise<FillStatus | undefined> { 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; return fill && fill.pages === null ? { ...fill, pages: this.#knownPages() } : fill;
} }
/** stop the fill job after its current step, and its refreshes; /** stop the fill job after its current step; cached pages stay */
* cached pages stay */
async stopFill(): Promise<FillStatus> { async stopFill(): Promise<FillStatus> {
const current = await this.fillStatus(); const current = await this.fillStatus();
if (!current) throw new Error("no fill job to stop"); 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() }; const stopped: FillStatus = { ...current, state: "stopped", updatedAt: this.#iso() };
await this.ctx.storage.put("fill", stopped); await this.ctx.storage.put("fill", stopped);
await this.ctx.storage.deleteAlarm(); 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, /** one fill step: up to `fillStep` pages, progress saved after each,
* then the next step is scheduled (or the job ends, and the next * then the next step is scheduled (or the job ends) */
* refresh is). On a job that has ended, the refresh starts. */
async alarm(): Promise<void> { async alarm(): Promise<void> {
const step = (await this.ctx.storage.get<number>("fillStep")) ?? 20; const step = (await this.ctx.storage.get<number>("fillStep")) ?? 20;
let status = await this.fillStatus(); 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 // a job saved under another page size or numbering counts its pages
// differently: resuming it would skip or repeat items, so it fails // differently: resuming it would skip or repeat items, so it fails
if (status?.state === "running" && !fillCountsAsNow(status)) { if (status?.state === "running" && !fillCountsAsNow(status)) {
@@ -292,7 +253,6 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
status = { ...status, state: "failed", error, updatedAt: this.#iso() }; status = { ...status, state: "failed", error, updatedAt: this.#iso() };
console.error({ event: "fill", kind: this.kind, state: "failed", error }); console.error({ event: "fill", kind: this.kind, state: "failed", error });
await this.ctx.storage.put("fill", status); await this.ctx.storage.put("fill", status);
await this.ctx.storage.setAlarm(this.#clock.now() + REFRESH_INTERVAL_MS);
return; return;
} }
for (let i = 0; i < step && status?.state === "running"; i += 1) { for (let i = 0; i < step && status?.state === "running"; i += 1) {
@@ -301,7 +261,7 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
break; break;
} }
try { 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); const fetched = status.fetched + (page.cached ? 0 : 1);
// a page whose own total says the data ended before it (diigo // 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 // 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); 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 }); 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); 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 /** 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`). * rides in the result (`cached`).
*/ */
async page(pageNum: number, count: number): Promise<CachePage> { 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(); const init = await this.wiring();
if (!init) throw new Error("not wired: this cache id was never set up"); 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) { if (hit) {
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "hit", items: hit.items.length }); console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "hit", items: hit.items.length });
return hit; return hit;
@@ -376,7 +329,7 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
this.#step += 1; this.#step += 1;
this.#pause = this.#clock.sleep(MS_PER_CALL); this.#pause = this.#clock.sleep(MS_PER_CALL);
// a request ahead of us at the gate may have etched this page // 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) { if (late) {
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "hit", items: late.items.length }); console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "hit", items: late.items.length });
return late; return late;
@@ -404,7 +357,7 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
} }
const kept = this.keep(toRows(data.items, console)); const kept = this.keep(toRows(data.items, console));
// fetched vs kept: the public cache's drop of private rows shows here // 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); return this.#etch(pageNum, count, data.total, kept);
} }
+36 -17
View File
@@ -174,11 +174,13 @@ async function proxyMint(request: Request, env: Env): Promise<Response> {
const detail = (await res.text()).slice(0, 200); const detail = (await res.text()).slice(0, 200);
return home(env, { error: `mint said ${res.status}: ${detail}` }, null); return home(env, { error: `mint said ${res.status}: ${detail}` }, null);
} }
// webapp answers {id} (+ x-webapp-id); the id rides the header, the // webapp answers {id, storeId} (+ x-webapp-id, x-webapp-store-id);
// wire page is ours // the ids ride the headers, the wire page is ours
const id = res.headers.get("x-webapp-id"); const id = res.headers.get("x-webapp-id");
if (!id) return home(env, { error: "mint produced no id" }, null); if (!id) return home(env, { error: "mint produced no id" }, null);
return await wirePage(id); const storeId = res.headers.get("x-webapp-store-id");
if (!storeId) console.warn({ event: "mint", outcome: "no store id: this session cannot be rotated" });
return await wirePage(id, storeId);
} catch (err) { } catch (err) {
console.error({ event: "mint", error: String(err) }); console.error({ event: "mint", error: String(err) });
return home(env, { error: `mint failed: ${String(err)}` }, null); return home(env, { error: `mint failed: ${String(err)}` }, null);
@@ -188,22 +190,37 @@ async function proxyMint(request: Request, env: Env): Promise<Response> {
/** the credential-save helper, once per page (see ./pm-save.ts) */ /** the credential-save helper, once per page (see ./pm-save.ts) */
const PM_SAVE_JS = pmSave.toString(); const PM_SAVE_JS = pmSave.toString();
/** the suggested petname gets the holder's local hh:mm (the worker only /** the suggested petname (in the input with id `petnameId`) gets the
* knows UTC), so two saves the same day are told apart at a glance */ * holder's local hh:mm (the worker only knows UTC), so two saves the same
const PETNAME_TIME_JS = `{ * day are told apart at a glance */
const p = document.getElementById("petname"); function petnameTimeJs(petnameId: string): string {
return `{
const p = document.getElementById(${JSON.stringify(petnameId)});
const d = new Date(); const d = new Date();
p.value += " " + String(d.getHours()).padStart(2, "0") + ":" + String(d.getMinutes()).padStart(2, "0"); p.value += " " + String(d.getHours()).padStart(2, "0") + ":" + String(d.getMinutes()).padStart(2, "0");
}`; }`;
/** the onclick that hands pmSave its browser powers */
function pmSaveClick(value: string): string {
return `pmSave(this, ${JSON.stringify(value)}, { petname: document.getElementById("petname"), credentials: navigator.credentials, PasswordCredential: window.PasswordCredential, log: console })`;
} }
/** the wire step, with the freshly-minted webapp id pre-filled */ /** the onclick that hands pmSave its browser powers, saving under the
async function wirePage(webappId: string): Promise<Response> { * petname in the input with id `petnameId` */
function pmSaveClick(value: string, petnameId: string): string {
return `pmSave(this, ${JSON.stringify(value)}, { petname: document.getElementById(${JSON.stringify(petnameId)}), credentials: navigator.credentials, PasswordCredential: window.PasswordCredential, log: console })`;
}
/** the wire step, with the freshly-minted webapp id pre-filled, and the
* store id (rotating the cookie) for the account owner to keep */
async function wirePage(webappId: string, storeId: string | null): Promise<Response> {
const fingerprint = await nick(webappId); const fingerprint = await nick(webappId);
const storeSection = storeId
? `<h2>keep: the cookie's store id</h2>
<p>This one is yours alone, not the cache's: with it you can rotate the
diigo session (log in again, paste the new cookie) or revoke it. Fingerprint
<code>${esc(await nick(storeId))}</code>
<button type="button" onclick='navigator.clipboard.writeText(${JSON.stringify(storeId)}).then(() => this.textContent = "copied ✓")'>copy</button></p>
<p><label>your petname for it <input id="store-petname" autocomplete="off" size="30" value="${esc(`diigo cookie store ${await nick(storeId)}`)}"></label></p>
<script>${petnameTimeJs("store-petname")}</script>
<p><button type="button" onclick='${pmSaveClick(storeId, "store-petname")}'>save to password manager</button></p>`
: `<p><b>note:</b> webapp sent no store id, so this session's cookie cannot be rotated; when it expires, mint again.</p>`;
const body = `<!doctype html> const body = `<!doctype html>
<html><head><meta charset="utf-8"><title>diigo cache: step 2 — wire the cache</title></head> <html><head><meta charset="utf-8"><title>diigo cache: step 2 — wire the cache</title></head>
<body> <body>
@@ -212,8 +229,10 @@ async function wirePage(webappId: string): Promise<Response> {
<button type="button" onclick='navigator.clipboard.writeText(${JSON.stringify(webappId)}).then(() => this.textContent = "copied ✓")'>copy</button></p> <button type="button" onclick='navigator.clipboard.writeText(${JSON.stringify(webappId)}).then(() => this.textContent = "copied ✓")'>copy</button></p>
<p><label>your petname for it <input id="petname" autocomplete="off" size="30" value="${esc(`diigo webapp ${fingerprint}`)}"></label> <p><label>your petname for it <input id="petname" autocomplete="off" size="30" value="${esc(`diigo webapp ${fingerprint}`)}"></label>
<small>(private to you: the password-manager username; never sent to the server)</small></p> <small>(private to you: the password-manager username; never sent to the server)</small></p>
<script>${PETNAME_TIME_JS}</script> <script>${petnameTimeJs("petname")}</script>
<p><button type="button" onclick='${pmSaveClick(webappId)}'>save to password manager</button></p> <p><button type="button" onclick='${pmSaveClick(webappId, "petname")}'>save to password manager</button></p>
${storeSection}
<h2>wire</h2>
<p>choose the cache mode, then <b>wire</b> — the next page shows the <p>choose the cache mode, then <b>wire</b> — the next page shows the
<b>cache id</b> (copy that too), after which you land back on home:</p> <b>cache id</b> (copy that too), after which you land back on home:</p>
<form method="post" action="/_wire"> <form method="post" action="/_wire">
@@ -320,8 +339,8 @@ async function wiredPage(cacheId: string, note: string, hasPublic: boolean): Pro
<button type="button" onclick='navigator.clipboard.writeText(${JSON.stringify(cacheId)}).then(() => this.textContent = "copied ✓")'>copy</button></p> <button type="button" onclick='navigator.clipboard.writeText(${JSON.stringify(cacheId)}).then(() => this.textContent = "copied ✓")'>copy</button></p>
<p><label>your petname for it <input id="petname" autocomplete="off" size="30" value="${esc(`diigo cache ${fingerprint}`)}"></label> <p><label>your petname for it <input id="petname" autocomplete="off" size="30" value="${esc(`diigo cache ${fingerprint}`)}"></label>
<small>(private to you: the password-manager username; never sent to the server)</small></p> <small>(private to you: the password-manager username; never sent to the server)</small></p>
<script>${PETNAME_TIME_JS}</script> <script>${petnameTimeJs("petname")}</script>
<p><button type="button" onclick='${pmSaveClick(cacheId)}'>save to password manager</button></p> <p><button type="button" onclick='${pmSaveClick(cacheId, "petname")}'>save to password manager</button></p>
<p>${note}</p> <p>${note}</p>
<p><a href="/cache/#${esc(cacheId)}">open this cache</a> — its <b>webkey</b> <p><a href="/cache/#${esc(cacheId)}">open this cache</a> — its <b>webkey</b>
(bookmark it, or save the id above): fill it, watch progress${hasPublic ? ", fill its public companion" : ""}.</p> (bookmark it, or save the id above): fill it, watch progress${hasPublic ? ", fill its public companion" : ""}.</p>
+3 -70
View File
@@ -26,14 +26,10 @@ const wired = async (webappId = "fake-webapp-id") => {
return stub; return stub;
}; };
const HOUR = 60 * 60 * 1000; /** run alarms until none is scheduled (bounded, so a runaway job fails) */
const drain = async (stub: DurableObjectStub, max = 20) => {
/** 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) => {
let ran = 0; let ran = 0;
const running = async () => (await stub.fillStatus())?.state === "running"; while (ran < max && (await runDurableObjectAlarm(stub))) ran += 1;
while (ran < max && (await running()) && (await runDurableObjectAlarm(stub))) ran += 1;
expect(ran).toBeLessThan(max); expect(ran).toBeLessThan(max);
return ran; return ran;
}; };
@@ -124,9 +120,6 @@ describe("fill job (goal 1e)", () => {
}); });
await drain(stub); await drain(stub);
expect(await stub.fillStatus()).toMatchObject({ state: "done", updatedAt: at }); 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 () => { 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 }); 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 () => { it("a public cache's fill stores no private rows", async () => {
const stub = testEnv.PUBLIC_DO.get(testEnv.PUBLIC_DO.newUniqueId()); const stub = testEnv.PUBLIC_DO.get(testEnv.PUBLIC_DO.newUniqueId());
await stub.setup({ webappId: "fake-webapp-id" }); await stub.setup({ webappId: "fake-webapp-id" });
@@ -1,7 +1,7 @@
<!doctype html> <!doctype html>
<html><head><meta charset="utf-8"> <html><head><meta charset="utf-8">
<title>weekly roundup on main: who holds what</title> <title>webapp cookie rotation: 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 --> <!-- drawn after the style of MarkM's ERTP slides; cookie-rotation-wiring.png is a headless-Chromium screenshot of this page -->
<style> <style>
html, body { margin: 0; background: #fff; } html, body { margin: 0; background: #fff; }
.sans { font-family: "Helvetica Neue", "DejaVu Sans", sans-serif; } .sans { font-family: "Helvetica Neue", "DejaVu Sans", sans-serif; }
@@ -11,17 +11,18 @@
<body> <body>
<svg id="c" xmlns="http://www.w3.org/2000/svg" width="1120" height="820" viewBox="0 0 1120 820" <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"> role="img" aria-labelledby="title desc">
<title id="title">weekly roundup on main: who holds what</title> <title id="title">webapp cookie rotation: who holds what</title>
<desc id="desc">Three actors and two makers. Alice holds a cache id, saved in her <desc id="desc">Three actors and two makers. Alice holds a reference to a store made by
password manager, which refers to a DiigoCache. Each DiigoCache refers to its makeMapStore, and to diigo-cache, which she wired up. She rotates the cookie
wiring table: webappId and publicId. webappId refers to an access object made by saying: await E(store).set("cookie", freshCookie). The store, and its
by makeWebApp; publicId refers to a PublicCache, which refers to the same read-only facets, both refer to the store's kv table, whose one row maps
access. Each access refers to its init table: url and headers, and the "cookie" to the session; its shapes are keyShape "cookie" and valueShape
headers hold the diigo session cookie. A viewer facet reads the PublicCache M.string(). makeWebApp makes access objects; each refers to its init
and can't fetch or write; diigo-week, the potluck plugin, reaches only the table: url, headers, and headerStore. headerStore refers to the store's
viewer, as the public page's h-feed. Mallory, who learned the instance id, read-only facet, which access reads at every send. diigo-cache holds a
also refers to access, so she can use the cookie. The wiring is set once, so reference to access. Mallory, who learned the instance id, also holds a
when Alice logs in again she has to mint a new access and a new cache.</desc> reference to access, so she can use the cookie, but she has no reference
to the store, so she cannot rotate it or swap in her own session.</desc>
<defs> <defs>
<radialGradient id="ball" cx="40%" cy="35%" r="70%"> <radialGradient id="ball" cx="40%" cy="35%" r="70%">
<stop offset="0%" stop-color="#7cc8f8"/> <stop offset="0%" stop-color="#7cc8f8"/>
@@ -98,51 +99,48 @@ function table(x, y, title, rows, colW) {
return { rowY: (i) => y + 36 + i * rowH + rowH / 2, x, w, colX: x + colW[0] }; return { rowY: (i) => y + 36 + i * rowH + rowH / 2, x, w, colX: x + colW[0] };
} }
// speech bubble (Alice, after logging in to diigo again) // speech bubble (Alice rotates after logging in again)
el("path", { 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", 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, 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" }); const code = el("text", { x: 46, y: 62, class: "mono", "font-size": 17, fill: "#222" });
code.innerHTML = '<tspan fill="#b0177b">await</tspan> E(store).set(<tspan fill="#1a7f37">"cookie"</tspan>, freshCookie);';
// actors // actors
actor(150, 200, "Alice"); actor(150, 200, "Alice");
actor(560, 200, "diigo-week"); actor(560, 200, "diigo-cache");
actor(930, 200, "Mallory"); actor(930, 200, "Mallory");
// makers // makers
maker(30, 320, 500, 470, "diigo-cache"); maker(30, 320, 470, 470, "makeMapStore");
maker(590, 320, 500, 470, "makeWebApp"); maker(560, 320, 530, 470, "makeWebApp");
// diigo-cache insides // MapStoreDo insides
obj(70, 410, 150, 80, "DiigoCache", true); obj(80, 420, 120, 80, "store");
const wiring = table(270, 410, "wiring", [["webappId", "…"], ["publicId", "…"]], [110, 90]); obj(80, 600, 120, 80, "readOnly", true);
obj(70, 610, 150, 80, "PublicCache", true); const kv = table(260, 430, "kv", [["cookie", "session=…"], ["", ""], ["", ""], ["", ""], ["", ""]], [90, 110]);
obj(300, 640, 120, 60, "viewer", true);
// makeWebApp insides // WebAppDo insides
obj(640, 560, 140, 90, "access", true); obj(620, 560, 140, 90, "access", true);
const init = table(840, 420, "init", [["url", "diigo…"], ["headers", "{cookie}"]], [100, 105]); const init = table(830, 420, "init", [["url", "diigo…"], ["headers", "{…}"], ["headerStore", ""], ["", ""]], [130, 85]);
// references // references
ref(140, 228, 130, 403, 0.03); // Alice → DiigoCache (cache id) ref(140, 228, 125, 418, 0.05); // Alice → store
ref(560, 228, 380, 627, -0.04); // diigo-week → viewer ref(172, 224, 508, 210, 0.04); // Alice → diigo-cache (she wired it)
ref(930 - 14, 200 + 20, 740, 553, -0.08); // Mallory → access ref(560 - 6, 200 + 18, 660, 553, 0.12); // cache → access
ref(160, 450, wiring.x - 2, wiring.rowY(0), 0.05); // DiigoCache → wiring ref(930 - 14, 200 + 20, 720, 553, -0.08); // Mallory → access
ref(wiring.colX + 40, wiring.rowY(0), 646, 580, -0.12); // webappId → access ref(160, 470, kv.x - 2, kv.rowY(0), 0.05); // store → kv
ref(wiring.colX + 40, wiring.rowY(1), 165, 598, -0.08); // publicId → PublicCache ref(150, 666, kv.x - 2, kv.rowY(0) + 6, -0.25); // readOnly → kv (read)
ref(200, 688, 632, 640, 0.25); // PublicCache → access ref(760, 600, init.x - 2, init.rowY(2), -0.1); // access → init
ref(306, 675, 232, 668, 0.1); // viewer → PublicCache (read) ref(init.colX + 40, init.rowY(2), 208, 640, -0.28); // headerStore → readOnly
ref(780, 600, init.x - 2, init.rowY(1), -0.1); // access → init
// captions // captions
const cap = (x, y, s, attrs = {}) => text(x, y, s, "sans", { "font-size": 14, fill: "#33536f", ...attrs }); 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, 118, "holds the instance id:", {});
cap(930, 136, "uses the cookie", {}); cap(930, 136, "uses the cookie, can't reach store", {});
cap(280, 806, "setup(wiring) is one-shot: different values are refused", {}); cap(330, 300, "storeId: rotate · revoke", {});
cap(840, 806, "the cookie rides in init.headers, fixed at mint", {}); cap(760, 806, "init.headerStore → the store's read-only facet, read at every send", {});
cap(265, 806, "shapes: keyShape \"cookie\", valueShape M.string()", {});
</script> </script>
</body></html> </body></html>
-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

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 [-1, 0], // west
] as const; ] as const;
/** where a mower is and what it has cut, as `"x,y"` cells; `heading` indexes north, east, south, west */ /** a mower on a `width` × `height` yard, starting at `at`; pushing past an
export type Yard = Readonly<{ * edge wraps to the other side (6d) */
width: number; export const makeMower = ({ width, height, at }: { width: number; height: number; at: { x: number; y: number } }) => {
height: number; let { x, y } = at;
x: number; let heading = 0;
y: number; const cut = new Set<string>();
heading: number; const cutHere = () => cut.add(`${x},${y}`);
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());
};
return { return {
start() { start() {
heading = 0; heading = 0;
@@ -55,7 +41,6 @@ export const makeMower = (yard: Yard, onMove: (yard: Yard) => void = () => {}) =
}, },
turn() { turn() {
heading = (heading + 1) % headings.length; heading = (heading + 1) % headings.length;
onMove(view());
}, },
stop() {}, stop() {},
cutCells: () => [...cut], cutCells: () => [...cut],
+5 -33
View File
@@ -1,44 +1,16 @@
/** @file The neighbor's harness as a Project Think agent, lent a mower. */ /** @file The neighbor's harness as a Project Think agent, lent a mower. */
import { Think } from "@cloudflare/think"; import { Think } from "@cloudflare/think";
import type { Connection } from "agents";
import { createExecuteTool } from "@cloudflare/think/tools/execute"; import { createExecuteTool } from "@cloudflare/think/tools/execute";
import { createWorkersAI } from "workers-ai-provider"; import { createWorkersAI } from "workers-ai-provider";
import { MAX_TOKENS, MODEL } from "./model.ts"; import { MAX_TOKENS, MODEL } from "./model.ts";
import { MowerConnector } from "./mower-connector.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 }; type Env = { AI: Ai; LOADER: WorkerLoader };
/** how often, at most, a mowing yard goes out to the page */ export class Neighbor extends Think<Env> {
const PUBLISH_MS = 200; #mower = makeMower({ width: 40, height: 40, at: { x: 20, y: 20 } });
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");
}
getModel() { getModel() {
return createWorkersAI({ binding: this.env.AI })(MODEL); 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() { getTools() {
return { return {
execute: createExecuteTool(this, { 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"` */ /** the cells the mower has cut, as `"x,y"` */
cutCells() { 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" }
}
}
+16
View File
@@ -0,0 +1,16 @@
{
"name": "capsite-lib",
"private": true,
"type": "module",
"scripts": {
"types": "wrangler types -c wrangler.tests.jsonc",
"lint": "wrangler types -c wrangler.tests.jsonc --check && tsc -p tsconfig.json && tsc -p tests/tsconfig.json",
"test": "vitest run"
},
"devDependencies": {
"@cloudflare/vitest-plugin": "1.3.6",
"typescript": "^5.9.0",
"vitest": "4.1.11",
"wrangler": "^4.148.0"
}
}
+2240
View File
File diff suppressed because it is too large. Load diff
+129
View File
@@ -0,0 +1,129 @@
/**
* @file a work-alike for enough of @endo/patterns: `M.string()`, `M.any()`,
* and literal patterns (a string, number, boolean, or null matches only
* itself, so `"cookie"` as a key shape admits exactly one key). Matchers
* are the same data endo makes: tagged records, as from @endo/pass-style's
* `makeTagged` (frozen here, where endo would harden).
*
* Structured clone (DO storage, Workers RPC) drops a tagged record's
* symbol-keyed and non-enumerable properties, so patterns cross those
* boundaries in endo's smallcaps encoding: see {@link toSmallcaps}.
* @see https://github.com/endojs/endo/tree/master/packages/patterns
* @see https://github.com/endojs/endo/blob/master/packages/marshal/src/encodeToSmallcaps.js
*/
const PASS_STYLE = Symbol.for("passStyle");
export type Tagged = Readonly<{ [Symbol.toStringTag]: string; payload: unknown }>;
export type Pattern = Tagged | string | number | boolean | null;
/** @endo/pass-style's `makeTagged` */
export function makeTagged(tag: string, payload: unknown): Tagged {
return Object.freeze(
Object.create(Object.prototype, {
[PASS_STYLE]: { value: "tagged" },
[Symbol.toStringTag]: { value: tag },
payload: { value: payload, enumerable: true },
}),
) as Tagged;
}
const isTagged = (x: unknown): x is Tagged =>
typeof x === "object" && x !== null && (x as Record<symbol, unknown>)[PASS_STYLE] === "tagged";
const StringShape = makeTagged("match:string", Object.freeze([]));
const AnyShape = makeTagged("match:any", undefined);
export const M = Object.freeze({
string: (): Tagged => StringShape,
any: (): Tagged => AnyShape,
});
export function matches(specimen: unknown, pattern: Pattern): boolean {
if (typeof pattern === "object" && pattern !== null) {
const tag = isTagged(pattern) ? pattern[Symbol.toStringTag] : undefined;
switch (tag) {
case "match:string":
return typeof specimen === "string";
case "match:any":
return true;
default:
throw new TypeError("not a pattern");
}
}
return Object.is(specimen, pattern);
}
/** the pattern as written in code, e.g. `M.string()` or `"cookie"` */
export function describe(pattern: Pattern): string {
if (typeof pattern === "object" && pattern !== null) {
return `M.${pattern[Symbol.toStringTag].replace(/^match:/, "")}()`;
}
return JSON.stringify(pattern);
}
/**
* throw unless `specimen` matches `pattern`. Unlike endo's, the message
* names the pattern and `label` but never the specimen: specimens here
* can be credentials, and messages cross RPC and land in logs.
*/
export function mustMatch(specimen: unknown, pattern: Pattern, label: string): void {
if (!matches(specimen, pattern)) {
throw new TypeError(`${label}: must match ${describe(pattern)}`);
}
}
/** a smallcaps-encoded passable, as JSON-able data */
export type Smallcaps = null | boolean | number | string | Smallcaps[] | { "#tag": string; payload: Smallcaps };
/** smallcaps quotes strings that start with one of these with `!` */
const startsSpecial = (s: string) => /^[!-\-]/.test(s);
/**
* the subset of @endo/marshal's smallcaps encoding that patterns here use:
* primitives, arrays, and tagged records (not a whole CapData: no `#`
* body prefix, no slots)
*/
export function toSmallcaps(passable: unknown): Smallcaps {
if (passable === undefined) return "#undefined";
if (passable === null || typeof passable === "boolean") return passable;
if (typeof passable === "number") {
if (Number.isNaN(passable)) return "#NaN";
if (passable === Infinity) return "#Infinity";
if (passable === -Infinity) return "#-Infinity";
return Object.is(passable, -0) ? 0 : passable;
}
if (typeof passable === "string") return startsSpecial(passable) ? `!${passable}` : passable;
if (Array.isArray(passable)) return passable.map(toSmallcaps);
if (isTagged(passable)) {
return { "#tag": toSmallcaps(passable[Symbol.toStringTag]) as string, payload: toSmallcaps(passable.payload) };
}
throw new TypeError("toSmallcaps: unsupported passable");
}
/** the inverse of {@link toSmallcaps} */
export function fromSmallcaps(encoding: Smallcaps): unknown {
if (encoding === null || typeof encoding === "boolean" || typeof encoding === "number") return encoding;
if (typeof encoding === "string") {
if (encoding.startsWith("!")) return encoding.slice(1);
switch (encoding) {
case "#undefined":
return undefined;
case "#NaN":
return NaN;
case "#Infinity":
return Infinity;
case "#-Infinity":
return -Infinity;
}
if (startsSpecial(encoding)) throw new TypeError("fromSmallcaps: unsupported special string");
return encoding;
}
if (Array.isArray(encoding)) return Object.freeze(encoding.map(fromSmallcaps));
if (typeof encoding === "object" && "#tag" in encoding) {
const { "#tag": tag, payload, ...rest } = encoding;
if (Object.keys(rest).length > 0) throw new TypeError("fromSmallcaps: extra properties on a tagged record");
return makeTagged(fromSmallcaps(tag) as string, fromSmallcaps(payload));
}
throw new TypeError("fromSmallcaps: unsupported encoding");
}
+60
View File
@@ -0,0 +1,60 @@
/**
* @file a MapStore as a Durable Object of its own, so a store can be held
* apart from whoever reads it: the DO id is the store's full authority
* (e.g. the account owner's, to rotate a credential), while a reader is
* handed only {@link MapStoreDo.readOnly}.
*/
import { DurableObject } from "cloudflare:workers";
import { fromSmallcaps, matches, toSmallcaps, type Pattern, type Smallcaps } from "./patterns.js";
import { makeMapStore, type MapStore, type ReadonlyMapStore, type StoreShapes } from "./store.js";
/** store shapes as they cross RPC and sit in storage: smallcaps-encoded
* (structured clone would strip a matcher down to its payload) */
export type EncodedShapes = { keyShape?: Smallcaps; valueShape?: Smallcaps };
export const encodeShapes = ({ keyShape, valueShape }: StoreShapes): EncodedShapes => ({
...(keyShape === undefined ? {} : { keyShape: toSmallcaps(keyShape) }),
...(valueShape === undefined ? {} : { valueShape: toSmallcaps(valueShape) }),
});
const decodeShapes = ({ keyShape, valueShape }: EncodedShapes): StoreShapes => ({
...(keyShape === undefined ? {} : { keyShape: fromSmallcaps(keyShape) as Pattern }),
...(valueShape === undefined ? {} : { valueShape: fromSmallcaps(valueShape) as Pattern }),
});
type Config = { label: string; shapes: EncodedShapes };
/** a store whose label and shapes its creator fixes, once */
export class MapStoreDo extends DurableObject {
/** one-shot: fix the label and shapes (see {@link encodeShapes}); an
* identical re-configure is a no-op */
configure(label: string, shapes: EncodedShapes): void {
const decoded = decodeShapes(shapes);
for (const shape of [decoded.keyShape, decoded.valueShape]) {
if (shape !== undefined) matches(undefined, shape); // throws on a non-pattern
}
makeMapStore(label, decoded, this.ctx.storage.kv); // throws on a bad label
const config: Config = { label, shapes: encodeShapes(decoded) };
const existing = this.ctx.storage.kv.get<Config>("config");
if (existing) {
if (JSON.stringify(existing) !== JSON.stringify(config)) {
throw new Error("already configured with a different label or shapes");
}
return;
}
this.ctx.storage.kv.put("config", config);
}
/** the store, with full authority */
store(): MapStore<unknown> {
const config = this.ctx.storage.kv.get<Config>("config");
if (!config) throw new Error("not configured: this store was never set up");
return makeMapStore(config.label, decodeShapes(config.shapes), this.ctx.storage.kv);
}
/** the store's queries alone */
readOnly(): ReadonlyMapStore<unknown> {
return this.store().readOnly();
}
}
+133
View File
@@ -0,0 +1,133 @@
/**
* @file a work-alike for enough of @agoric/store's MapStore: string keys,
* shapes checked with ./patterns.js, entries kept in a Durable Object's
* synchronous KV storage. The facets are RpcTargets (workerd's / capnweb's,
* in place of endo's `Far`), so a store or its read-only view can be
* handed out by reference.
* @see https://github.com/Agoric/agoric-sdk/tree/master/packages/store
*/
import { RpcTarget } from "cloudflare:workers";
import { M, mustMatch, type Pattern } from "./patterns.js";
/** the storage a store needs: a DO's `ctx.storage.kv`, or a stand-in */
export type Kv = Pick<SyncKvStorage, "get" | "put" | "delete" | "list">;
export type StoreShapes = { keyShape?: Pattern; valueShape?: Pattern };
/**
* Entries live under `store:<label>:<key>`, so the label also names the
* storage area (as a baggage key does for endo's durable stores): two
* stores with one label on one Kv are the same store.
*
* Error messages name the label and shapes, never keys or values.
*/
export function makeMapStore<V>(label: string, { keyShape = M.string(), valueShape = M.any() }: StoreShapes, kv: Kv) {
if (label.includes(":")) throw new TypeError("store label must not contain ':'");
const prefix = `store:${label}:`;
const core: Core<V> = {
label,
has: (key) => kv.get(prefix + key) !== undefined,
get: (key) => kv.get<V>(prefix + key),
put: (key, value) => kv.put(prefix + key, value),
delete: (key) => {
kv.delete(prefix + key);
},
entries: () => [...kv.list<V>({ prefix })].map(([k, v]): [string, V] => [k.slice(prefix.length), v]),
checkKey: (key) => mustMatch(key, keyShape, `${label}: key`),
checkValue: (value) => mustMatch(value, valueShape, `${label}: value`),
};
return new MapStore<V>(core);
}
type Core<V> = {
label: string;
has(key: string): boolean;
get(key: string): V | undefined;
put(key: string, value: V): void;
delete(key: string): void;
entries(): [string, V][];
checkKey(key: unknown): void;
checkValue(value: unknown): void;
};
/** the queries */
function reads<V>(core: Core<V>) {
return {
has: (key: string): boolean => core.has(key),
get: (key: string): V => {
const value = core.get(key);
if (value === undefined) throw new RangeError(`${core.label}: key not found`);
return value;
},
keys: (): string[] => core.entries().map(([k]) => k),
values: (): V[] => core.entries().map(([, v]) => v),
entries: (): [string, V][] => core.entries(),
getSize: (): number => core.entries().length,
};
}
/** a store's queries only: what a reader of a rotating credential holds */
export class ReadonlyMapStore<V> extends RpcTarget {
#reads: ReturnType<typeof reads<V>>;
constructor(core: Core<V>) {
super();
this.#reads = reads(core);
}
has(key: string): boolean {
return this.#reads.has(key);
}
get(key: string): V {
return this.#reads.get(key);
}
keys(): string[] {
return this.#reads.keys();
}
values(): V[] {
return this.#reads.values();
}
entries(): [string, V][] {
return this.#reads.entries();
}
getSize(): number {
return this.#reads.getSize();
}
}
/** a store's full authority: the queries plus `init`/`set`/`delete`, and
* {@link MapStore.readOnly} to hand out the queries alone */
export class MapStore<V> extends ReadonlyMapStore<V> {
#core: Core<V>;
constructor(core: Core<V>) {
super(core);
this.#core = core;
}
/** add a key that is not yet present */
init(key: string, value: V): void {
this.#core.checkKey(key);
this.#core.checkValue(value);
if (this.#core.has(key)) throw new RangeError(`${this.#core.label}: key already registered`);
this.#core.put(key, value);
}
/** replace the value of a key that is present */
set(key: string, value: V): void {
this.#core.checkKey(key);
this.#core.checkValue(value);
if (!this.#core.has(key)) throw new RangeError(`${this.#core.label}: key not found`);
this.#core.put(key, value);
}
delete(key: string): void {
if (!this.#core.has(key)) throw new RangeError(`${this.#core.label}: key not found`);
this.#core.delete(key);
}
readOnly(): ReadonlyMapStore<V> {
return new ReadonlyMapStore(this.#core);
}
}
+142
View File
@@ -0,0 +1,142 @@
import { env } from "cloudflare:workers";
import { evictDurableObject } from "cloudflare:test";
import { describe, expect, it } from "vitest";
import { M, fromSmallcaps, makeTagged, matches, mustMatch, toSmallcaps } from "../src/patterns.js";
import { encodeShapes } from "../src/store-do.js";
type TestEnv = {
STORE_DO: DurableObjectNamespace<import("./test-worker.js").StoreHost>;
MAP_STORE_DO: DurableObjectNamespace<import("../src/store-do.js").MapStoreDo>;
};
const testEnv = env as unknown as TestEnv;
const SECRET = "session=s3kr1t";
/** the message an RPC call fails with, or "" if it succeeds */
async function errorOf(call: Promise<unknown>): Promise<string> {
try {
await call;
return "";
} catch (err) {
return String(err);
}
}
describe("patterns", () => {
it("M.string() matches strings only; a literal matches only itself", () => {
expect(matches("x", M.string())).toBe(true);
expect(matches(1, M.string())).toBe(false);
expect(matches(undefined, M.any())).toBe(true);
expect(matches("cookie", "cookie")).toBe(true);
expect(matches("authorization", "cookie")).toBe(false);
});
it("matchers are endo's tagged records", () => {
const s = M.string() as unknown as Record<string | symbol, unknown>;
expect(s[Symbol.for("passStyle")]).toBe("tagged");
expect(s[Symbol.toStringTag]).toBe("match:string");
expect(Object.keys(s)).toEqual(["payload"]);
expect(s.payload).toEqual([]);
expect((M.any() as unknown as Record<string, unknown>).payload).toBeUndefined();
expect(Object.isFrozen(s)).toBe(true);
});
it("smallcaps: endo's encoding, round-tripped", () => {
expect(toSmallcaps(M.string())).toEqual({ "#tag": "match:string", payload: [] });
expect(toSmallcaps(M.any())).toEqual({ "#tag": "match:any", payload: "#undefined" });
expect(toSmallcaps("#cookie")).toBe("!#cookie");
expect(toSmallcaps([NaN, -0, Infinity])).toEqual(["#NaN", 0, "#Infinity"]);
const back = fromSmallcaps(toSmallcaps(M.string())) as Parameters<typeof matches>[1];
expect(matches("x", back)).toBe(true);
expect(matches(1, back)).toBe(false);
expect(fromSmallcaps("!#cookie")).toBe("#cookie");
expect(() => matches("x", makeTagged("match:nope", []))).toThrow("not a pattern");
});
it("mustMatch names the shape but not the specimen", () => {
expect(() => mustMatch(SECRET, "cookie", "jar: key")).toThrow('jar: key: must match "cookie"');
expect(() => mustMatch(SECRET, "cookie", "jar: key")).not.toThrow(SECRET);
});
});
describe("MapStore over RPC", () => {
const fresh = () => testEnv.STORE_DO.get(testEnv.STORE_DO.newUniqueId());
it("rotates: the admin's set is what the read-only view sees next", async () => {
const store = await fresh().cookies();
const rd = await store.readOnly();
await store.init("cookie", "session=old");
expect(await rd.get("cookie")).toBe("session=old");
await store.set("cookie", "session=new");
expect(await rd.entries()).toEqual([["cookie", "session=new"]]);
});
it("the read-only view has no write methods", async () => {
const store = await fresh().cookies();
const rd = (await store.readOnly()) as unknown as { set(k: string, v: string): Promise<void> };
expect(await errorOf(rd.set("cookie", SECRET))).not.toBe("");
expect(await store.has("cookie")).toBe(false);
});
it("the key shape admits only `cookie`; errors carry no values", async () => {
const store = await fresh().cookies();
const err = await errorOf(store.init("authorization", SECRET));
expect(err).toContain('cookie: key: must match "cookie"');
expect(err).not.toContain(SECRET);
expect(await errorOf(store.init("cookie", 42 as unknown as string))).toContain("cookie: value: must match M.string()");
});
it("init refuses a present key; set and get refuse a missing one", async () => {
const store = await fresh().cookies();
expect(await errorOf(store.set("cookie", SECRET))).toContain("cookie: key not found");
expect(await errorOf(store.get("cookie"))).toContain("cookie: key not found");
await store.init("cookie", SECRET);
const err = await errorOf(store.init("cookie", SECRET));
expect(err).toContain("cookie: key already registered");
expect(err).not.toContain(SECRET);
});
it("survives eviction: entries live in DO storage", async () => {
const stub = fresh();
{
// disposed before eviction: a live store stub holds the DO open
using store = await stub.cookies();
await store.init("cookie", "session=durable");
}
await evictDurableObject(stub);
using again = await stub.cookies();
expect(await again.get("cookie")).toBe("session=durable");
expect(await again.getSize()).toBe(1);
await again.delete("cookie");
expect(await again.keys()).toEqual([]);
});
});
describe("MapStoreDo", () => {
const COOKIE_SHAPES = encodeShapes({ keyShape: "cookie", valueShape: M.string() });
const fresh = () => testEnv.MAP_STORE_DO.get(testEnv.MAP_STORE_DO.newUniqueId());
it("keeps the shapes its creator chose, across eviction", async () => {
const stub = fresh();
await stub.configure("cookie", COOKIE_SHAPES);
await evictDurableObject(stub);
{
using store = await stub.store();
expect(await errorOf(store.init("authorization", SECRET))).toContain('cookie: key: must match "cookie"');
expect(await errorOf(store.init("cookie", 42))).toContain("cookie: value: must match M.string()");
await store.init("cookie", "session=a");
}
using rd = await stub.readOnly();
expect(await rd.entries()).toEqual([["cookie", "session=a"]]);
});
it("configures once: the same shapes again is a no-op, others are refused", async () => {
const stub = fresh();
await stub.configure("cookie", COOKIE_SHAPES);
await stub.configure("cookie", encodeShapes({ keyShape: "cookie", valueShape: M.string() }));
expect(await errorOf(stub.configure("cookie", encodeShapes({ keyShape: M.string() })))).toContain(
"already configured",
);
expect(await errorOf(fresh().store())).toContain("not configured");
});
});
+17
View File
@@ -0,0 +1,17 @@
/** @file the tests' main module: a DO that hosts stores on its own storage. */
import { DurableObject } from "cloudflare:workers";
import { M } from "../src/patterns.js";
import { makeMapStore, type MapStore } from "../src/store.js";
export { MapStoreDo } from "../src/store-do.js";
/** hosts the store from the credential-rotation sketch: one key, `cookie` */
export class StoreHost extends DurableObject {
cookies(): MapStore<string> {
return makeMapStore<string>("cookie", { keyShape: "cookie", valueShape: M.string() }, this.ctx.storage.kv);
}
}
export default {
fetch: () => new Response("store tests", { status: 404 }),
};
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"types": ["@cloudflare/vitest-plugin/types"]
},
"include": ["./**/*", "../src/**/*", "../worker-configuration.d.ts"]
}
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "preserve",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true,
"lib": ["ES2022", "ESNext.Disposable"],
"noEmit": true,
"types": []
},
"include": ["src/**/*", "worker-configuration.d.ts"]
}
+9
View File
@@ -0,0 +1,9 @@
import { defineProject } from "vitest/config";
import { cloudflareTest } from "@cloudflare/vitest-plugin";
export default defineProject({
plugins: [cloudflareTest({ wrangler: { configPath: "./wrangler.tests.jsonc" } })],
test: {
include: ["tests/**/*.test.ts"],
},
});
+17
View File
@@ -0,0 +1,17 @@
{
"$schema": "node_modules/wrangler/config-schema.json",
// a host DO for the stores under test (lib ships no worker of its own)
"name": "capsite-lib-tests",
"main": "./tests/test-worker.ts",
"compatibility_date": "2026-09-29",
"durable_objects": {
"bindings": [
{ "name": "STORE_DO", "class_name": "StoreHost" },
{ "name": "MAP_STORE_DO", "class_name": "MapStoreDo" }
]
},
"exports": {
"StoreHost": { "type": "durable-object", "storage": "sqlite" },
"MapStoreDo": { "type": "durable-object", "storage": "sqlite" }
}
}
+37 -2
View File
@@ -12,19 +12,54 @@ grows past a form or two.
- `GET /` — the mint form. Prefill via query string: `?url=…&headers=<urlencoded JSON>&msPerCall=…&title=…`; secret header keys (cookie, authorization, proxy-authorization) render **blank** — paste them at mint time; never echoed back. A dedicated `cookie` field is sugar for the `cookie` header (if the JSON also has one, they must agree). - `GET /` — the mint form. Prefill via query string: `?url=…&headers=<urlencoded JSON>&msPerCall=…&title=…`; secret header keys (cookie, authorization, proxy-authorization) render **blank** — paste them at mint time; never echoed back. A dedicated `cookie` field is sugar for the `cookie` header (if the JSON also has one, they must agree).
- `GET /form?render=1&…` — the same form for a proxying worker (diigo-cache's `/_connect`): the action is left as an `ACTION` placeholder for the proxy to point at its own relay. - `GET /form?render=1&…` — the same form for a proxying worker (diigo-cache's `/_connect`): the action is left as an `ACTION` placeholder for the proxy to point at its own relay.
- `POST /` — mint. Form-encoded (that page) or JSON `{url, headers, msPerCall}` (service-style). Responds `{id}` (and `x-webapp-id`). The id is *not* logged: possession is authority. - `POST /` — mint. Form-encoded (that page) or JSON `{url, headers, msPerCall}` (service-style). Responds `{id, storeId}` (and `x-webapp-id`, `x-webapp-store-id`). Neither id is logged: possession is authority.
- `POST /at/<id>` — drive an instance by capability: JSON `{path?, query?, method?, body?}` → the fluent chain → `{status, text}` (or `{error}`; messages carry no header/param values). - `POST /at/<id>` — drive an instance by capability: JSON `{path?, query?, method?, body?}` → the fluent chain → `{status, text}` (or `{error}`; messages carry no header/param values).
- `PUT /store/<storeId>/<key>` — set a header-store entry (JSON value body), e.g. `PUT /store/<storeId>/cookie` with `"session=…"` rotates the cookie; `DELETE` removes it. → `{ok: true}` (or `{error}`; messages carry no keys or values).
## RPC surface (same-account workers; binding `entrypoint: "WebAppFactory"`) ## RPC surface (same-account workers; binding `entrypoint: "WebAppFactory"`)
- `fetch(request)` — the HTTP surface above, over the binding - `fetch(request)` — the HTTP surface above, over the binding
- `newWebApp({url, headers?, msPerCall?})` → `{id, app}` — the fluent stub; - `newWebApp({url, headers?, msPerCall?})` → `{id, storeId, app}` — the fluent stub;
promise pipelining makes a whole `pathjoin().query().get()` chain a promise pipelining makes a whole `pathjoin().query().get()` chain a
single round trip single round trip
- `at(id)` — the fluent stub for a previously-minted instance - `at(id)` — the fluent stub for a previously-minted instance
- on a stub, `postForm(fields?, echoCookies?)` → `{status, contentType,
contentDisposition?, location?, body}`: a multipart/form-data POST.
`echoCookies` maps a form field to a cookie name; the cookie's value
(header store included) fills the field at send, so a double-submit
CSRF token goes out without the holder seeing it. Redirects are not
followed and a non-OK status is a reply, not an Error (a 3xx to a login
page is how many sites say "session expired"). `location` comes back
query-stripped; `set-cookie` never comes back. `body` is bytes: the
caller knows its charset.
- `store(storeId)` — a header store, with full authority:
`set("cookie", …)` rotates the cookie under every handle already out
## The header store: two ids, two authorities
Mint makes two things: the instance, and a header store (a `MapStoreDo`
from [the capsite lib](../lib/src/store-do.ts), shaped
`("cookie", { keyShape: "cookie", valueShape: M.string() })`). A `cookie`
header goes into the store, not the instance's `init`; the instance reads
the store's read-only view at every send.
- the **instance id** is authority to *use* the cookie: it goes to the
cache's wiring.
- the **store id** is authority to *choose* it: it stays with the account
owner, who can rotate it (log in again, `PUT`) or revoke it (`DELETE`,
or log out).
Kept apart because whoever can choose the cookie can swap in another
account's session: if the cache's id could rotate, a leaked instance id
would let Mallory fill the cache (and its public page) with her own
bookmarks, and the owner's logout would not stop it.
Instances minted before header stores keep their cookie in
`init.headers`, unchanged; they work as before and cannot rotate.
## Run ## Run
pnpm test # header store + rotation (vitest, workerd pool)
npx wrangler dev # → its own ready line (usually :8787 with the npx wrangler dev # → its own ready line (usually :8787 with the
# two-config diigo-cache run; standalone, :8788) # two-config diigo-cache run; standalone, :8788)
+16
View File
@@ -0,0 +1,16 @@
{
"name": "webapp",
"private": true,
"type": "module",
"scripts": {
"types": "wrangler types",
"lint": "wrangler types --check && tsc -p tsconfig.json && tsc -p tests/tsconfig.json",
"test": "vitest run"
},
"devDependencies": {
"@cloudflare/vitest-plugin": "1.3.6",
"typescript": "^5.9.0",
"vitest": "4.1.11",
"wrangler": "^4.148.0"
}
}
+2240
View File
File diff suppressed because it is too large. Load diff
+253 -34
View File
@@ -7,21 +7,52 @@
// DurableObjectNamespace/DurableObjectId/DurableObjectStub are ambient types // DurableObjectNamespace/DurableObjectId/DurableObjectStub are ambient types
// in worker-configuration.d.ts (not exports of "cloudflare:workers") // in worker-configuration.d.ts (not exports of "cloudflare:workers")
import { RpcTarget, DurableObject, WorkerEntrypoint } from "cloudflare:workers"; import { RpcTarget, DurableObject, WorkerEntrypoint } from "cloudflare:workers";
import { M } from "../../lib/src/patterns.js";
import { encodeShapes, MapStoreDo } from "../../lib/src/store-do.js";
export { MapStoreDo };
export type Query = Record<string, string | number>; export type Query = Record<string, string | number>;
type Headers = Record<string, string>; type Headers = Record<string, string>;
/** headers looked up at each send, e.g. a store's read-only view: whoever
* holds the store can rotate a credential under handles already out */
export type HeaderMap = { entries(): [string, unknown][] | Promise<[string, unknown][]> };
/** /**
* init for a new instance — fixed at creation. An instance is immutable * init for a new instance — fixed at creation. An instance is immutable
* authority: no re-config methods, only attenuation via the fluent chain. * authority: no re-config methods, only attenuation via the fluent chain.
* The one thing that changes under it is its header store's contents.
*/ */
export interface WebAppInit { export interface WebAppInit {
url: string; url: string;
headers?: Headers; headers?: Headers;
/** min spacing between outbound calls, ms (0 = unthrottled) */ /** min spacing between outbound calls, ms (0 = unthrottled) */
msPerCall?: number; msPerCall?: number;
/** id of a {@link MapStoreDo} whose entries are added as headers at
* each send (see {@link mintInstance}); the instance only reads it */
headerStore?: string;
} }
/**
* what {@link WebApp.postForm} hands back: the status and the response
* headers a caller needs to tell a result from a refusal, never
* `set-cookie` (a credential stays where it is) and with any query
* stripped from `location`
*/
export type Reply = {
status: number;
contentType: string;
contentDisposition?: string;
location?: string;
/** the body as sent: the caller knows its charset (some formats name
* it in their own header, not in content-type) */
body: Uint8Array;
};
/** one outbound request, redirects not followed; the DO's gate and fetch */
export type Exchange = (url: string, headers: Headers, method: "POST", body: FormData) => Promise<Response>;
/** structural type of a stub handle: chain to narrow, then fire */ /** structural type of a stub handle: chain to narrow, then fire */
export interface FluentGet { export interface FluentGet {
pathjoin(ref: string): FluentGet; pathjoin(ref: string): FluentGet;
@@ -29,8 +60,10 @@ export interface FluentGet {
withHeaders(h: Headers): FluentGet; withHeaders(h: Headers): FluentGet;
withHeader(key: string, value: string): FluentGet; withHeader(key: string, value: string): FluentGet;
cookies(cookie: string): FluentGet; cookies(cookie: string): FluentGet;
withHeaderMap(map: HeaderMap): FluentGet;
get(): Promise<string>; get(): Promise<string>;
post(body: string): Promise<string>; post(body: string): Promise<string>;
postForm(fields?: Record<string, string>, echoCookies?: Record<string, string>): Promise<Reply>;
} }
/** /**
@@ -57,17 +90,23 @@ export interface FluentGet {
export class WebApp extends RpcTarget implements FluentGet { export class WebApp extends RpcTarget implements FluentGet {
#url: string; #url: string;
#headers: Headers; #headers: Headers;
#maps: readonly HeaderMap[];
#send: (url: string, headers: Headers, method: "GET" | "POST", body?: string) => Promise<string>; #send: (url: string, headers: Headers, method: "GET" | "POST", body?: string) => Promise<string>;
#exchange: Exchange;
constructor( constructor(
url: string, url: string,
headers: Headers, headers: Headers,
maps: readonly HeaderMap[],
send: (url: string, headers: Headers, method: "GET" | "POST", body?: string) => Promise<string>, send: (url: string, headers: Headers, method: "GET" | "POST", body?: string) => Promise<string>,
exchange: Exchange,
) { ) {
super(); super();
this.#url = url; this.#url = url;
this.#headers = headers; this.#headers = headers;
this.#maps = maps;
this.#send = send; this.#send = send;
this.#exchange = exchange;
} }
/** Join a relative path, merging the base's query. /** Join a relative path, merging the base's query.
@@ -85,13 +124,13 @@ export class WebApp extends RpcTarget implements FluentGet {
throw new Error(`pathjoin: ${ref} not within ${hereNoQuery.href}`); throw new Error(`pathjoin: ${ref} not within ${hereNoQuery.href}`);
} }
const baseParams: Query = Object.fromEntries(here.searchParams); const baseParams: Query = Object.fromEntries(here.searchParams);
return new WebApp(unionQuery(there.href, baseParams), this.#headers, this.#send); return new WebApp(unionQuery(there.href, baseParams), this.#headers, this.#maps, this.#send, this.#exchange);
} }
/** Union headers, flower-style (see {@link WebApp}): a shared key with a /** Union headers, flower-style (see {@link WebApp}): a shared key with a
* different value throws; the same value is fine. */ * different value throws; the same value is fine. */
withHeaders(h: Headers): WebApp { withHeaders(h: Headers): WebApp {
return new WebApp(this.#url, unionHeaders(this.#headers, h), this.#send); return new WebApp(this.#url, unionHeaders(this.#headers, h), this.#maps, this.#send, this.#exchange);
} }
/** one key, flower-style (see {@link WebApp}) */ /** one key, flower-style (see {@link WebApp}) */
@@ -105,15 +144,72 @@ export class WebApp extends RpcTarget implements FluentGet {
/** Union params into the existing query, flower-style (see {@link WebApp}). */ /** Union params into the existing query, flower-style (see {@link WebApp}). */
query(params: Query): WebApp { query(params: Query): WebApp {
return new WebApp(unionQuery(this.#url, params), this.#headers, this.#send); return new WebApp(unionQuery(this.#url, params), this.#headers, this.#maps, this.#send, this.#exchange);
}
/** Add headers read from `map` at each send, unioned flower-style (see
* {@link WebApp}) with the rest — so a contradiction surfaces at send. */
withHeaderMap(map: HeaderMap): WebApp {
return new WebApp(this.#url, this.#headers, [...this.#maps, map], this.#send, this.#exchange);
} }
async get(): Promise<string> { async get(): Promise<string> {
return this.#send(this.#url, this.#headers, "GET"); return this.#send(this.#url, await this.#headersNow(), "GET");
} }
async post(body: string): Promise<string> { async post(body: string): Promise<string> {
return this.#send(this.#url, this.#headers, "POST", body); return this.#send(this.#url, await this.#headersNow(), "POST", body);
}
/**
* POST `fields` as multipart/form-data. `echoCookies` maps a form field
* to a cookie name: at send, that cookie's value (from the headers,
* header store included) goes in the field, so a double-submit CSRF
* token can be sent by a holder who never sees it.
*
* Unlike `get`/`post`, a non-OK status is a {@link Reply}, not an
* Error, and redirects are not followed: a 3xx to a login page is how
* many sites say "session expired".
*/
async postForm(fields: Record<string, string> = {}, echoCookies: Record<string, string> = {}): Promise<Reply> {
const headers = await this.#headersNow();
if (Object.keys(headers).some((k) => k.toLowerCase() === "content-type")) {
throw new Error("postForm: content-type is set by the form, not the headers");
}
const jar = parseCookies(
Object.entries(headers).find(([k]) => k.toLowerCase() === "cookie")?.[1] ?? "",
);
const form = new FormData();
for (const [name, value] of Object.entries(fields)) form.append(name, value);
for (const [field, cookie] of Object.entries(echoCookies)) {
// names only: values must not appear in Error messages
if (field in fields) throw new Error(`postForm: contradicts on ${field}`);
const value = jar.get(cookie);
if (value === undefined) throw new Error(`postForm: no ${cookie} cookie to echo`);
form.append(field, value);
}
const res = await this.#exchange(this.#url, headers, "POST", form);
const location = res.headers.get("location");
return {
status: res.status,
contentType: res.headers.get("content-type") ?? "",
...withDefined("contentDisposition", res.headers.get("content-disposition")),
...withDefined("location", location === null ? null : stripQuery(location, this.#url)),
body: new Uint8Array(await res.arrayBuffer()),
};
}
async #headersNow(): Promise<Headers> {
let headers = this.#headers;
for (const map of this.#maps) {
const entries = await map.entries();
for (const [key, value] of entries) {
// key name only: header values must not appear in Error messages
if (typeof value !== "string") throw new Error(`headers: ${key} is not a string`);
}
headers = unionHeaders(headers, Object.fromEntries(entries) as Headers);
}
return headers;
} }
} }
@@ -149,11 +245,16 @@ class Gate {
* storage, surviving eviction (instance memory evaporates when the DO naps; * storage, surviving eviction (instance memory evaporates when the DO naps;
* storage is where "this instance means this URL" durably lives). * storage is where "this instance means this URL" durably lives).
* *
* Its cookie, when minted by {@link mintInstance}, is not in `init` but in
* the header store, whose id goes to the account owner and not to whoever
* holds the instance id: the owner can rotate it, and the holder cannot
* swap in another account's session.
*
* @see https://developers.cloudflare.com/durable-objects/ — newUniqueId is * @see https://developers.cloudflare.com/durable-objects/ — newUniqueId is
* unforgeable (128-bit, inderivable); idFromName by contrast is ambient: * unforgeable (128-bit, inderivable); idFromName by contrast is ambient:
* any worker with the namespace binding can recompute it * any worker with the namespace binding can recompute it
*/ */
export class WebAppDo extends DurableObject<{ WEBAPP?: never }> { export class WebAppDo extends DurableObject<WebAppEnv> {
#ready?: Promise<void>; #ready?: Promise<void>;
/** one-shot configuration; a different-url re-configure is refused */ /** one-shot configuration; a different-url re-configure is refused */
@@ -207,16 +308,46 @@ export class WebAppDo extends DurableObject<{ WEBAPP?: never }> {
} }
return res.text(); return res.text();
}; };
return new WebApp(init.url, init.headers ?? {}, send); const exchange: Exchange = async (url, headers, method, body) => {
await gate.waitMyTurn();
return fetch(url, { method, headers, body, redirect: "manual" });
};
const maps = init.headerStore === undefined ? [] : [this.#readHeaderStore(init.headerStore)];
return new WebApp(init.url, init.headers ?? {}, maps, send, exchange);
}
/** a header map reading the store's read-only view, afresh at each send */
#readHeaderStore(storeId: string): HeaderMap {
const ns = this.env.MAP_STORE_DO;
const store = ns.get(ns.idFromString(storeId));
return {
async entries() {
using rd = await store.readOnly();
return await rd.entries();
},
};
} }
} }
/** split the cookie (any case of the header name) from the other headers */
function splitCookie(headers: Headers): { cookie?: string; rest: Headers } {
const rest: Headers = {};
let cookie: string | undefined;
for (const [key, value] of Object.entries(headers)) {
if (key.toLowerCase() === "cookie") cookie = value;
else rest[key] = value;
}
return { cookie, rest };
}
type WebAppEnv = {
WEBAPP_DO: DurableObjectNamespace<WebAppDo>;
MAP_STORE_DO: DurableObjectNamespace<MapStoreDo>;
};
/** the worker's whole HTTP surface (the default export and the /** the worker's whole HTTP surface (the default export and the
* WebAppFactory entrypoint share it) */ * WebAppFactory entrypoint share it) */
const defaultFetch = async ( const defaultFetch = async (request: Request, env: WebAppEnv): Promise<Response> => {
request: Request,
env: { WEBAPP_DO: DurableObjectNamespace<WebAppDo> },
): Promise<Response> => {
const url = new URL(request.url); const url = new URL(request.url);
// mint form: site-agnostic; secret headers (cookie, authorization) are // mint form: site-agnostic; secret headers (cookie, authorization) are
@@ -227,7 +358,7 @@ const defaultFetch = async (
// mint: browser form POST (form-encoded) or JSON (service-style) // mint: browser form POST (form-encoded) or JSON (service-style)
if (url.pathname === "/" && request.method === "POST") { if (url.pathname === "/" && request.method === "POST") {
return mint(request, env.WEBAPP_DO); return mint(request, env);
} }
// the mint form, renderable for a proxying worker: ?render=1 keeps the // the mint form, renderable for a proxying worker: ?render=1 keeps the
@@ -246,6 +377,14 @@ const defaultFetch = async (
return drive(await app, request); return drive(await app, request);
} }
// a header store, by its id (the owner's, not the instance's): PUT
// JSON value sets a key (e.g. rotates the cookie), DELETE removes it
const entry = url.pathname.match(/^\/store\/([A-Za-z0-9-]+)\/([^/]+)$/);
if (entry && (request.method === "PUT" || request.method === "DELETE")) {
const store = env.MAP_STORE_DO.get(env.MAP_STORE_DO.idFromString(entry[1]));
return storeEntry(store, decodeURIComponent(entry[2]), request);
}
return new Response("not found", { status: 404 }); return new Response("not found", { status: 404 });
}; };
@@ -305,10 +444,7 @@ function withCookie(init: WebAppInit, cookie: string): WebAppInit {
} }
/** mint a fresh instance from form-encoded or JSON input */ /** mint a fresh instance from form-encoded or JSON input */
async function mint( async function mint(request: Request, env: WebAppEnv): Promise<Response> {
request: Request,
ns: DurableObjectNamespace<WebAppDo>,
): Promise<Response> {
const ct = request.headers.get("content-type") ?? ""; const ct = request.headers.get("content-type") ?? "";
let init: WebAppInit; let init: WebAppInit;
try { try {
@@ -335,13 +471,35 @@ async function mint(
return Response.json({ error: "bad url" }, { status: 400 }); return Response.json({ error: "bad url" }, { status: 400 });
} }
const id = ns.newUniqueId(); const { id, storeId } = await mintInstance(env, init);
const instance = ns.get(id); // note: ids intentionally NOT logged — they are bearer capabilities
await instance.configure(init);
const app = await instance.handle();
// note: id intentionally NOT logged — it is a bearer capability
console.log({ event: "mint", msPerCall: init.msPerCall }); console.log({ event: "mint", msPerCall: init.msPerCall });
return Response.json({ id: id.toString() }, { headers: { "x-webapp-id": id.toString() } }); return Response.json({ id, storeId }, { headers: { "x-webapp-id": id, "x-webapp-store-id": storeId } });
}
/**
* a configured instance plus its header store, shaped to hold just the
* cookie: the instance id is authority to use the cookie; the store id
* (for the account owner) is authority to rotate or remove it. Any
* `cookie` header in `init` goes to the store, not to the instance.
*/
async function mintInstance(env: WebAppEnv, init: WebAppInit): Promise<{ id: string; storeId: string }> {
const { cookie, rest } = splitCookie(init.headers ?? {});
const storeId = env.MAP_STORE_DO.newUniqueId();
const store = env.MAP_STORE_DO.get(storeId);
await store.configure("cookie", encodeShapes({ keyShape: "cookie", valueShape: M.string() }));
if (cookie !== undefined) {
using full = await store.store();
await full.init("cookie", cookie);
}
const id = env.WEBAPP_DO.newUniqueId();
await env.WEBAPP_DO.get(id).configure({
url: init.url,
headers: rest,
...(init.msPerCall === undefined ? {} : { msPerCall: init.msPerCall }),
headerStore: storeId.toString(),
});
return { id: id.toString(), storeId: storeId.toString() };
} }
/** drive a handle from the /at/<id> JSON protocol (also used by the /** drive a handle from the /at/<id> JSON protocol (also used by the
@@ -368,6 +526,60 @@ async function drive(app: FluentGet, request: Request): Promise<Response> {
} }
} }
/** the /store/<id>/<key> protocol: PUT a JSON value (set, or init if
* absent), or DELETE → {ok} (or {error}; messages carry no values) */
async function storeEntry(store: DurableObjectStub<MapStoreDo>, key: string, request: Request): Promise<Response> {
let value: unknown;
if (request.method === "PUT") {
try {
value = await request.json();
} catch (err) {
return Response.json({ error: `bad input: ${String(err)}` }, { status: 400 });
}
}
try {
using full = await store.store();
if (request.method === "DELETE") {
if (await full.has(key)) await full.delete(key);
} else if (await full.has(key)) {
await full.set(key, value);
} else {
await full.init(key, value);
}
} catch (err) {
// store errors name shapes, never keys or values (see lib/src/store.ts)
return Response.json({ error: String(err) }, { status: 400 });
}
// note: neither id nor value logged
console.log({ event: "store", method: request.method });
return Response.json({ ok: true });
}
/** a cookie header's name → value (the first of a repeated name wins) */
function parseCookies(header: string): Map<string, string> {
const jar = new Map<string, string>();
for (const pair of header.split(";")) {
const eq = pair.indexOf("=");
if (eq < 0) continue;
const name = pair.slice(0, eq).trim();
if (name && !jar.has(name)) jar.set(name, pair.slice(eq + 1).trim());
}
return jar;
}
/** `ref` resolved against `base`, query and fragment dropped: they can carry credentials */
function stripQuery(ref: string, base: string): string {
const url = new URL(ref, base);
url.search = "";
url.hash = "";
return url.href;
}
/** `{[key]: value}`, or `{}` when value is null: optional fields stay absent */
function withDefined<K extends string>(key: K, value: string | null): { [P in K]?: string } {
return (value === null ? {} : { [key]: value }) as { [P in K]?: string };
}
function unionHeaders(base: Headers, more: Headers): Headers { function unionHeaders(base: Headers, more: Headers): Headers {
const merged = { ...base }; const merged = { ...base };
for (const [key, value] of Object.entries(more)) { for (const [key, value] of Object.entries(more)) {
@@ -396,37 +608,37 @@ function unionQuery(base: string, params: Query): string {
/** /**
* the RPC service of the webapp worker. Flow: * the RPC service of the webapp worker. Flow:
* *
* const { id, app } = await env.WEBAPP.newWebApp({ * const { id, storeId, app } = await env.WEBAPP.newWebApp({
* url: "https://api.github.com", headers: { authorization: `Bearer ${t}` }, * url: "https://diigo.example/", headers: { cookie: c },
* msPerCall: 250, * msPerCall: 250,
* }); * });
* // hold id (persist it, hand it to workers you trust), then e.g.: * // hold id (persist it, hand it to workers you trust), then e.g.:
* const text = await app.query({ per_page: 5 }).get(); * const text = await app.query({ per_page: 5 }).get();
* // later, from another worker (same account) holding the id: * // later, from another worker (same account) holding the id:
* const app2 = env.WEBAPP.at(id); * const app2 = env.WEBAPP.at(id);
* // the account owner, holding storeId, after logging in again:
* await (await env.WEBAPP.store(storeId)).set("cookie", c2);
*/ */
export class WebAppFactory extends WorkerEntrypoint { export class WebAppFactory extends WorkerEntrypoint {
/** the same HTTP surface as the default export, over the entrypoint /** the same HTTP surface as the default export, over the entrypoint
* (for service-binding callers that proxy pages, e.g. diigo-cache's * (for service-binding callers that proxy pages, e.g. diigo-cache's
* /_connect → this form) */ * /_connect → this form) */
async fetch(request: Request): Promise<Response> { async fetch(request: Request): Promise<Response> {
const env = this.env as { WEBAPP_DO: DurableObjectNamespace<WebAppDo> }; return defaultFetch(request, this.env);
return defaultFetch(request, env);
} }
/** mint a fresh instance: unforgeable uniqueId + configured fluent stub. /** mint a fresh instance: unforgeable uniqueId + configured fluent stub,
* The caller decides who else ever learns the id. (If the caller only * plus the id of its header store (see {@link mintInstance}). The
* caller decides who else ever learns either id. (If the caller only
* wanted the id, it must dispose() the app stub — workerd warns about * wanted the id, it must dispose() the app stub — workerd warns about
* undisposed stubs; see the `at()` alternative + `/at/<id>` route for * undisposed stubs; see the `at()` alternative + `/at/<id>` route for
* id-only flows.) */ * id-only flows.) */
async newWebApp(init: WebAppInit): Promise<{ id: string; app: FluentGet }> { async newWebApp(init: WebAppInit): Promise<{ id: string; storeId: string; app: FluentGet }> {
new URL(init.url); // fail before minting on garbage new URL(init.url); // fail before minting on garbage
const { id, storeId } = await mintInstance(this.env, init);
const ns = this.env.WEBAPP_DO; const ns = this.env.WEBAPP_DO;
const id = ns.newUniqueId(); const app = await ns.get(ns.idFromString(id)).handle();
const instance = ns.get(id); return { id, storeId, app };
await instance.configure(init);
const app = await instance.handle();
return { id: id.toString(), app };
} }
/** reconnect by a previously-obtained id */ /** reconnect by a previously-obtained id */
@@ -434,6 +646,13 @@ export class WebAppFactory extends WorkerEntrypoint {
const ns = this.env.WEBAPP_DO; const ns = this.env.WEBAPP_DO;
return ns.get(ns.idFromString(id)).handle(); return ns.get(ns.idFromString(id)).handle();
} }
/** a header store by its id, with full authority (the instance id
* reaches none: see {@link mintInstance}) */
async store(storeId: string) {
const ns = this.env.MAP_STORE_DO;
return ns.get(ns.idFromString(storeId)).store();
}
} }
function sleep(ms: number): Promise<void> { function sleep(ms: number): Promise<void> {
return new Promise((r) => setTimeout(r, ms)); return new Promise((r) => setTimeout(r, ms));
+131
View File
@@ -0,0 +1,131 @@
import { env } from "cloudflare:workers";
import { runInDurableObject } from "cloudflare:test";
import { afterEach, describe, expect, it, vi } from "vitest";
import worker, { type WebAppInit } from "../src/index.js";
type TestEnv = {
WEBAPP_DO: DurableObjectNamespace<import("../src/index.js").WebAppDo>;
MAP_STORE_DO: DurableObjectNamespace<import("../src/index.js").MapStoreDo>;
};
const testEnv = env as unknown as TestEnv;
const URL_ = "https://diigo.example/api/";
/** the cookie header of each outbound fetch */
function spyCookies(): (string | null)[] {
const seen: (string | null)[] = [];
vi.spyOn(globalThis, "fetch").mockImplementation(async (_input, init) => {
seen.push(new Headers(init?.headers).get("cookie"));
return new Response("ok");
});
return seen;
}
afterEach(() => {
vi.restoreAllMocks();
});
/** the worker's HTTP surface, as a JSON client */
const call = (path: string, method: string, body?: unknown) =>
worker.fetch(
new Request(`https://webapp.example${path}`, {
method,
body: body === undefined ? undefined : JSON.stringify(body),
headers: { "content-type": "application/json" },
}),
testEnv,
);
const mint = async (init: WebAppInit) => {
const { id, storeId } = (await (await call("/", "POST", init)).json()) as { id: string; storeId: string };
const instance = testEnv.WEBAPP_DO.get(testEnv.WEBAPP_DO.idFromString(id));
return { id, storeId, instance };
};
/** the failure of a call: its error status, or what it threw; "" if it succeeds */
async function errorOf(response: Promise<Response>): Promise<string> {
try {
const res = await response;
return res.ok ? "" : `${res.status} ${await res.text()}`;
} catch (err) {
return String(err);
}
}
/** `init` as stored */
const storedInit = (stub: DurableObjectStub) =>
runInDurableObject(stub, (_obj, state) => state.storage.kv.get<WebAppInit>("init"));
describe("cookie rotation", () => {
it("mint puts the cookie in the header store, not init; sends carry it", async () => {
const seen = spyCookies();
const { storeId, instance } = await mint({
url: URL_,
headers: { Cookie: "session=a", accept: "application/json" },
});
expect(await storedInit(instance)).toEqual({
url: URL_,
headers: { accept: "application/json" },
headerStore: storeId,
});
using app = await instance.handle();
await app.get();
expect(seen).toEqual(["session=a"]);
});
it("the store id rotates under handles already out, and revokes", async () => {
const seen = spyCookies();
const { storeId, instance } = await mint({ url: URL_, headers: { cookie: "session=a" } });
using app = await instance.handle();
await app.pathjoin("x").get();
expect(await (await call(`/store/${storeId}/cookie`, "PUT", "session=b")).json()).toEqual({ ok: true });
await app.pathjoin("x").get();
expect(await (await call(`/store/${storeId}/cookie`, "DELETE")).json()).toEqual({ ok: true });
await app.get();
expect(seen).toEqual(["session=a", "session=b", null]);
});
it("the instance id reaches no store: its holder cannot swap in another session", async () => {
const seen = spyCookies();
const { id, instance } = await mint({ url: URL_, headers: { cookie: "session=alice" } });
expect(await errorOf(call(`/store/${id}/cookie`, "PUT", "session=mallory"))).not.toBe("");
expect((await call(`/at/${id}/cookie`, "POST", { cookie: "session=mallory" })).status).toBe(404);
using app = await instance.handle();
await app.get();
expect(seen).toEqual(["session=alice"]);
});
it("the store's shapes admit only the cookie; errors carry no values", async () => {
const { storeId } = await mint({ url: URL_ });
const err = await errorOf(call(`/store/${storeId}/authorization`, "PUT", "Bearer s3kr1t"));
expect(err).toContain('cookie: key: must match \\"cookie\\"');
expect(err).not.toContain("s3kr1t");
expect(await errorOf(call(`/store/${storeId}/cookie`, "PUT", 42))).toContain("must match M.string()");
});
it("an instance minted before header stores keeps its cookie in init, untouched", async () => {
const seen = spyCookies();
const instance = testEnv.WEBAPP_DO.get(testEnv.WEBAPP_DO.newUniqueId());
const old = { url: URL_, headers: { cookie: "session=old" }, msPerCall: 0 };
await runInDurableObject(instance, (_obj, state) => state.storage.put("init", old));
using app = await instance.handle();
await app.get();
expect(seen).toEqual(["session=old"]);
expect(await storedInit(instance)).toEqual(old);
});
it("a fixed header contradicting the stored cookie fails at send, naming no values", async () => {
spyCookies();
const { instance } = await mint({ url: URL_, headers: { cookie: "session=a" } });
using app = await instance.handle();
const err = await app
.withHeader("cookie", "session=mine")
.get()
.then(
() => "",
(e: unknown) => String(e),
);
expect(err).toContain("headers: contradicts on cookie");
expect(err).not.toContain("session=");
});
});
+117
View File
@@ -0,0 +1,117 @@
import { env } from "cloudflare:workers";
import { afterEach, describe, expect, it, vi } from "vitest";
import worker, { type WebAppInit } from "../src/index.js";
type TestEnv = {
WEBAPP_DO: DurableObjectNamespace<import("../src/index.js").WebAppDo>;
MAP_STORE_DO: DurableObjectNamespace<import("../src/index.js").MapStoreDo>;
};
const testEnv = env as unknown as TestEnv;
const URL_ = "https://site.example/app/export/7/data";
type Seen = { url: string; redirect?: string; contentType: string | null; form: Record<string, string> };
/** each outbound fetch, its form fields read back; answers with `res()` */
function spyForms(res: () => Response): Seen[] {
const seen: Seen[] = [];
vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
const req = new Request(input as string, init as RequestInit);
const form = Object.fromEntries([...(await req.formData()).entries()].map(([k, v]) => [k, String(v)]));
seen.push({ url: req.url, redirect: init?.redirect, contentType: req.headers.get("content-type"), form });
return res();
});
return seen;
}
afterEach(() => {
vi.restoreAllMocks();
});
const mint = async (init: WebAppInit) => {
const res = await worker.fetch(
new Request("https://webapp.example/", {
method: "POST",
body: JSON.stringify(init),
headers: { "content-type": "application/json" },
}),
testEnv,
);
const { id, storeId } = (await res.json()) as { id: string; storeId: string };
return { id, storeId, instance: testEnv.WEBAPP_DO.get(testEnv.WEBAPP_DO.idFromString(id)) };
};
/** the failure of a call: what it threw; "" if it succeeds */
async function errorOf(p: Promise<unknown>): Promise<string> {
try {
await p;
return "";
} catch (err) {
return String(err);
}
}
describe("postForm", () => {
it("echoes a cookie from the header store into a form field; the holder never sees it", async () => {
const seen = spyForms(
() =>
new Response("col1,col2", {
headers: {
"content-type": "text/csv",
"content-disposition": 'attachment;filename="x.csv"',
"set-cookie": "sess=next; HttpOnly",
},
}),
);
const { instance } = await mint({ url: URL_, headers: { cookie: "a=1; tok=s3cret; b=2" } });
using app = await instance.handle();
const reply = await app.query({ since: "2026-07-13\x1f" }).postForm({ kind: "all" }, { csrf: "tok" });
expect(seen).toEqual([
{
url: `${URL_}?since=2026-07-13%1F`,
redirect: "manual",
contentType: expect.stringMatching(/^multipart\/form-data; boundary=/),
form: { kind: "all", csrf: "s3cret" },
},
]);
expect(reply).toEqual({
status: 200,
contentType: "text/csv",
contentDisposition: 'attachment;filename="x.csv"',
body: new TextEncoder().encode("col1,col2"),
});
});
it("does not follow a redirect: the 3xx comes back, location query-stripped", async () => {
spyForms(() => new Response(null, { status: 302, headers: { location: "/login?next=s3cret#x" } }));
const { instance } = await mint({ url: URL_, headers: { cookie: "tok=t" } });
using app = await instance.handle();
const reply = await app.postForm({}, { csrf: "tok" });
expect(reply).toEqual({ status: 302, contentType: "", location: "https://site.example/login", body: new Uint8Array() });
});
it("refuses, naming no values: a missing cookie, a field set twice, a content-type header", async () => {
spyForms(() => new Response("ok"));
const { instance } = await mint({ url: URL_, headers: { cookie: "tok=s3cret" } });
using app = await instance.handle();
expect(await errorOf(app.postForm({}, { csrf: "nope" }))).toMatch(/no nope cookie to echo/);
const twice = await errorOf(app.postForm({ csrf: "mine" }, { csrf: "tok" }));
expect(twice).toMatch(/contradicts on csrf/);
expect(twice).not.toMatch(/s3cret|mine/);
const typed = app.withHeader("content-type", "text/plain");
expect(await errorOf(typed.postForm())).toMatch(/content-type is set by the form/);
});
it("rotating the store's cookie changes what is echoed", async () => {
const seen = spyForms(() => new Response("ok"));
const { storeId, instance } = await mint({ url: URL_, headers: { cookie: "tok=one" } });
using app = await instance.handle();
await app.postForm({}, { csrf: "tok" });
await worker.fetch(
new Request(`https://webapp.example/store/${storeId}/cookie`, { method: "PUT", body: JSON.stringify("tok=two") }),
testEnv,
);
await app.postForm({}, { csrf: "tok" });
expect(seen.map((s) => s.form.csrf)).toEqual(["one", "two"]);
});
});
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"types": ["@cloudflare/vitest-plugin/types"]
},
"include": ["./**/*", "../worker-configuration.d.ts"]
}
+1
View File
@@ -7,6 +7,7 @@
"esModuleInterop": true, "esModuleInterop": true,
"verbatimModuleSyntax": true, "verbatimModuleSyntax": true,
"skipLibCheck": true, "skipLibCheck": true,
"lib": ["ES2022", "ESNext.Disposable"],
"noEmit": true, "noEmit": true,
"types": [] "types": []
}, },
+9
View File
@@ -0,0 +1,9 @@
import { defineProject } from "vitest/config";
import { cloudflareTest } from "@cloudflare/vitest-plugin";
export default defineProject({
plugins: [cloudflareTest({ wrangler: { configPath: "./wrangler.jsonc" } })],
test: {
include: ["tests/**/*.test.ts"],
},
});
+8 -2
View File
@@ -5,7 +5,13 @@
"compatibility_date": "2026-09-29", "compatibility_date": "2026-09-29",
"observability": { "enabled": true }, "observability": { "enabled": true },
"durable_objects": { "durable_objects": {
"bindings": [{ "name": "WEBAPP_DO", "class_name": "WebAppDo" }] "bindings": [
{ "name": "WEBAPP_DO", "class_name": "WebAppDo" },
{ "name": "MAP_STORE_DO", "class_name": "MapStoreDo" }
]
}, },
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["WebAppDo"] }] "migrations": [
{ "tag": "v1", "new_sqlite_classes": ["WebAppDo"] },
{ "tag": "v2", "new_sqlite_classes": ["MapStoreDo"] }
]
} }