From bb0b439c8ad3bdb9f7a5d757147345d04d378be7 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 18:47:42 -0600 Subject: [PATCH] docs(id book): cover the mail Worker and the two Worker proofs of concept (#13900) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The PM-BOOK coverage census (programme #13900) found three ID Workers with no chapter in the id book. Add them, surveyed from source: - reference/mail-worker.md (The mail Worker API): the production mail Worker `mail` in nixos/services/id-mail/worker/ — all four routes (mail.security.cab, mail.id.security.cab, id-mail.security.cab, mail-id.security.cab), the POST contract, bearer/Digest caller auth and the amd (template) / admin (free) grants, MAIL_CONFIG / CALLERS / EMAIL / LIMITER bindings and limits, the full failure-shape table, the host side (id serve --world-mail-command, the rest/worker transports, services.id-mail), and the operator vs publish/promote deployment paths, including that only the operator path acts on the retire list. - reference/worker-poc.md: id-worker-poc, the completed #2271 World Durable Object proof of concept (journal equality vs the native wasmtime host), its routes, journal schema, loader refusals and where its ideas landed. - reference/d1-journal-poc.md: id-d1-journal-poc, the local-only D1 journal fit probe — routes, entry shapes, ordinal allocation, bookmark-vs-cursor limits, and its open design threads (#5681, #5864, #5863). Registered in SUMMARY.md after The hosted Worker API (the id book has no second navigation/manifest gate; SUMMARY.md plus create-missing = false is the whole gate). Cross-linked from The hosted Worker API, The hosted edition, Running a node (new mail Worker operations section), and the Keeping this book current sync contract. Verification: mechanical audit over the book — 106 SUMMARY entries, every file listed, single H1 equal to its SUMMARY text, every internal link resolving with text equal to the target title — 0 problems. mdbook build clean with zero warnings; nix build .#id-docs green with the three new pages rendered. --- pkgs/id/book/SUMMARY.md | 3 + pkgs/id/book/concepts/hosted.md | 2 + .../development/keeping-this-book-current.md | 2 +- pkgs/id/book/operations/services.md | 4 + pkgs/id/book/reference/d1-journal-poc.md | 100 +++++++++ pkgs/id/book/reference/hosted-worker.md | 2 + pkgs/id/book/reference/mail-worker.md | 201 ++++++++++++++++++ pkgs/id/book/reference/worker-poc.md | 97 +++++++++ 8 files changed, 410 insertions(+), 1 deletion(-) create mode 100644 pkgs/id/book/reference/d1-journal-poc.md create mode 100644 pkgs/id/book/reference/mail-worker.md create mode 100644 pkgs/id/book/reference/worker-poc.md diff --git a/pkgs/id/book/SUMMARY.md b/pkgs/id/book/SUMMARY.md index f33cc7cc6b..e0ea5c4891 100644 --- a/pkgs/id/book/SUMMARY.md +++ b/pkgs/id/book/SUMMARY.md @@ -32,6 +32,9 @@ - [The web UI: pages and HTTP API](reference/web-ui.md) - [WebSocket protocols](reference/websockets.md) - [The hosted Worker API](reference/hosted-worker.md) +- [The mail Worker API](reference/mail-worker.md) +- [id-worker-poc: the World Durable Object proof of concept](reference/worker-poc.md) +- [id-d1-journal-poc: the D1 journal proof of concept](reference/d1-journal-poc.md) - [The MCP bridge](reference/mcp.md) - [Configuration and environment](reference/configuration.md) - [Data stores and schemas](reference/data-stores.md) diff --git a/pkgs/id/book/concepts/hosted.md b/pkgs/id/book/concepts/hosted.md index 91e6474f7c..9f527a24fb 100644 --- a/pkgs/id/book/concepts/hosted.md +++ b/pkgs/id/book/concepts/hosted.md @@ -70,6 +70,8 @@ Its worker (`src/worker.ts`) exposes a `WorldObject` Durable Object (binding `WO A subfolder, `d1-journal-poc/`, is a second, local-only fit probe for D1: `GET /health`, `POST /append`, `GET /snapshot`, `GET /tail`, with journal header version 1 entries `created` and `caps_granted`, a placeholder database ID, and always `--local`. Its own note records that a D1 bookmark is not a stream cursor. +Both proofs of concept have their own chapters: [id-worker-poc: the World Durable Object proof of concept](../reference/worker-poc.md) and [id-d1-journal-poc: the D1 journal proof of concept](../reference/d1-journal-poc.md). + ## Where the rest lives The design for a deployed hosted edition — provisioning and SSO binding, per-user stores, storage contracts, self-hosted tier adapters and the media plane — is carried by the design chapter hosted and serverless editions (30 records in the survey's mapping). The shipped scaffold above is the ground that design stands on, and this chapter's claim is only the scaffold's: implemented locally, gated, and not running anywhere. diff --git a/pkgs/id/book/development/keeping-this-book-current.md b/pkgs/id/book/development/keeping-this-book-current.md index e9f7f0b970..2305b92413 100644 --- a/pkgs/id/book/development/keeping-this-book-current.md +++ b/pkgs/id/book/development/keeping-this-book-current.md @@ -11,7 +11,7 @@ A book that drifts from the system is worse than no book: agents and operators s Concretely, in the same change as the code: 1. A new or changed command or flag → its reference chapter, plus [Add a command](add-a-verb.md) if the change alters the pattern that chapter teaches. -2. A new or changed MCP tool → [The MCP bridge](../reference/mcp.md). A new or changed web route → [The web UI: pages and HTTP API](../reference/web-ui.md) or [WebSocket protocols](../reference/websockets.md), whichever serves it. A new or changed hosted Worker route → [The hosted Worker API](../reference/hosted-worker.md). +2. A new or changed MCP tool → [The MCP bridge](../reference/mcp.md). A new or changed web route → [The web UI: pages and HTTP API](../reference/web-ui.md) or [WebSocket protocols](../reference/websockets.md), whichever serves it. A new or changed hosted Worker route → [The hosted Worker API](../reference/hosted-worker.md). A new or changed mail Worker route, caller grant, template, limit or binding (in `nixos/services/id-mail/worker/config.json` and its sources) → [The mail Worker API](../reference/mail-worker.md). 3. A changed default → **every** chapter that states the old default. Search the book for the value; defaults are stated in more places than you remember. 4. A new or changed config key or environment variable → [Configuration and environment](../reference/configuration.md). 5. A schema or data-format change → [Data stores and schemas](../reference/data-stores.md). A new format version is described beside the old one, never written over it: the old version's readers are still in the field during a rollout, per [Release and rollout](release-and-rollout.md). diff --git a/pkgs/id/book/operations/services.md b/pkgs/id/book/operations/services.md index 0b81030ce4..672d824c24 100644 --- a/pkgs/id/book/operations/services.md +++ b/pkgs/id/book/operations/services.md @@ -157,6 +157,10 @@ What the hosted edition would hold for a bound user, once deployed, is one `User A second package, `pkgs/id/worker-poc`, is a proof of concept that runs one example world in a Worker isolate and proves journal equality against the native wasmtime host. It is not a production path and an operator has no reason to run it outside its own tests. +## The mail Worker + +Confirmation mail has one production Worker of its own, separate from the hosted edition above: the Worker named `mail` in `nixos/services/id-mail/worker/`, reached at `https://mail.security.cab` (one of its four declared routes). On the live host, the NixOS module `services.id-mail` wires the primary instance's `--world-mail-command` to `id-cloudflare-mail` with the `worker` transport, so each confirmation message is POSTed to that Worker with the caller token, and the Worker — not the host — delivers it through its send-email binding, in template mode: only the two configured code messages, one recipient at a time, under its rate limits. Its routes, caller grants, configuration, failure shapes and publish/promote deployment are in [The mail Worker API](../reference/mail-worker.md). An operator debugging confirmation mail that never arrives should check, in order: the sink the node was started with (this section and [serve and publications](../reference/cli-serve.md)), the command's transport selection and environment, and then the Worker's response — its JSON error names the refusal, including `401` for a caller-token mismatch and `400` with error `template` when the message no longer matches a configured template. + ## Exit behaviour for operators Serve has no special exit codes of its own. The `id` binary's contract, from [The id command line](../reference/cli.md), is: diff --git a/pkgs/id/book/reference/d1-journal-poc.md b/pkgs/id/book/reference/d1-journal-poc.md new file mode 100644 index 0000000000..8d45dcf697 --- /dev/null +++ b/pkgs/id/book/reference/d1-journal-poc.md @@ -0,0 +1,100 @@ +# id-d1-journal-poc: the D1 journal proof of concept + +Source: https://github.com/developing-today/code/blob/main/pkgs/id/worker-poc/d1-journal-poc/wrangler.toml, https://github.com/developing-today/code/blob/main/pkgs/id/worker-poc/d1-journal-poc/README.md, https://github.com/developing-today/code/blob/main/pkgs/id/worker-poc/d1-journal-poc/worker.mjs, https://github.com/developing-today/code/blob/main/pkgs/id/worker-poc/d1-journal-poc/smoke.mjs + +`id-d1-journal-poc` is a **local-only fit probe, not a service and not a production path**. It is a subfolder of `pkgs/id/worker-poc/` — the package covered in [id-worker-poc: the World Durable Object proof of concept](worker-poc.md) — with its own Wrangler configuration and its own Worker name, which is why it is covered under that exact name here. [The hosted Worker API](hosted-worker.md) and [The hosted edition](../concepts/hosted.md) mention it in passing; this chapter is its full record. + +| Item | Value | +|---|---| +| Worker name | `id-d1-journal-poc` | +| Source | `pkgs/id/worker-poc/d1-journal-poc/` — entry point `worker.mjs` | +| Compatibility date | `2025-03-01` | +| Database | D1 binding `DB`, database name `id-d1-journal-poc`, database ID `00000000-0000-0000-0000-000000000001` — a **placeholder**, used only by local Wrangler with `--local` | +| Status | A completed probe with a passing local smoke. It is never deployed: its harness always supplies its own temporary persistence directory and the `--local` flag. | + +## What it was for, and what it proved + +The parent proof of concept keeps a world's journal in a Durable Object's SQLite storage. This probe asks the neighbouring storage question: does **Cloudflare D1** fit the same journal job — storing a world's journal entries as exact bytes, in a durable order, and reading a consistent snapshot and tail back across separate requests? + +What it establishes, within its stated limits: + +- Submitted newline-terminated JSONL bytes can be stored directly as a D1 BLOB and read back **byte-exact**: the smoke checks that the snapshot bytes plus a later tail are exactly the submitted JSONL bytes. +- A per-world ordinal can be allocated by the insert itself, from that world's durable tail, and returned atomically with a D1 session bookmark; a bookmark from an append, carried to a separate request in the `x-d1-bookmark` header, gives that request a consistent read. +- Reads order explicitly (`ORDER BY ordinal ASC`) rather than relying on insertion or row order. + +It is an ordinal-allocation and exact-byte fit probe. Its own README is explicit about what it does **not** establish: + +- It assumes #806's single writer per world. It is not a multi-writer conflict protocol. +- The #5863 storage contract was still open at its writing; this schema is only for this probe. +- There is no signature verification here: exact-byte storage and ordering only, nothing about the signed journal's semantics. +- Local Wrangler cannot prove regional replica routing, production `served_by_region` / `served_by_primary`, or production replica behaviour. The D1 `withSession()` sequential-consistency and bookmark behaviour it relies on is a provider contract, cited in its README from Cloudflare's D1 documentation. +- A D1 bookmark is a read-consistency token, **distinct from the stream cursor**. This probe's stream cursor is only the last returned ordinal; it is not the proposed production ordinal-plus-digest cursor. + +## The surface + +One binding, from `wrangler.toml`: + +| Binding | Value | +|---|---| +| `DB` | D1 database, database name `id-d1-journal-poc`, placeholder database ID above. | + +There are no routes, no Durable Objects, no secrets and no environment variables. The synthetic world is a constant in the source, `WORLD_ID = "d1-journal-poc-world"`; there is no world parameter. + +Routes, from `worker.mjs`: + +| Method | Path | Purpose | +|---|---|---| +| GET | `/health` | Answers the plain text `ok`. Does not touch the database or create the schema. | +| POST | `/append` | Append one journal entry (shape below). Answers `{world_id, ordinal, bookmark}`. | +| GET | `/snapshot` | Every entry for the world, in ordinal order, as one JSONL body. | +| GET | `/tail` | Entries after the `?after=` ordinal (default `0`), in ordinal order, as one JSONL body. | + +Any other method/path combination is `404 {"error":"not found"}`. + +`/snapshot` and `/tail` answer with content type `application/x-ndjson` and four headers that describe the returned range: `x-journal-first-ordinal`, `x-journal-last-ordinal`, `x-journal-entry-count` and `x-journal-stream-cursor`. On an empty result the first ordinal is `0` and the last ordinal — and the stream cursor — fall back to the requested `after` value for `/tail`, or `0` for `/snapshot`. + +## Entries and the store + +The table, created lazily on the first `/append`, `/snapshot` or `/tail`: + +```text +journal_entries ( + world_id TEXT NOT NULL, + ordinal INTEGER NOT NULL CHECK (ordinal > 0), + entry_bytes BLOB NOT NULL, + PRIMARY KEY (world_id, ordinal) +) +``` + +An append body must be exactly one entry: newline-terminated JSONL bytes, with no interior newline, decoding as one UTF-8 JSON object. Only two entry kinds are accepted, both from journal header version `1` (`JOURNAL_VERSION`): + +| Entry | Required shape | +|---|---| +| `created` | `entry.world_id` must be the synthetic world and `entry.version` must be `1`. | +| `caps_granted` | `entry.granted` must be an array of strings. | + +The append runs in a `first-primary` session: the insert computes the next ordinal as `COALESCE(MAX(ordinal), 0) + 1` for the world inside the insert statement itself, then re-queries the inserted row's ordinal under the same session and returns it with the session bookmark. That single-writer assumption (#806) is what makes the max-plus-one allocation sound here. + +Failure shapes, all JSON `{"error": ...}`: + +| Status | Cause | +|---|---| +| `400` | The body is not exactly one newline-terminated entry; the line is not valid UTF-8 JSON or not a JSON object; a `created` entry names another world or a version other than `1`; a `caps_granted` entry's `granted` is not a string array; the entry kind is neither of the two; or `after` on `/tail` is not a non-negative safe integer. Each refusal's message names its specific cause. | +| `404` | Any other method/path combination: `{"error":"not found"}`. | +| `500` | Anything else, including a D1 result the code cannot interpret — for example an append that returns no ordinal or no session bookmark, or a stored value that is not a byte array, an `ArrayBuffer` or a typed-array view when read back. The message is the thrown error's message. | + +## Running its proof + +From `pkgs/id/worker-poc/`: + +```text +node d1-journal-poc/smoke.mjs +``` + +The harness needs Node.js 22 or newer and `wrangler` on `PATH`. It starts its own local Wrangler Worker on a free ephemeral port with a unique temporary D1 persistence directory, runs the checks — one synthetic world, the version-1 `created` and `caps_granted` entries, a bookmark carried from an append to a separate request, snapshot bytes plus a later tail compared byte-for-byte against the submitted JSONL — and stops and removes both the Worker and the directory on exit. It does not use the parent package's Wrangler configuration or its Durable Object database. + +## Where its ideas landed, and what it is not + +- The probe is evidence for the serverless storage question, not a component of the answer in production form. The design thread it feeds — D1 versus Turso for the serverless edition (#5681), the D1 journal fit design and spike (#5864, from #5681), and the #5863 storage contract it names as still open — is carried in this book's research and design chapters, including [Adopt the IndexedDB request-batch profile](../research/store.md) and [Design: hosted and serverless editions](../design/hosted-editions.md). [Data stores and schemas](data-stores.md) records its journal header beside the other stores: version `1`, entries `created` and `caps_granted`, and the note that a D1 bookmark is not a stream cursor. +- Nothing references it as a dependency: the hosted Worker (`pkgs/id/hosted-worker`) uses a Durable Object's SQLite storage and R2, not D1, and no NixOS module, host configuration or workflow deploys or invokes this Worker. The placeholder database ID names no real database. +- It is not a second journal implementation to build on. A reader who needs the journal's production semantics starts from the native event store and the signed-journal design records, not from this probe's `journal_entries` table. diff --git a/pkgs/id/book/reference/hosted-worker.md b/pkgs/id/book/reference/hosted-worker.md index 49a1a6f363..124acd980e 100644 --- a/pkgs/id/book/reference/hosted-worker.md +++ b/pkgs/id/book/reference/hosted-worker.md @@ -140,6 +140,8 @@ The `d1-journal-poc/` subfolder is a second, local-only D1 fit probe. It uses a | GET | `/snapshot` | Read a snapshot. | | GET | `/tail` | Read the journal tail. Journal header version is `1`; entries include `created` and `caps_granted`. A D1 bookmark is not a stream cursor. | +The two proofs of concept have their own chapters, which carry their full surfaces and results: [id-worker-poc: the World Durable Object proof of concept](worker-poc.md) and [id-d1-journal-poc: the D1 journal proof of concept](d1-journal-poc.md). A third Worker belongs to ID but is not part of the hosted edition at all: the production mail Worker covered in [The mail Worker API](mail-worker.md). + ## Worked example Toy data: a bound user with `binding_id` written here as `BINDING_ID`, run under the local test harness, where the ceiling is `1073741824` bytes. diff --git a/pkgs/id/book/reference/mail-worker.md b/pkgs/id/book/reference/mail-worker.md new file mode 100644 index 0000000000..2cefc994bf --- /dev/null +++ b/pkgs/id/book/reference/mail-worker.md @@ -0,0 +1,201 @@ +# The mail Worker API + +Source: https://github.com/developing-today/code/blob/main/nixos/services/id-mail/worker/src/index.js, https://github.com/developing-today/code/blob/main/nixos/services/id-mail/worker/src/transports/email.js, https://github.com/developing-today/code/blob/main/nixos/services/id-mail/worker/src/limiter.js, https://github.com/developing-today/code/blob/main/nixos/services/id-mail/worker/config.json, https://github.com/developing-today/code/blob/main/nixos/services/id-mail/worker/cloudflare.config.ts, https://github.com/developing-today/code/blob/main/nixos/services/id-mail/worker/DEPLOYMENT.md, https://github.com/developing-today/code/blob/main/nixos/services/id-mail/default.nix, https://github.com/developing-today/code/blob/main/nixos/services/id-mail/cloudflare-mail.sh + +This chapter documents the ID mail Worker **as it stands**: the production mail surface for ID, in `nixos/services/id-mail/worker/`. It is a different package, with a different status, from the hosted edition in [The hosted Worker API](hosted-worker.md): that Worker is a local-only scaffold that is not deployed, while this one is the Worker the live ID node's mail wiring points at. + +| Item | Value | +|---|---| +| Worker name | `mail` (the `worker` key of `config.json`; the package name in `package.json` is also `mail`) | +| Source | `nixos/services/id-mail/worker/` — entry point `src/index.js`, one transport in `src/transports/email.js`, the rate limiter in `src/limiter.js` | +| Compatibility date | `2026-10-01` (`compatibilityDate` in `config.json`) | +| `workers.dev` | `true` (`workersDev` in `config.json`) | +| Retires | `id-mail` (the `retire` list in `config.json`; see "Deployment" below for which path acts on it) | +| Sender | `id@security.cab` (the only entry in `senders`, and the only address either caller may send from) | + +There is **no `wrangler.toml`** in this package. The configuration of record is `config.json`, consumed two ways: `cloudflare.config.ts` builds the Worker definition for the pinned `cf` CLI from it, and `deploy.mjs` generates a Wrangler configuration (`.generated/wrangler.json`) from it for the operator deploy path. A reader looking for a Wrangler file to edit will not find one; `config.json` is the file to change, and [Keeping this book current](../development/keeping-this-book-current.md) applies to it. + +## What it does, and for whom + +The Worker sends ID's address-confirmation and sign-in mail. It does not generate codes, hold accounts, or decide who may confirm an address: all of that is native ID code. The flow, end to end: + +1. The directory code in `pkgs/id/crates/id-directory/` generates a confirmation or sign-in code and builds the message with `code_mail` in `directory_view.rs`: subject `id: confirm your address` or `id: sign-in code`, body `Your code is {code}. It works for 15 minutes.` with the code substituted. Code generation, the 15-minute lifetime, and the check when a code is presented all live on that native side. +2. `id serve` hands the message to its configured mail sink. The sinks are the three in [serve and publications](cli-serve.md); the production node uses the command sink, `--world-mail-command`, which sets `ID_MAIL_TO`, `ID_MAIL_SUBJECT` and `ID_MAIL_BODY` in the child process environment (see [Configuration and environment](configuration.md)). +3. On the live host, that command is `id-cloudflare-mail`, built from `nixos/services/id-mail/cloudflare-mail.sh` by the NixOS module `nixos/services/id-mail/default.nix`. The module wires it into the primary `id` instance (port `3005`, `--world`) and supplies its environment from a sops-rendered file. +4. The script POSTs the message to this Worker (its `worker` transport; see "The host side: two transports" below). +5. The Worker authenticates the caller, checks the message against that caller's grant and — for the template-mode caller — against the configured templates, applies the rate limits, and delivers through its Cloudflare send-email binding, one send per recipient. It returns the message IDs Cloudflare issued. + +The template check is the Worker's part of the confirmation design: the production caller may only send messages whose subject matches a configured template exactly and whose body matches that template with a single six-digit code in the `{code}` position. A compromised or misbehaving caller in template mode therefore cannot send arbitrary text through this Worker; it can only send the two code messages, to one recipient at a time. + +## Routes + +`config.json` declares four routes, each attached as a custom domain by the generated configuration: + +| Route | Notes | +|---|---| +| `mail.security.cab` | The route the live host configuration uses: `nixos/hosts/default.nix` sets `services.id-mail.workerUrl = "https://mail.security.cab"`. | +| `mail.id.security.cab` | Also declared in `config.json`. | +| `id-mail.security.cab` | Also declared in `config.json`. | +| `mail-id.security.cab` | Also declared in `config.json`. | + +All four routes reach the same Worker and the same single handler: the handler does not branch on the host. There is exactly one HTTP route in the code — `POST` on any path — specified under "The request" below. The promotion workflow's health probe (see "Deployment") POSTs to each configured route and expects the unauthenticated `401` described there. + +## The request + +Implementation: `src/index.js`. The handler accepts one shape: + +```text +POST / (any path; only the method is checked) +Authorization: Bearer +Content-Type: application/json + +{"to": "ada@example.org", "subject": "id: confirm your address", "text": "Your code is 123456. It works for 15 minutes.\n"} +``` + +The toy values above are invented; the subject and body shape are the first configured template with a six-digit code. + +| Field | Shape | Rules (enforced in `src/transports/email.js` unless noted) | +|---|---|---| +| `to` | string, or array of strings | 1 to the caller's `maxRecipients` addresses. Each address must match the transport's address pattern, be at most 254 characters, and contain no line break. Rate-limit keys are the lowercased addresses. | +| `subject` | string | One line, at most 200 characters. | +| `text` | string | At most 10,000 characters. | +| `from` | string, optional | Defaults to the first address in the caller's grant. Must be one line and must be in the caller's grant `from` list, or the request is refused with `403`. | +| `transport` | string, optional | Defaults to `defaultTransport` from the configuration (`email`). Must be an enabled transport the caller is granted, or the request is refused (`400` unknown, `403` not granted). `email` is the only transport that exists. | + +The whole body is capped at 64 KiB (`MAX_BODY_BYTES` = 64 × 1024 in `src/index.js`): a body that declares or streams more than that is refused with `413` before it is buffered whole or parsed (#11331). + +On success the Worker answers `200` with `{"messageIds": [...]}` — one Cloudflare message ID per recipient, in recipient order, from `env.EMAIL.send({from, to, subject, text})`. + +## Authentication and caller grants + +Authentication is a bearer token per caller, checked against the `CALLERS` secret binding: + +- The Worker SHA-256-hashes the presented token and compares the hex digest against each caller's stored `sha256` in `CALLERS`, using a constant-time-style comparison over the digest text. The secret therefore holds digests, never the tokens themselves. +- `deploy.mjs` builds `CALLERS` at deploy time: for each caller in `config.json` it reads the token from the Bitwarden secret named by that caller's `tokenKey` and stores only its SHA-256 hex. +- A missing or unmatched token is `401 {"error":"unauthorized"}`. This response is also the deployment health signal: the promotion workflow probes each route with an unauthenticated POST and expects exactly this `401`, returned after the Worker has validated its `CALLERS` and `MAIL_CONFIG` bindings and before it touches the Durable Object or the email transport, so the probe can never send mail. + +The callers declared in `config.json`: + +| Caller | Bitwarden token name (`tokenKey`) | Mode | `from` | `maxRecipients` | +|---|---|---|---|---| +| `amd` | `cloudflare.id-mail-worker-token` | `template` | `id@security.cab` | 1 | +| `admin` | `cloudflare.id-mail-admin-token` | `free` | `id@security.cab` | 5 | + +- `template` mode (`amd`, the production node's caller): subject and body must match a configured template, as described above. +- `free` mode (`admin`): any subject and body that pass the general field checks may be sent, to up to five recipients. + +Grants are validated twice: `deploy.mjs` validates `config.json` before deploying (modes must be `template` or `free`, grant senders must be within `senders`, recipient caps must be positive integers, template mode requires templates), and the Worker re-validates the shape of both `MAIL_CONFIG` and `CALLERS` on every request, failing closed with `500` rather than acting on a with a value of the wrong shape (#6970). + +## Configuration and environment reference + +The Worker reads four bindings, declared in `cloudflare.config.ts` and mirrored in the Wrangler configuration `deploy.mjs` generates: + +| Binding | Type | Content | +|---|---|---| +| `MAIL_CONFIG` | Text (plain-text var in the generated Wrangler config) | JSON built from `config.json` by both config paths, containing exactly `defaultTransport`, `transports`, `limits` and `templates`. Caller definitions and routes are **not** in it. | +| `CALLERS` | Secret | JSON object keyed by caller name: `{sha256, transports}` per caller, where `transports` maps a transport name to its grant `{mode, from, maxRecipients}`. Set by `wrangler secret put CALLERS` on the operator deploy path; inherited from the current active version on the workflow publish path. | +| `EMAIL` | Send-email binding | `allowedSenderAddresses` is the `senders` list from `config.json`: `id@security.cab` only. | +| `LIMITER` | Durable Object namespace | The `Limiter` class exported from `src/limiter.js`, in the same Worker. Migration tag `v1`, SQLite-backed (`new_sqlite_classes = ["Limiter"]` in the generated config). | + +The `MAIL_CONFIG` values as configured today, from `config.json`: + +| Key | Value | +|---|---| +| `defaultTransport` | `email` | +| `transports` | `["email"]` | +| `limits.windowSeconds` | `60` | +| `limits.callerPerWindow` | `60` | +| `limits.recipientPerWindow` | `5` | +| `templates[0]` | subject `id: confirm your address`; body `Your code is {code}. It works for 15 minutes.` plus a trailing newline | +| `templates[1]` | subject `id: sign-in code`; body as above | + +A template matches when the subject is exactly equal and the body matches the template body with `{code}` replaced by exactly six digits (`\d{6}`) and nothing else changed. The two templates are the same two messages the native `code_mail` function builds; changing one side without the other breaks confirmation mail for the template-mode caller, in the `400 {"error":"template"}` shape below. + +## Rate limits + +Limits are enforced by the `Limiter` Durable Object, one object instance per limited key, because — as the comment in `src/limiter.js` states — the platform rate-limiting binding is per-machine and too loose for a recipient cap. Each instance keeps a fixed-window counter (`count`, `windowStart`) in its storage and sets an alarm at the end of the window that deletes the stored state, so dormant keys do not persist (#5739). + +Order matters, and is deliberate in `src/index.js`: + +1. The caller key (`caller:{name}`) is taken first, at `callerPerWindow` (60) per 60-second window. A caller denial is final: the handler returns `429` without resolving or mutating any recipient object (#5739). +2. Only then is each recipient key (`target:email:{lowercased address}`) taken, at `recipientPerWindow` (5) per window. If any recipient is over the limit, the request is refused with `429` — after the caller token has already been consumed for this window. + +## Failure shapes + +Every response is JSON of the form `{"error": ...}` except the success response. The complete set the handler and the email transport produce: + +| Status | `error` | Cause | +|---|---|---| +| `405` | `method not allowed` | Any method other than `POST`. Checked first, before configuration or authentication. | +| `500` | `worker is not configured` | `CALLERS` or `MAIL_CONFIG` missing, unparseable, or with the wrong shape (#6970). | +| `401` | `unauthorized` | No bearer token, or its digest matches no caller. | +| `413` | `body is too large` | The body declares or streams more than 64 KiB (#11331). | +| `400` | `body is not JSON` | The body does not parse as JSON. | +| `400` | `body must be a JSON object` | The JSON value is not a plain object. | +| `400` | `unknown transport` | `transport` names no enabled, implemented transport. | +| `403` | `caller may not use this transport` | The transport exists but is not in the caller's grants. | +| `400` | `to, subject, text and from must be strings` | A required field is missing or not a string (including a `to` that is neither a string nor a list of strings). | +| `400` | `to, subject and from must be one line` | A line break in the subject, the sender, or a recipient. | +| `400` | `to must have 1 to addresses` | Recipient count outside the caller's grant. | +| `400` | `to must be email addresses` | An address fails the pattern or exceeds 254 characters. | +| `400` | `subject or text is too long` | Subject over 200 or text over 10,000 characters. | +| `403` | `caller may not send from that address` | `from` is not in the caller's grant. | +| `400` | `template` | Template mode: subject/body match no configured template (including a code that is not exactly six digits). The error text is the single word `template`. | +| `500` | `caller grant is misconfigured` | A grant reaches the transport with the wrong shape despite the boundary validation. | +| `429` | `rate limited` | Caller or recipient window exhausted, in the order above. | +| `502` | the send error's `code`, or `send_failed` | The send-email binding threw; the response also carries a `message` field with the error's message. A multi-recipient send that fails part-way has already delivered to the earlier recipients; the Worker does not roll back or report which recipients succeeded. | + +There are no other routes or responses: no health endpoint, no GET surface, and no path routing — a `GET` to any route is the `405` above, and a `POST` to any path is the send handler. + +## The host side: two transports + +The Worker is one of two ways confirmation mail can leave the host. The script `id-cloudflare-mail` (source `cloudflare-mail.sh`, run by `id serve --world-mail-command` with `ID_MAIL_TO`, `ID_MAIL_SUBJECT` and `ID_MAIL_BODY` set) selects on `ID_MAIL_TRANSPORT`: + +| Transport | Path | Credentials it reads | +|---|---|---| +| `rest` | POSTs `{from, to, subject, text}` directly to the Cloudflare Email Sending REST API, `https://api.cloudflare.com/client/v4/accounts//email/sending/send`, and checks the response reports success with no permanent bounces. `from` defaults to `id@security.cab` (`ID_MAIL_FROM` overrides). | `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID` | +| `worker` | POSTs `{to, subject, text}` — no `from` — to `ID_MAIL_WORKER_URL` with the bearer token, discarding the response body; `curl -f` makes any non-success status a script failure. The Worker's grant supplies the sender. | `ID_MAIL_WORKER_URL`, `ID_MAIL_WORKER_TOKEN` | + +The NixOS module `services.id-mail` chooses between them: its `transport` option is `rest` or `worker` (default `rest`), `workerUrl` is required for `worker`, and it renders the chosen pair plus the world admin token into the sops template `id-mail.env` for the primary instance. Its secrets are `cloudflare_email_sending_token`, `cloudflare_account_id` and `id_mail_worker_token`. The live host configuration (`nixos/hosts/default.nix`) sets `transport = "worker"` and `workerUrl = "https://mail.security.cab"`, so the production node sends through this Worker, as the `amd` template-mode caller, one recipient at a time. + +## Relationship to the hosted Worker and the IdP + +- **To the IdP and directory:** the Worker is a transport, not an identity component. Accounts, codes, sessions and the confirmation decision are the native directory's (`pkgs/id/crates/id-directory/`); the Worker never sees a code except as six digits inside a template body it pattern-matches, never verifies a code, and keeps no account state — its only stored state is the `Limiter` counters. +- **To the hosted Worker:** none in code. [The hosted Worker API](hosted-worker.md) is a separate package (`pkgs/id/hosted-worker`, Worker name `id-hosted-worker`) implementing the per-user data plane of [The hosted edition](../concepts/hosted.md), local-only and undeployed. The mail Worker shares no source, bindings or routes with it, and the mail publish/promote workflows are not evidence about the hosted Worker's status — a point [Running a node: serve, worlds and the hosted edition](../operations/services.md) also makes from the operator side. +- **To the other mail sinks:** `id serve` can also write mail to an outbox directory or relay through a loopback SMTP server instead of running a command (see [serve and publications](cli-serve.md)). Those sinks bypass this Worker entirely; it exists for the host whose configured sink is the Cloudflare command. + +## Operations + +Tests: the package's `npm test` runs four Node suites — `runtime.test.mjs` (the handler contract: authentication, the failure envelopes above, template mode, the limiter ordering, the bounded body read), `deploy.test.mjs`, `upload-version.test.mjs` and `promote.test.mjs`. The workflow `id-mail-worker-tests.yml` runs them on changes to this package. + +Deployment has two distinct paths, and `DEPLOYMENT.md` in the package is the operator record for the second: + +1. **The operator command `id-mail-deploy`** (from `deploy.nix`, running `deploy.sh` → `deploy.mjs`). It validates `config.json`, generates `.generated/wrangler.json`, dry-runs the deploy, then — on a real run — retires each Worker in the `retire` list (`id-mail`) **before** deploying, because a hostname can belong to only one Worker; deploys `mail`; and sets the `CALLERS` secret from the Bitwarden tokens. `deploy.mjs` accepts exactly one optional argument, `--dry-run`; any other or duplicated argument aborts with exit `2` before any deploy work (#3281, #7855). `deploy.sh` supplies `CLOUDFLARE_ACCOUNT_ID` from sops, and `deploy.mjs` additionally needs `BWS_ACCESS_TOKEN` for the token lookups. +2. **The GitHub workflows `id-mail-worker-publish` and `id-mail-worker-promote`.** Both are manual, main-only, and default-off (a confirmation input defaults to false). Publish uploads a new version with the pinned `cf` CLI and the Workers Versions API but does **not** deploy it; it records a provenance artifact (version ID, run tag, commit SHA, the active deployment observed before upload) and fails if the active deployment changes during the upload or if the latest uploaded version is not the active one — so the new version inherits `CALLERS` from the current live version, never from an unpromoted upload. Promote takes a successful publish run ID and attempt, re-verifies the artifact, the exact version and tag, the unchanged active deployment, the inherited `CALLERS` binding descriptor and the version's bindings and settings; probes every configured route with the unauthenticated POST that must answer `401`; then creates a 100% deployment of only that version and repeats the metadata checks and probes. Neither workflow calls route/trigger operations, changes script settings, writes secrets, or retires or deletes Workers — the `retire` list is acted on only by the operator path above, which is the distinction `DEPLOYMENT.md`'s scope notes are making. + +The workflows run in the protected GitHub environment `mail-worker-production` (main branch only, independent reviewer required) and read exactly one credential there, the environment-only secret named `ID_MAIL_WORKER_CF_TOKEN_MAIL_WORKER_PRODUCTION` — a Cloudflare API token with the Individual Workers Editor permission scoped to the account and the existing `mail` Worker. They never reference the generic `CLOUDFLARE_API_TOKEN`. `DEPLOYMENT.md` records that the environment did not yet exist in the repository's environment list at its writing and that neither workflow is to be dispatched until an administrator has created and protected it; this chapter repeats that as the package's own record, not as a live check. Publishing also assumes the `mail` Worker already exists: upload is not a bootstrap operation, and the repository variable `CLOUDFLARE_ACCOUNT_ID` must be set. + +Rollback on the operator path is the path itself: `DEPLOYMENT.md` states the `id-mail-deploy` command and its rollback/fallback path are unchanged by the workflow cutover. On the workflow path, promotion is the only step that changes what serves, and it refuses to proceed against any drift from the uploaded artifact — an operator recovering from a bad promotion redeploys a known version rather than editing routes, bindings or secrets, none of which promotion touches. + +## Worked example + +Toy data: the production caller (`amd`, template mode), one recipient, the first template. + +```text +POST https://mail.security.cab/ +Authorization: Bearer +{"to": "ada@example.org", "subject": "id: confirm your address", "text": "Your code is 123456. It works for 15 minutes.\n"} +→ 200 {"messageIds": [""]} + +Same request with no Authorization header +→ 401 {"error": "unauthorized"} + +Same request, body "Your code is 12345. It works for 15 minutes.\n" (five digits) +→ 400 {"error": "template"} + +Same request, a sixth send to ada@example.org inside one minute +→ 429 {"error": "rate limited"} + +GET https://mail.security.cab/ +→ 405 {"error": "method not allowed"} +``` diff --git a/pkgs/id/book/reference/worker-poc.md b/pkgs/id/book/reference/worker-poc.md new file mode 100644 index 0000000000..fc28cf02e4 --- /dev/null +++ b/pkgs/id/book/reference/worker-poc.md @@ -0,0 +1,97 @@ +# id-worker-poc: the World Durable Object proof of concept + +Source: https://github.com/developing-today/code/blob/main/pkgs/id/worker-poc/wrangler.toml, https://github.com/developing-today/code/blob/main/pkgs/id/worker-poc/README.md, https://github.com/developing-today/code/blob/main/pkgs/id/worker-poc/src/worker.ts, https://github.com/developing-today/code/blob/main/pkgs/id/worker-poc/src/manifest.ts, https://github.com/developing-today/code/blob/main/pkgs/id/worker-poc/src/guest.ts + +`id-worker-poc` is a **completed proof of concept, not a product and not a production path**. This chapter exists so the Worker is covered by its exact name — the name in its `wrangler.toml` and in the `name` field of its `package.json` — and so its result is on the record in one place. [The hosted edition](../concepts/hosted.md) and [The hosted Worker API](hosted-worker.md) already state its status in passing; what follows is the whole of it. + +| Item | Value | +|---|---| +| Worker name | `id-worker-poc` | +| Source | `pkgs/id/worker-poc/` — entry point `src/worker.ts` | +| Compatibility date | `2024-11-01` | +| Tracking issue | #2271, from the #2057 design | +| Status | Complete: every acceptance box in its README is checked, dated 2026-11-01. Nothing in the package is deployed or run outside its own tests and harnesses. | + +## What it was for, and what it proved + +The question was narrow: can one example ID world run **unmodified** in a Cloudflare Worker isolate — workerd, one Durable Object per world, a SQLite journal — and evolve its state **identically** to the same world on the native wasmtime host (`pkgs/id/src/sandbox.rs`)? + +The answer it proved is yes, on state evolution. The harness compares per-step `(view, records, snapshot)` plus the snapshot hash over identical scripted input sequences, on two guests: + +- the counter sequence (seed 0, then three increments), and +- a tic-tac-toe sequence including an occupied-cell move, an out-of-range move, the winning move and a move after the win — final records `{"board":"XXX-O---O","plays":5,"winner":"X"}` on both hosts. + +Each sequence also runs with a forced cold start mid-sequence on both hosts, and the Durable Object harness (`compare/do-cold-start.mjs`) drives the real object under `wrangler dev`: a `/cold-start` after step 2 restores step 2 from the SQLite journal, a full `wrangler dev` restart restores it again, and step 3's snapshot hash equals the native reference hash. The README's harness summary is `compare: PASS (13 steps equal)`, `do-cold-start: PASS`. + +Two differences were registered **before** implementation, in the findings note on #2271, and equality was never claimed over them: + +- Workers have no fuel metering; the isolate host is bounded by CPU time where the native host meters fuel. +- The hosted loader refuses an unhostable manifest **up front, naming the reason**, where the native host traps at run time. + +Equality is therefore claimed on state evolution only, never on execution-budget behaviour. + +## The surface + +Bindings, from `wrangler.toml`: + +| Binding / rule | Value | +|---|---| +| `WORLD` | Durable Object namespace → class `WorldObject`. Migration tag `v1-sqlite`, `new_sqlite_classes = ["WorldObject"]`. | +| CompiledWasm rule | `type = "CompiledWasm"`, globs `**/*.wasm`, `fallthrough = true` — it compiles the prebuilt guest the entry point imports: the unmodified `pkgs/id/examples/roc-counter/counter.wasm`. | + +There are no routes, no `workers.dev` setting, no secrets, no environment variables and no other bindings in the configuration. The front-door `fetch` handler forwards every request to one `WorldObject`, selected by the `?world=` query parameter (default `default`): the object is named by that parameter's value via `idFromName`. + +The object's routes, from `src/worker.ts`: + +| Method | Path | Purpose | +|---|---|---| +| POST | `/step` | Apply one step. Body `{participant, event}`: `participant` must be a non-negative integer and `event` a non-empty string, validated before the guest is touched; a malformed body is `400` with an error naming that requirement. On success, `{step, view, records, snapshotHash}`. | +| POST | `/cold-start` | Drop the in-memory guest, so the next request restores from the journal. Answers `{cold: true, journaledStep}`. | +| GET | `/state` | `{step, view, records, snapshotHash}` for the current state; `snapshotHash` is `null` when the guest exports no snapshot. | + +Any other method/path combination is a plain-text `404` with body `not found` — and, by the order of the handler, an unmatched request still instantiates (or restores) the guest before answering, because only `/step` and `/cold-start` are matched before the guest is loaded. + +All request handling is serialised through a per-object promise chain, lazy guest initialisation is shared through one promise, and a step's update → hash → journal insert runs as one unit, so journal order always matches guest evolution order. A failure after the guest has advanced but before the journal insert commits discards the guest; the next request restores from the journal. + +## The journal and the guest + +The object's SQLite `journal` table is the source of truth, created in the constructor: + +| Column | Content | +|---|---| +| `step` | Integer primary key. | +| `participant` | The step's participant. | +| `event` | The step's event text. | +| `snapshot` | The guest snapshot bytes (BLOB) after the step. | +| `view` | The guest view after the step, as text. | +| `records` | The guest records after the step, as text, nullable. | +| `snapshot_hash` | SHA-256 hex of the snapshot. | + +The schema is unversioned — there is no schema-version constant in this package, unlike the hosted Worker's `UserDO` (see [Data stores and schemas](data-stores.md), which also lists this journal). Restoring takes the latest row's snapshot and hands it to the guest's `plaza_restore`. + +The guest driver (`src/guest.ts`, class `PlazaGuest`) drives only the `plaza_*` exports, with the native host's alloc/free and output discipline, and receives no imports. The manifest baked into `src/worker.ts` is `{name: "roc-counter", portability: "portable"}` with seed `0`. + +The hosted loader (`src/manifest.ts`) enforces the two up-front refusals, each throwing an error that names the manifest and the reason: + +- `portability=native` is not hostable in a Worker isolate; +- a declared memory (`wasm_memory_bytes`) over the hosted ceiling `HOSTED_MEMORY_CEILING_BYTES` — 64 MiB, the #2057 ceiling — is refused. + +## Running its proofs + +From the package (`package.json` scripts; Node 22 or newer for the smokes, no install needed for them): + +| Command | What it runs | +|---|---| +| `npm run smoke` | The Node smokes: `counter-smoke` (seed + three increments, per-step hashes, a guest-level cold start), `participant-clamp` (the PR #3726 clamp-not-wrap pin for participant IDs above `i32::MAX`), `post-update-failure` (a one-shot post-update view failure leaves only the successful event in the journal and in cold-start restore) and `participant-validation` (the #4074 pin: participant values the native u64 host can never produce — NaN, negative infinity, negative or fractional values — are rejected, not coerced). | +| `npm run compare` | Regenerates nothing itself: it diffs the isolate runner's per-step lines against the native reference JSONL, which is regenerated from `pkgs/id` with `WORKER_POC_REFERENCE_OUT=worker-poc/compare/native-reference.jsonl cargo test --test worker_poc_reference -- --nocapture`. | +| `npm run do-cold-start` | The Durable Object cold-start harness under `wrangler dev` described above. | +| `npm run typecheck` | `tsc --noEmit`. | +| `npm run dev` | `wrangler dev` — a local harness entry point, not a deployment. | + +## Where its ideas landed, and what it is not + +- The proof is an input to the hosted edition's design, not its implementation. The package that carries the hosted data plane forward is `pkgs/id/hosted-worker` ([The hosted Worker API](hosted-worker.md)): a different Worker (`id-hosted-worker`), a different object (`UserDO`, one per bound user), a different store (per-user key/value, blob references and a signed-object bridge store) and a local-only scaffold status of its own. No code in `worker-poc` is the hosted Worker, and the hosted Worker does not run worlds through this object's `/step` route. What carried over is the established fact the design stands on — an unmodified `plaza_*` guest evolves identically in an isolate when its journal is the source of truth — plus the loader-refusal shape (refuse up front, name the reason), which the design records treat in [Design: hosted and serverless editions](../design/hosted-editions.md). +- The world-on-Worker question it answered is the #2271 slice of [Worlds and the Roc guest runtime](../concepts/worlds.md); the native sandbox, the guest examples and the plaza ABI were explicitly unchanged by the PoC, and the native `WorldManifest` portability field was recorded in its README as a separate Rust follow-up that did not gate it. +- It is not referenced by any production configuration: no NixOS module, host configuration or workflow deploys or invokes it. Its subfolder probe, `id-d1-journal-poc`, is covered separately in [id-d1-journal-poc: the D1 journal proof of concept](d1-journal-poc.md). + +One documentation gap in the package itself: the README's layout bullet for `src/worker.ts` names `POST /step` and `POST /cold-start` but not `GET /state`, which the source's own header comment and handler both implement. The table above follows the source.