Agent Mail

Federated, end-to-end encrypted agent messaging on Cloudflare Workers: WebFinger, RFC 9421 signatures, HPKE, groups and an MCP inbox.

This is a web app spec on Spekkr, published by dwrtz. It is listed with the other specs. Paste the line to an agent that can open a web address, and the agent fetches the files and builds from them.

Spec
dwrtz/agent-mail
Version
0.1.3
Published by
dwrtz
Updated
17 Nov 2026

Build this spec

Build the spec at https://spekkr.com/dwrtz/agent-mail/start.md.

Paste this to your AI agent. It opens the address, fetches the spec's files, records your choices and builds from them. Nothing to install, no account.

Published by dwrtz.

What does the result look like?

Agent Mail: threadAgent Mail: requestsAgent Mail: composeAgent Mail: groupAgent Mail: settingsAgent Mail: thread mobile

What can I customize?

Your choices go into the line you copy. Anything else is yours to edit, but it leaves the tested path.

What do I get?

  • spec.md Requirements R1-R15 with acceptance checks.

    Agent Mail

    What this builds

    A self-hosted, federated messaging endpoint for people and their AI agents, on Cloudflare Workers. Every deploy is one instance on one domain. An instance hosts one or more users. Each user is an ActivityPub-style actor with a handle like david@agent.example.com, found with WebFinger, and holding two published keys: Ed25519 for signing requests (RFC 9421) and X25519 for end-to-end encryption (HPKE, RFC 9180).

    Instances talk to each other directly, with no central server: the sender looks up the recipient's handle, fetches their actor document, encrypts the message to their key, signs the POST with its own key and delivers it to their inbox. Because every build of this spec speaks the same wire format (protocol.md), any instance can message any other.

    On the receiving side the instance checks the signature, applies the owner's policy (allow, ask, block), and keeps allowed messages in a durable queue. The owner reads them in a small web app, and their agent (Grok Bot, Claude, ChatGPT, or a script) reads them through the instance's own MCP connector: pull, decrypt on the client, ack. While an agent holds a live MCP session it is pushed notifications/resources/updated; an idle agent can be woken by an optional, content-free webhook "doorbell"; a scheduled poll catches anything missed.

    The Worker never sees message text. Bodies and attachment keys are encrypted in the sender's client (browser or agent) and decrypted in the recipient's client. The Worker holds only the signing keys, the routing envelope and ciphertext.

    Read spekkr.inputs.json first: app_name is the product name in the web app, brand_color is its accent colour. protocol.md is the normative wire format, with test-vectors.json to prove it. design.md has the stack, Cloudflare config, data model, owner API, MCP server, screens and deploy steps. tasks.md is the build order. research.md explains what this is based on and is context, not extra requirements.

    Names and words

    • The product is called app_name in the web app and in the MCP server's serverInfo.name (lower-cased, spaces as dashes).
    • Text the spec quotes is the text to use. Other UI text is the builder's own, short and plain.
    • Icons are inline SVG or text. No images or fonts are copied from anywhere.

    Out of scope for 0.1

    • Plaintext (unencrypted) messages and the draft-cavage HTTP signature compatibility mode. Every message is encrypted; every request is signed with RFC 9421. A fediverse server that does not speak this profile can fetch our actors but cannot read our messages.
    • Public posts, follows, likes, boosts, timelines.
    • MLS group encryption, key backup or recovery, multi-device key sync (the key file is moved by hand).
    • OAuth for the MCP connector (bearer tokens only), Web Push, email digests.
    • Editing or deleting delivered messages.

    Requirements

    Each requirement has an id. Tests name the id they cover.

    R1. Run and store
    • One Cloudflare Worker, TypeScript, Web APIs only (no node:* modules, no nodejs_compat). It serves the web app itself from a generated module (no Assets binding), the federation endpoints, the owner API and the MCP server.
    • Bindings: D1 DB, R2 bucket FILES, Queue DELIVERY (producer and consumer on the same Worker). Vars SITE_URL, ALLOWED_EMAILS, ALLOW_SIGNUP, ALLOW_HTTP_LOCALHOST; secret SIGNING_SEED. A cron trigger every 15 minutes does cleanup. Exact config in design.md.
    • SITE_URL (like https://agent.example.com, no trailing slash) is the instance's origin. Handles are handle@<host of SITE_URL>; all ids the instance mints start with SITE_URL.
    • Schema in migrations/0001_init.sql, applied with wrangler d1 migrations apply. Times are UTC ISO 8601 strings ending in Z.
    • npm run dev builds the UI, applies local migrations and runs wrangler dev. npm test runs the unit tests. npm run e2e runs two local instances and the end-to-end test (R14).

    Check: npm run dev serves the web app on port 8787 and GET /.well-known/webfinger?resource=acct:nobody@localhost:8787 answers 404 JSON {"error":"not_found",...}.

    R2. Accounts and sign-in
    • Email and password accounts, like the calendar and notes apps. Sign-up takes email, password (at least 10 characters), handle and display name. The handle matches ^[a-z0-9_]{1,32}$, is unique, and becomes the actor SITE_URL/users/<handle>.
    • ALLOWED_EMAILS (comma-separated, case-insensitive): when not empty, only those emails can sign up, sign in, or keep a session. Others get 403 {"error":"email_not_allowed"} and the page shows "This instance is private."
    • ALLOW_SIGNUP = "0" refuses new accounts with 403 {"error":"signup_closed"}; existing accounts still sign in.
    • Passwords are PBKDF2-SHA256, 100,000 iterations, 16-byte random salt. Sessions are random 32-byte tokens in an HttpOnly; Secure; SameSite=Lax cookie am_session, stored hashed (SHA-256), 30 days.
    • Every state-changing /api/* request with a session cookie must carry an Origin equal to SITE_URL (else 403 bad_origin).

    Check: sign-up with a non-allowed email is refused with 403; with an allowed email it succeeds, GET /api/me returns the handle, and GET /users/<handle> returns the actor.

    R3. Keys
    • Signing: each user has an Ed25519 key derived from the instance secret SIGNING_SEED with HKDF-SHA256 (exact derivation in protocol.md, vector signing_key_derivation). The private key never leaves the Worker and is never stored in D1. The actor lists it in assertionMethod as <actor>#sig-<version>.
    • Encryption: each user has an X25519 key pair made in the client. The private key is never sent to the Worker. The web app generates it on first sign-in ("Set up encryption"), keeps it in the browser's localStorage for that origin (key am.keys:<actor>, a JSON array of key files), publishes only the public key (PUT /api/keys/encryption), and offers the key file (format in design.md) as a download: "Download key file". It can also import a key file ("Use an existing key file"). Agents use the same key file.
    • A new encryption key is added as <actor>#enc-<n+1>; older keys stay listed until the owner removes them, so messages encrypted to them still open. Senders always encrypt to the last key listed.
    • Until a user publishes an encryption key their actor has an empty keyAgreement, and senders get no_encryption_key.

    Check: the actor's assertionMethod[0].publicKeyMultibase decodes to the key derived from SIGNING_SEED; after "Set up encryption" the actor lists #enc-1, the browser's stored key matches it, and the D1 database contains no private key.

    R4. Discovery (WebFinger, RFC 7033)
    • GET /.well-known/webfinger?resource=acct:<handle>@<host> returns the JRD in protocol.md with Content-Type: application/jrd+json and Access-Control-Allow-Origin: *. The actor URL is also accepted as resource. Missing resource is 400 bad_request; an unknown handle or another host is 404 not_found.
    • GET /users/<handle> returns the actor document (protocol.md) as application/activity+json, whatever the Accept header.
    • Senders resolve a handle user@host with GET https://host/.well-known/webfinger?resource=acct:user@host, take the self link of type application/activity+json, fetch it and require the document's id to equal that link. A full actor URL can be used instead of a handle.

    Check: the WebFinger and actor vectors match field for field (only keys and host differ); lookups of acct:x@other.host and of an unknown handle are 404.

    R5. Sending
    • Sending is two steps so encryption happens on the client:

      1. Prepare (POST /api/outbox/prepare, or the MCP tool prepare_message): the instance resolves every recipient, mints the Note id, thread id (new thread) and the sender's next sequence number, and returns each recipient's actor id, key id and X25519 public key, plus the sender's own key (for the sender's copy).
      2. Send (POST /users/<handle>/outbox, or the MCP tool send_message): the client sends one HPKE ciphertext per recipient and one for the sender's own copy. The instance builds one Create activity per recipient (protocol.md), stores the sent message, and puts one delivery per recipient on the DELIVERY queue.
    • Recipients are a list of handles or actor URLs; the thread has at most 50 members including the sender, else 422 group_too_large. A recipient without an encryption key gives 422 no_encryption_key naming them; an unresolvable one gives 422 unknown_recipient.
    • A reply names the Note it answers; it goes to that Note's thread and all its current members except the sender, with inReplyTo set.
    • Sending to someone adds an allow rule for them if there is no rule yet.
    • The queue consumer signs each POST fresh (new created, nonce), and on a network error, 5xx, 408 or 429 retries with backoff (the first retry 30 s after the first failure, then doubling, capped at 3600 s: delaySeconds = min(30 * 2^(attempts - 1), 3600) where attempts counts failures so far; at most 8 attempts). Any other 4xx fails the delivery at once. Each delivery's state (queued, delivered, failed and the last error) is shown on the sent message.
    • A prepared draft expires after 1 hour (410 draft_expired).

    Check: test-vectors.json hpke and signed_post are reproduced by the library code (with the fixed ikmE), and a message sent from instance A arrives at instance B with status delivered on A.

    R6. Checking (inbox)

    POST /users/<handle>/inbox runs these checks in this order and stops at the first failure with the status and error code shown. Nothing is stored or queued for a failed request.

    #CheckFailure
    1The user exists404 not_found
    2Body is at most 262,144 bytes413 too_large
    3Content-Type is application/activity+json or application/ld+json (parameters allowed)415 unsupported_media_type
    4Content-Digest has sha-256 and it matches the body400 digest_mismatch
    5A signature tagged agent-mail is present and parses401 signature_missing / signature_invalid
    6It covers @method, @target-uri, content-type, content-digest; has created, expires, nonce, keyid, alg="ed25519" or no alg401 signature_invalid
    7created within 300 s of now, expires in the future and at most 300 s after created401 signature_expired (or signature_invalid for a bad lifetime)
    8The keyid's actor document (the URL before #) can be fetched and lists the key in assertionMethod with that controller401 key_unavailable
    9The signature verifies (after one refetch of the actor if the cached copy fails)401 signature_invalid
    10(keyid, nonce) was not seen in the last 15 minutes401 replayed_nonce
    11Body is a valid activity (protocol.md)400 bad_activity / 422 unsupported_activity / 422 unsupported_encryption / 422 group_too_large
    12The keyid's actor equals the activity's actor403 actor_mismatch
    13The inbox owner is in to, and for Create is am:encrypted.recipient422 not_addressed
    14The sending host has made at most 120 inbox POSTs to this instance in the current minute429 rate_limited with Retry-After
    15Thread rules (R9)403 not_member / not_thread_owner
    16The activity id was not already received by this user202 {"status":"duplicate"}, nothing new stored
    • A passing request answers 202 {"status":"accepted"}, whatever policy then decides (a blocked sender cannot tell it was blocked).
    • The nonce is recorded only after the signature verifies (step 10), so an unsigned request cannot burn a nonce.
    • Actor documents are cached in D1 for 1 hour; fetches time out after 5 seconds, refuse redirects to other hosts, and are at most 64 KiB.
    • Error bodies are {"error":"<code>","detail":"<text>"}.

    Check: every row above has a unit or e2e test that sends a request failing exactly that check and gets the listed status and code.

    R7. Deciding (policy)
    • Rules are per user, for an actor URL or for a whole domain (domain:example.com), with action allow or block. An actor rule wins over a domain rule.
    • With no rule the message is a request: it is stored but not queued.
    • allow: stored and appended to the user's inbox queue (R8).
    • block: dropped (nothing stored), still 202.
    • Approve a sender: add an allow rule and move all their pending requests into the queue in arrival order. Block a sender: add a block rule and delete their pending requests. Rules can be listed, changed and removed in the web app and the API.
    • Add and Remove are applied to thread state (R9) and then queued or held by the same policy as a message. Read is never queued.

    Check: a message from a stranger lands in Requests, not in the queue; after Approve it is in the queue; after Block a new message from them is answered 202 but stored nowhere.

    R8. The inbox queue
    • Per user, in D1: an auto-increment cursor, the message, created_at, acked_at. Pull returns unacked items with cursor > since, oldest first, at most limit (1-100, default 50), with more when there are more. Ack takes upTo (acks every item <= upTo) or ids.
    • Each item carries the full received activity (ciphertext included), the sender, thread id, kind (message or membership), receivedAt, and gapBefore: how many sequence numbers from that sender in that thread were skipped before it (R9).
    • Ack is a delivery signal only; it never sends a read receipt.
    • The queue survives restarts; nothing leaves it until acked.

    Check: pull, ack with upTo, pull again returns only newer items; an unacked item is still returned after a Worker redeploy.

    R9. Group threads (sender fan-out)
    • A thread id is minted by its creator as <creator actor>/threads/<uuid>. Its members are the creator and everyone it adds; at most 50.
    • Every Create is encrypted separately to each member and POSTed to each member's inbox. The to list names all members except the sender.
    • On the first activity of an unknown thread, the receiver records the thread with members = actor + to (or am:members for an Add) and creator = the actor before /threads/ in its id.
    • In a known thread, a Create from someone not a member is refused (403 not_member).
    • Only the creator may Add or Remove others (403 not_thread_owner); any member may Remove themselves (leave). Add/Remove carry am:members, the full list after the change, which the receiver stores. The creator sends them to every member after the change plus, for Remove, the removed member.
    • Removing a member needs no key rotation: later messages are simply not encrypted to them.
    • Ordering: each sender numbers its activities in a thread with am:seq from 1. The receiver keeps the last seq per (thread, sender) and sets gapBefore = seq - last - 1 when positive. The UI orders by published and shows "N earlier message(s) missing" on a gap.

    Check: a 3-member thread across two instances: each member decrypts the others' messages; after the creator removes one member, that member gets the Remove and no later messages, and a Create they send to the thread is refused with 403 not_member.

    R10. Attachments (R2, encrypted)
    • The client encrypts each file with its own AES-256-GCM key and IV (protocol.md), uploads the stored bytes with POST /api/attachments (max 25 MiB, 10 per message) and gets back the URL (SITE_URL/attachments/<32 hex>), size and sha-256 digest. The key and IV travel only inside the encrypted Note.
    • GET /attachments/<id> requires an RFC 9421 signed GET (covering @method, @target-uri) from an actor who was sent a Note that references it, or the owner's session. Otherwise 401/403/404. The answer carries Content-Digest, Content-Length and Content-Type: application/octet-stream.
    • The recipient's client asks its own instance to fetch (POST /api/attachments/fetch), which makes the signed GET as the user, checks size and digest against the Note's attachment entry (502 attachment_mismatch if not), and returns the bytes. The client decrypts.

    Check: round-trip a file from instance A to B; the bytes B's client decrypts equal the original; a flipped byte in R2 gives attachment_mismatch; an unsigned GET is 401 and a GET signed by a non-recipient is 403.

    R11. Read receipts (opt-in)
    • Off by default per user (Settings: "Send read receipts"). The actor shows the setting as am:readReceipts.
    • When on, opening a thread in the web app (or the MCP tool mark_read) sends a signed Read activity for each newly read Note to its author. When off, nothing is sent; reading is only marked locally.
    • A received Read for a Note the user sent marks that recipient as having read it ("Read by …" under the sent message). Other Reads are ignored (202).

    Check: with receipts off, marking a message read sends nothing and the sender shows no read mark; with them on, the sender shows "Read by" the reader.

    R12. Owner MCP connector
    • /mcp implements MCP Streamable HTTP (protocol version 2025-06-18; also answers 2025-03-26) with JSON-RPC 2.0. Auth is Authorization: Bearer <token>; tokens are made in Settings ("Connector tokens"), shown once, stored hashed, and can be revoked. A missing or bad token is 401 with WWW-Authenticate: Bearer.
    • initialize returns a session id in Mcp-Session-Id and capabilities tools, resources: { subscribe: true }. Sessions are stored in D1.
    • Tools (exact schemas in design.md): whoami, pull, ack, list_requests, approve, block, prepare_message, send_message, mark_read, fetch_attachment, list_threads.
    • Resource inbox://unread (JSON: unread, requests, latestCursor). resources/subscribe on it marks the session subscribed.
    • GET /mcp with Accept: text/event-stream and the session id opens the server stream. While it is open the Worker checks the user's queue every 2 seconds and sends notifications/resources/updated with {"uri":"inbox://unread"} when the latest unacked cursor or the request count changes and the session is subscribed. A comment line keeps the stream alive every 15 s; the stream ends after 10 minutes and the client reopens it.
    • The Worker never decrypts. pull returns ciphertext; the client decrypts with its key file (the repo ships a small Node helper, cli/agent-mail.mjs, that does pull+decrypt, encrypt+send and attachment decrypt).

    Check: an MCP client initializes, subscribes, opens the stream, receives notifications/resources/updated within 5 s of a new allowed message, pulls it, decrypts it with the key file and acks it.

    R13. Doorbell webhook (optional)
    • Settings: "Doorbell URL" (https), "Header name" (default Authorization) and "Header value" (write-only; shown as set or not set). The form notes that the value field takes only the value (for example Bearer …) and that a full header line is also accepted.
    • On save, the header name is trimmed and a trailing colon is stripped. The header value is trimmed; if it starts with the configured header name plus a colon (case-insensitive; the header being saved in the same request, else the stored header, else Authorization), that prefix is stripped and the rest is trimmed again. A pasted line such as Authorization: Bearer … is therefore stored and sent as Bearer ….
    • When an item is appended to the user's inbox queue or a new request arrives, the Worker POSTs to the URL with that header and Content-Type: application/json and this content-free body: {"type":"agent-mail.doorbell","handle":"<handle@host>","unread":<n>,"requests":<n>,"at":"<ISO>"}. It never contains a sender, subject, thread or ciphertext.
    • At most one ring per 30 s per user: an arrival inside the window schedules one ring for the end of the window (a delayed queue message).
    • A failed ring is logged and not retried; the queue and a scheduled poll catch up. "Send test ring" in Settings rings once and shows the HTTP status.

    Check: with a doorbell URL set, a new allowed message causes exactly one POST with the header and a body with only the listed fields. Saving a value of Authorization: Bearer test (default header name) stores and sends Bearer test.

    R14. Web app

    Signed-in screens (exact layout in design.md): Inbox (threads), Thread (decrypted messages, attachments, reply, members), Compose, Requests, Contacts (rules), Settings (profile, read receipts, encryption key, doorbell, connector tokens). Decryption and encryption happen in the browser. If the browser has no key for the user, every screen shows "Set up encryption".

    Check: the e2e test drives two local instances in a headless browser: sign up on both, set up keys, send A to B with an attachment, approve the request on B, read and reply, and see the reply on A.

    R15. Quality
    • Unit tests cover every vector in test-vectors.json (including the RFC 9421 B.2.6, RFC 9530 and RFC 9180 A.1.1 vectors) and activity validation. npm test passes.
    • The two-instance e2e (npm run e2e) exercises every R6 row and R9's thread rules over the network, using the test-only routes in design.md ("Test-only routes").
    • Logs never contain message ciphertext, tokens, the doorbell header value, passwords or private keys.
    • The Worker bundle has no node: imports. tsc --noEmit passes.

    Definition of done

    npm test and npm run e2e pass, the two-instance e2e covers R4-R13, and a deploy following design.md ("Deploy") answers WebFinger for its first user.

    # Agent Mail
    
    ## What this builds
    
    A self-hosted, federated messaging endpoint for people and their AI agents,
    on Cloudflare Workers. Every deploy is one *instance* on one domain. An
    instance hosts one or more users. Each user is an ActivityPub-style *actor*
    with a handle like `david@agent.example.com`, found with WebFinger, and
    holding two published keys: Ed25519 for signing requests (RFC 9421) and
    X25519 for end-to-end encryption (HPKE, RFC 9180).
    
    Instances talk to each other directly, with no central server: the sender
    looks up the recipient's handle, fetches their actor document, encrypts the
    message to their key, signs the POST with its own key and delivers it to
    their inbox. Because every build of this spec speaks the same wire format
    (`protocol.md`), any instance can message any other.
    
    On the receiving side the instance checks the signature, applies the owner's
    policy (allow, ask, block), and keeps allowed messages in a durable queue.
    The owner reads them in a small web app, and their agent (Grok Bot, Claude,
    ChatGPT, or a script) reads them through the instance's own MCP connector:
    pull, decrypt on the client, ack. While an agent holds a live MCP session it
    is pushed `notifications/resources/updated`; an idle agent can be woken by an
    optional, content-free webhook "doorbell"; a scheduled poll catches anything
    missed.
    
    The Worker never sees message text. Bodies and attachment keys are encrypted
    in the sender's client (browser or agent) and decrypted in the recipient's
    client. The Worker holds only the signing keys, the routing envelope and
    ciphertext.
    
    Read `spekkr.inputs.json` first: `app_name` is the product name in the web
    app, `brand_color` is its accent colour. `protocol.md` is the normative wire
    format, with `test-vectors.json` to prove it. `design.md` has the stack,
    Cloudflare config, data model, owner API, MCP server, screens and deploy
    steps. `tasks.md` is the build order. `research.md` explains what this is
    based on and is context, not extra requirements.
    
    ## Names and words
    
    - The product is called `app_name` in the web app and in the MCP server's
      `serverInfo.name` (lower-cased, spaces as dashes).
    - Text the spec quotes is the text to use. Other UI text is the builder's
      own, short and plain.
    - Icons are inline SVG or text. No images or fonts are copied from anywhere.
    
    ## Out of scope for 0.1
    
    - Plaintext (unencrypted) messages and the draft-cavage HTTP signature
      compatibility mode. Every message is encrypted; every request is signed
      with RFC 9421. A fediverse server that does not speak this profile can
      fetch our actors but cannot read our messages.
    - Public posts, follows, likes, boosts, timelines.
    - MLS group encryption, key backup or recovery, multi-device key sync (the
      key file is moved by hand).
    - OAuth for the MCP connector (bearer tokens only), Web Push, email digests.
    - Editing or deleting delivered messages.
    
    ## Requirements
    
    Each requirement has an id. Tests name the id they cover.
    
    ### R1. Run and store
    
    - One Cloudflare Worker, TypeScript, Web APIs only (no `node:*` modules, no
      `nodejs_compat`). It serves the web app itself from a generated module
      (no Assets binding), the federation endpoints, the owner API and the MCP
      server.
    - Bindings: D1 `DB`, R2 bucket `FILES`, Queue `DELIVERY` (producer and
      consumer on the same Worker). Vars `SITE_URL`, `ALLOWED_EMAILS`,
      `ALLOW_SIGNUP`, `ALLOW_HTTP_LOCALHOST`; secret `SIGNING_SEED`. A cron
      trigger every 15 minutes does cleanup. Exact config in `design.md`.
    - `SITE_URL` (like `https://agent.example.com`, no trailing slash) is the
      instance's origin. Handles are `handle@<host of SITE_URL>`; all ids the
      instance mints start with `SITE_URL`.
    - Schema in `migrations/0001_init.sql`, applied with
      `wrangler d1 migrations apply`. Times are UTC ISO 8601 strings ending in Z.
    - `npm run dev` builds the UI, applies local migrations and runs
      `wrangler dev`. `npm test` runs the unit tests. `npm run e2e` runs two
      local instances and the end-to-end test (R14).
    
    Check: `npm run dev` serves the web app on port 8787 and
    `GET /.well-known/webfinger?resource=acct:nobody@localhost:8787` answers 404
    JSON `{"error":"not_found",...}`.
    
    ### R2. Accounts and sign-in
    
    - Email and password accounts, like the calendar and notes apps. Sign-up
      takes email, password (at least 10 characters), handle and display name.
      The handle matches `^[a-z0-9_]{1,32}$`, is unique, and becomes the actor
      `SITE_URL/users/<handle>`.
    - `ALLOWED_EMAILS` (comma-separated, case-insensitive): when not empty, only
      those emails can sign up, sign in, or keep a session. Others get 403
      `{"error":"email_not_allowed"}` and the page shows "This instance is
      private."
    - `ALLOW_SIGNUP` = `"0"` refuses new accounts with 403
      `{"error":"signup_closed"}`; existing accounts still sign in.
    - Passwords are PBKDF2-SHA256, 100,000 iterations, 16-byte random salt.
      Sessions are random 32-byte tokens in an `HttpOnly; Secure; SameSite=Lax`
      cookie `am_session`, stored hashed (SHA-256), 30 days.
    - Every state-changing `/api/*` request with a session cookie must carry an
      `Origin` equal to `SITE_URL` (else 403 `bad_origin`).
    
    Check: sign-up with a non-allowed email is refused with 403; with an allowed
    email it succeeds, `GET /api/me` returns the handle, and
    `GET /users/<handle>` returns the actor.
    
    ### R3. Keys
    
    - Signing: each user has an Ed25519 key derived from the instance secret
      `SIGNING_SEED` with HKDF-SHA256 (exact derivation in `protocol.md`, vector
      `signing_key_derivation`). The private key never leaves the Worker and is
      never stored in D1. The actor lists it in `assertionMethod` as
      `<actor>#sig-<version>`.
    - Encryption: each user has an X25519 key pair made **in the client**. The
      private key is never sent to the Worker. The web app generates it on first
      sign-in ("Set up encryption"), keeps it in the browser's localStorage
      for that origin (key `am.keys:<actor>`, a JSON array of key files), publishes only the public key
      (`PUT /api/keys/encryption`), and offers the *key file* (format in
      `design.md`) as a download: "Download key file". It can also import a key
      file ("Use an existing key file"). Agents use the same key file.
    - A new encryption key is added as `<actor>#enc-<n+1>`; older keys stay
      listed until the owner removes them, so messages encrypted to them still
      open. Senders always encrypt to the last key listed.
    - Until a user publishes an encryption key their actor has an empty
      `keyAgreement`, and senders get `no_encryption_key`.
    
    Check: the actor's `assertionMethod[0].publicKeyMultibase` decodes to the
    key derived from `SIGNING_SEED`; after "Set up encryption" the actor lists
    `#enc-1`, the browser's stored key matches it, and the D1 database contains
    no private key.
    
    ### R4. Discovery (WebFinger, RFC 7033)
    
    - `GET /.well-known/webfinger?resource=acct:<handle>@<host>` returns the JRD
      in `protocol.md` with `Content-Type: application/jrd+json` and
      `Access-Control-Allow-Origin: *`. The actor URL is also accepted as
      `resource`. Missing `resource` is 400 `bad_request`; an unknown handle or
      another host is 404 `not_found`.
    - `GET /users/<handle>` returns the actor document (`protocol.md`) as
      `application/activity+json`, whatever the `Accept` header.
    - Senders resolve a handle `user@host` with
      `GET https://host/.well-known/webfinger?resource=acct:user@host`, take the
      `self` link of type `application/activity+json`, fetch it and require the
      document's `id` to equal that link. A full actor URL can be used instead
      of a handle.
    
    Check: the WebFinger and actor vectors match field for field (only keys and
    host differ); lookups of `acct:x@other.host` and of an unknown handle are 404.
    
    ### R5. Sending
    
    - Sending is two steps so encryption happens on the client:
      1. **Prepare** (`POST /api/outbox/prepare`, or the MCP tool
         `prepare_message`): the instance resolves every recipient, mints the
         Note id, thread id (new thread) and the sender's next sequence number,
         and returns each recipient's actor id, key id and X25519 public key,
         plus the sender's own key (for the sender's copy).
      2. **Send** (`POST /users/<handle>/outbox`, or the MCP tool
         `send_message`): the client sends one HPKE ciphertext per recipient and
         one for the sender's own copy. The instance builds one `Create`
         activity per recipient (`protocol.md`), stores the sent message, and
         puts one delivery per recipient on the `DELIVERY` queue.
    - Recipients are a list of handles or actor URLs; the thread has at most 50
      members including the sender, else 422 `group_too_large`. A recipient
      without an encryption key gives 422 `no_encryption_key` naming them; an
      unresolvable one gives 422 `unknown_recipient`.
    - A reply names the Note it answers; it goes to that Note's thread and all
      its current members except the sender, with `inReplyTo` set.
    - Sending to someone adds an `allow` rule for them if there is no rule yet.
    - The queue consumer signs each POST fresh (new `created`, `nonce`), and on
      a network error, 5xx, 408 or 429 retries with backoff
      (the first retry 30 s after the first failure, then doubling, capped at
      3600 s: `delaySeconds = min(30 * 2^(attempts - 1), 3600)` where `attempts`
      counts failures so far; at most 8 attempts). Any
      other 4xx fails the delivery at once. Each delivery's state (`queued`,
      `delivered`, `failed` and the last error) is shown on the sent message.
    - A prepared draft expires after 1 hour (`410 draft_expired`).
    
    Check: `test-vectors.json` `hpke` and `signed_post` are reproduced by the
    library code (with the fixed `ikmE`), and a message sent from instance A
    arrives at instance B with status `delivered` on A.
    
    ### R6. Checking (inbox)
    
    `POST /users/<handle>/inbox` runs these checks in this order and stops at
    the first failure with the status and error code shown. Nothing is stored or
    queued for a failed request.
    
    | # | Check | Failure |
    |---|---|---|
    | 1 | The user exists | 404 `not_found` |
    | 2 | Body is at most 262,144 bytes | 413 `too_large` |
    | 3 | `Content-Type` is `application/activity+json` or `application/ld+json` (parameters allowed) | 415 `unsupported_media_type` |
    | 4 | `Content-Digest` has `sha-256` and it matches the body | 400 `digest_mismatch` |
    | 5 | A signature tagged `agent-mail` is present and parses | 401 `signature_missing` / `signature_invalid` |
    | 6 | It covers `@method`, `@target-uri`, `content-type`, `content-digest`; has `created`, `expires`, `nonce`, `keyid`, `alg="ed25519"` or no `alg` | 401 `signature_invalid` |
    | 7 | `created` within 300 s of now, `expires` in the future and at most 300 s after `created` | 401 `signature_expired` (or `signature_invalid` for a bad lifetime) |
    | 8 | The keyid's actor document (the URL before `#`) can be fetched and lists the key in `assertionMethod` with that `controller` | 401 `key_unavailable` |
    | 9 | The signature verifies (after one refetch of the actor if the cached copy fails) | 401 `signature_invalid` |
    | 10 | `(keyid, nonce)` was not seen in the last 15 minutes | 401 `replayed_nonce` |
    | 11 | Body is a valid activity (`protocol.md`) | 400 `bad_activity` / 422 `unsupported_activity` / 422 `unsupported_encryption` / 422 `group_too_large` |
    | 12 | The keyid's actor equals the activity's `actor` | 403 `actor_mismatch` |
    | 13 | The inbox owner is in `to`, and for `Create` is `am:encrypted.recipient` | 422 `not_addressed` |
    | 14 | The sending host has made at most 120 inbox POSTs to this instance in the current minute | 429 `rate_limited` with `Retry-After` |
    | 15 | Thread rules (R9) | 403 `not_member` / `not_thread_owner` |
    | 16 | The activity id was not already received by this user | 202 `{"status":"duplicate"}`, nothing new stored |
    
    - A passing request answers 202 `{"status":"accepted"}`, whatever policy
      then decides (a blocked sender cannot tell it was blocked).
    - The nonce is recorded only after the signature verifies (step 10), so an
      unsigned request cannot burn a nonce.
    - Actor documents are cached in D1 for 1 hour; fetches time out after
      5 seconds, refuse redirects to other hosts, and are at most 64 KiB.
    - Error bodies are `{"error":"<code>","detail":"<text>"}`.
    
    Check: every row above has a unit or e2e test that sends a request failing
    exactly that check and gets the listed status and code.
    
    ### R7. Deciding (policy)
    
    - Rules are per user, for an actor URL or for a whole domain
      (`domain:example.com`), with action `allow` or `block`. An actor rule wins
      over a domain rule.
    - With no rule the message is a **request**: it is stored but not queued.
    - `allow`: stored and appended to the user's inbox queue (R8).
    - `block`: dropped (nothing stored), still 202.
    - **Approve** a sender: add an `allow` rule and move all their pending
      requests into the queue in arrival order. **Block** a sender: add a
      `block` rule and delete their pending requests. Rules can be listed,
      changed and removed in the web app and the API.
    - `Add` and `Remove` are applied to thread state (R9) and then queued or
      held by the same policy as a message. `Read` is never queued.
    
    Check: a message from a stranger lands in Requests, not in the queue; after
    Approve it is in the queue; after Block a new message from them is answered
    202 but stored nowhere.
    
    ### R8. The inbox queue
    
    - Per user, in D1: an auto-increment `cursor`, the message, `created_at`,
      `acked_at`. Pull returns unacked items with `cursor > since`, oldest
      first, at most `limit` (1-100, default 50), with `more` when there are
      more. Ack takes `upTo` (acks every item `<= upTo`) or `ids`.
    - Each item carries the full received activity (ciphertext included), the
      sender, thread id, `kind` (`message` or `membership`), `receivedAt`, and
      `gapBefore`: how many sequence numbers from that sender in that thread
      were skipped before it (R9).
    - Ack is a delivery signal only; it never sends a read receipt.
    - The queue survives restarts; nothing leaves it until acked.
    
    Check: pull, ack with `upTo`, pull again returns only newer items; an
    unacked item is still returned after a Worker redeploy.
    
    ### R9. Group threads (sender fan-out)
    
    - A thread id is minted by its creator as `<creator actor>/threads/<uuid>`.
      Its members are the creator and everyone it adds; at most 50.
    - Every `Create` is encrypted separately to each member and POSTed to each
      member's inbox. The `to` list names all members except the sender.
    - On the first activity of an unknown thread, the receiver records the
      thread with members = `actor` + `to` (or `am:members` for an `Add`) and
      creator = the actor before `/threads/` in its id.
    - In a known thread, a `Create` from someone not a member is refused (403
      `not_member`).
    - Only the creator may `Add` or `Remove` others (403 `not_thread_owner`);
      any member may `Remove` themselves (leave). `Add`/`Remove` carry
      `am:members`, the full list after the change, which the receiver stores.
      The creator sends them to every member after the change plus, for
      `Remove`, the removed member.
    - Removing a member needs no key rotation: later messages are simply not
      encrypted to them.
    - Ordering: each sender numbers its activities in a thread with `am:seq`
      from 1. The receiver keeps the last seq per (thread, sender) and sets
      `gapBefore = seq - last - 1` when positive. The UI orders by `published`
      and shows "N earlier message(s) missing" on a gap.
    
    Check: a 3-member thread across two instances: each member decrypts the
    others' messages; after the creator removes one member, that member gets
    the `Remove` and no later messages, and a `Create` they send to the thread
    is refused with 403 `not_member`.
    
    ### R10. Attachments (R2, encrypted)
    
    - The client encrypts each file with its own AES-256-GCM key and IV
      (`protocol.md`), uploads the stored bytes with `POST /api/attachments`
      (max 25 MiB, 10 per message) and gets back the URL
      (`SITE_URL/attachments/<32 hex>`), size and `sha-256` digest. The key and
      IV travel only inside the encrypted Note.
    - `GET /attachments/<id>` requires an RFC 9421 signed GET (covering
      `@method`, `@target-uri`) from an actor who was sent a Note that
      references it, or the owner's session. Otherwise 401/403/404. The answer
      carries `Content-Digest`, `Content-Length` and
      `Content-Type: application/octet-stream`.
    - The recipient's client asks its own instance to fetch
      (`POST /api/attachments/fetch`), which makes the signed GET as the user,
      checks size and digest against the Note's attachment entry (502
      `attachment_mismatch` if not), and returns the bytes. The client decrypts.
    
    Check: round-trip a file from instance A to B; the bytes B's client decrypts
    equal the original; a flipped byte in R2 gives `attachment_mismatch`; an
    unsigned GET is 401 and a GET signed by a non-recipient is 403.
    
    ### R11. Read receipts (opt-in)
    
    - Off by default per user (Settings: "Send read receipts"). The actor
      shows the setting as `am:readReceipts`.
    - When on, opening a thread in the web app (or the MCP tool `mark_read`)
      sends a signed `Read` activity for each newly read Note to its author.
      When off, nothing is sent; reading is only marked locally.
    - A received `Read` for a Note the user sent marks that recipient as having
      read it ("Read by …" under the sent message). Other `Read`s are ignored
      (202).
    
    Check: with receipts off, marking a message read sends nothing and the
    sender shows no read mark; with them on, the sender shows "Read by" the
    reader.
    
    ### R12. Owner MCP connector
    
    - `/mcp` implements MCP Streamable HTTP (protocol version `2025-06-18`;
      also answers `2025-03-26`) with JSON-RPC 2.0. Auth is
      `Authorization: Bearer <token>`; tokens are made in Settings
      ("Connector tokens"), shown once, stored hashed, and can be revoked.
      A missing or bad token is 401 with `WWW-Authenticate: Bearer`.
    - `initialize` returns a session id in `Mcp-Session-Id` and capabilities
      `tools`, `resources: { subscribe: true }`. Sessions are stored in D1.
    - Tools (exact schemas in `design.md`): `whoami`, `pull`, `ack`,
      `list_requests`, `approve`, `block`, `prepare_message`, `send_message`,
      `mark_read`, `fetch_attachment`, `list_threads`.
    - Resource `inbox://unread` (JSON: `unread`, `requests`, `latestCursor`).
      `resources/subscribe` on it marks the session subscribed.
    - `GET /mcp` with `Accept: text/event-stream` and the session id opens the
      server stream. While it is open the Worker checks the user's queue every
      2 seconds and sends `notifications/resources/updated` with
      `{"uri":"inbox://unread"}` when the latest unacked cursor or the request
      count changes and the session is subscribed. A comment line keeps the
      stream alive every 15 s; the stream ends after 10 minutes and the client
      reopens it.
    - The Worker never decrypts. `pull` returns ciphertext; the client decrypts
      with its key file (the repo ships a small Node helper, `cli/agent-mail.mjs`,
      that does pull+decrypt, encrypt+send and attachment decrypt).
    
    Check: an MCP client initializes, subscribes, opens the stream, receives
    `notifications/resources/updated` within 5 s of a new allowed message,
    pulls it, decrypts it with the key file and acks it.
    
    ### R13. Doorbell webhook (optional)
    
    - Settings: "Doorbell URL" (https), "Header name" (default
      `Authorization`) and "Header value" (write-only; shown as set or not set).
      The form notes that the value field takes only the value (for example
      `Bearer …`) and that a full header line is also accepted.
    - On save, the header name is trimmed and a trailing colon is stripped.
      The header value is trimmed; if it starts with the configured header
      name plus a colon (case-insensitive; the header being saved in the same
      request, else the stored header, else `Authorization`), that prefix is
      stripped and the rest is trimmed again. A pasted line such as
      `Authorization: Bearer …` is therefore stored and sent as `Bearer …`.
    - When an item is appended to the user's inbox queue or a new request
      arrives, the Worker POSTs to the URL with that header and
      `Content-Type: application/json` and this content-free body:
      `{"type":"agent-mail.doorbell","handle":"<handle@host>","unread":<n>,"requests":<n>,"at":"<ISO>"}`.
      It never contains a sender, subject, thread or ciphertext.
    - At most one ring per 30 s per user: an arrival inside the window
      schedules one ring for the end of the window (a delayed queue message).
    - A failed ring is logged and not retried; the queue and a scheduled poll
      catch up. "Send test ring" in Settings rings once and shows the HTTP
      status.
    
    Check: with a doorbell URL set, a new allowed message causes exactly one
    POST with the header and a body with only the listed fields. Saving a
    value of `Authorization: Bearer test` (default header name) stores and
    sends `Bearer test`.
    
    ### R14. Web app
    
    Signed-in screens (exact layout in `design.md`): Inbox (threads), Thread
    (decrypted messages, attachments, reply, members), Compose, Requests,
    Contacts (rules), Settings (profile, read receipts, encryption key, doorbell,
    connector tokens). Decryption and encryption happen in the browser. If the
    browser has no key for the user, every screen shows "Set up encryption".
    
    Check: the e2e test drives two local instances in a headless browser:
    sign up on both, set up keys, send A to B with an attachment, approve the
    request on B, read and reply, and see the reply on A.
    
    ### R15. Quality
    
    - Unit tests cover every vector in `test-vectors.json` (including the RFC
      9421 B.2.6, RFC 9530 and RFC 9180 A.1.1 vectors) and activity
      validation. `npm test` passes.
    - The two-instance e2e (`npm run e2e`) exercises every R6 row and R9's
      thread rules over the network, using the test-only routes in
      `design.md` ("Test-only routes").
    - Logs never contain message ciphertext, tokens, the doorbell header value,
      passwords or private keys.
    - The Worker bundle has no `node:` imports. `tsc --noEmit` passes.
    
    ## Definition of done
    
    `npm test` and `npm run e2e` pass, the two-instance e2e covers R4-R13, and a
    deploy following `design.md` ("Deploy") answers WebFinger for its first
    user.
    

    Open spec.md as plain text

  • protocol.md The normative wire format: WebFinger, actors, RFC 9421 signatures, HPKE payloads, activities, error codes, doorbell.

    Protocol: agent-mail/0.1

    This file is normative. Every instance built from this spec must produce and accept exactly these shapes, so that separate builds interoperate. test-vectors.json has worked examples of each; a build passes them all.

    Documents are JSON in ActivityStreams 2.0 compact form. Consumers read the properties as written here; no JSON-LD expansion is needed or done. Unknown properties are ignored. URLs are https. (A test-only var allows http://localhost and http://127.0.0.1 so two local instances can talk.)

    Base64url is RFC 4648 section 5 without padding. Base64 (in structured header byte sequences) is standard with padding.

    1. Identity and discovery

    1.1 WebFinger (RFC 7033)
    GET /.well-known/webfinger?resource=acct:alice@a.example
    200 Content-Type: application/jrd+json
    Access-Control-Allow-Origin: *
    
    {"subject":"acct:alice@a.example",
     "aliases":["https://a.example/users/alice"],
     "links":[{"rel":"self","type":"application/activity+json","href":"https://a.example/users/alice"}]}

    resource may also be the actor URL. The host part must equal the host of SITE_URL (including the port, if any). Unknown: 404 not_found.

    1.2 Actor document

    GET /users/<handle> with Content-Type: application/activity+json:

    {
      "@context": ["https://www.w3.org/ns/activitystreams",
                   "https://w3id.org/security/multikey/v1",
                   {"am": "https://spekkr.com/dwrtz/agent-mail/ns#",
                    "keyAgreement": {"@id": "https://w3id.org/security#keyAgreementMethod", "@type": "@id"}}],
      "id": "https://a.example/users/alice",
      "type": "Person",
      "preferredUsername": "alice",
      "name": "Alice",
      "inbox": "https://a.example/users/alice/inbox",
      "outbox": "https://a.example/users/alice/outbox",
      "assertionMethod": [{"id": "https://a.example/users/alice#sig-1", "type": "Multikey",
                           "controller": "https://a.example/users/alice", "publicKeyMultibase": "z6Mk..."}],
      "keyAgreement":    [{"id": "https://a.example/users/alice#enc-1", "type": "Multikey",
                           "controller": "https://a.example/users/alice", "publicKeyMultibase": "z6LS..."}],
      "am:protocol": "agent-mail/0.1",
      "am:readReceipts": false
    }
    • assertionMethod: Ed25519 signing keys (FEP-521a style). Multikey: "z" + base58btc(0xed 0x01 + 32-byte public key).
    • keyAgreement: X25519 HPKE keys. Multikey: "z" + base58btc(0xec 0x01

      • 32-byte public key). Senders use the last entry. Empty until the user sets up encryption.
    • Key ids are <actor>#sig-<n> and <actor>#enc-<n>.
    • Every key's controller equals the actor id.
    • GET /users/<handle>/outbox returns an empty OrderedCollection ({"@context":"https://www.w3.org/ns/activitystreams","id":"<outbox>","type":"OrderedCollection","totalItems":0,"orderedItems":[]}); messages are never public.
    1.3 Signing key derivation (this implementation's choice; not visible on the wire)

    ed25519 seed = HKDF-SHA256(ikm = base64url-decode(SIGNING_SEED), salt = "agent-mail/0.1", info = "sig:<handle>:<version>", L = 32). Version starts at 1. Vector: signing_key_derivation.

    2. Request signatures (RFC 9421 + RFC 9530)

    Every inbox POST and every attachment GET between instances is signed.

    POST headers:

    Content-Type: application/activity+json
    Content-Digest: sha-256=:<base64 SHA-256 of the body>:
    Signature-Input: am=("@method" "@target-uri" "content-type" "content-digest");created=<unix s>;expires=<created+300>;nonce="<base64url of 16 random bytes>";keyid="<actor>#sig-<n>";alg="ed25519";tag="agent-mail"
    Signature: am=:<base64 Ed25519 signature over the signature base>:

    GET (attachments): Signature-Input: am=("@method" "@target-uri");created=...;expires=...;nonce="...";keyid="...";alg="ed25519";tag="agent-mail".

    • The signature base is built exactly as RFC 9421 section 2.5: one line "<component>": <value> per covered component in order, then "@signature-params": <the Signature-Input value after "am=">, joined by \n with no trailing newline. @method is upper case; @target-uri is the absolute URL the request is sent to, including any query; header values are trimmed.
    • Parameter order as shown. alg is always ed25519; tag is always agent-mail, and verifiers pick the Signature-Input member with tag="agent-mail" whatever its label.
    • Verifiers: clock skew 300 s; lifetime at most 300 s; nonce 16-64 characters, remembered per keyid for 15 minutes; key looked up by fetching the keyid's document URL (part before #) with Accept: application/activity+json and finding the entry in assertionMethod whose id equals the keyid.
    • Vectors: signed_post, signed_get, and the RFC's own B.2.6 (Ed25519) and RFC 9530 example under rfc_vectors.

    3. End-to-end encryption (HPKE, RFC 9180)

    • Suite: mode base, KEM 0x0020 DHKEM(X25519, HKDF-SHA256), KDF 0x0001 HKDF-SHA256, AEAD 0x0001 AES-128-GCM. Single-shot seal/open.
    • info = UTF-8 agent-mail/0.1 note.
    • aad = UTF-8 <Note id> + \n + <recipient actor id>. This binds each ciphertext to its Note and its recipient: it cannot be replayed into another message or to another member.
    • Plaintext = UTF-8 JSON:
    {"v":1,
     "summary":"Lunch?",
     "content":"Are you free for lunch on Friday?",
     "attachments":[{"url":"https://a.example/attachments/6b0c...","name":"hello.txt","mediaType":"text/plain",
                     "size":17,"key":"<base64url 32 bytes>","iv":"<base64url 12 bytes>"}]}

    summary (subject) may be null. content is plain text, at most 65,536 characters. attachments[].size is the plaintext size; one entry per attachment on the Note, matched by url.

    • Vector: hpke (with a fixed ikmE so the output is reproducible) and RFC 9180 A.1.1 under rfc_vectors.
    3.1 Attachment encryption

    AES-256-GCM, a fresh random 32-byte key and 12-byte IV per file, no AAD. Stored bytes = ciphertext followed by the 16-byte tag. The Note's am:size and am:digest describe the stored bytes, so the fetcher checks them before decrypting. Vector: attachment.

    4. Activities

    All activities have "@context": ["https://www.w3.org/ns/activitystreams", {"am": "https://spekkr.com/dwrtz/agent-mail/ns#"}], an id on the actor's origin (<actor>/activities/<uuid>), actor, to (a non-empty array of actor ids, the members other than the actor, at most

    1. and published (ISO 8601 UTC).
    4.1 Create (a message)

    One POST per recipient. Every copy has the same activity id and Note id; only am:encrypted differs.

    {
      "@context": [...],
      "id": "https://a.example/users/alice/activities/<uuid>",
      "type": "Create",
      "actor": "https://a.example/users/alice",
      "published": "2026-11-17T02:00:00Z",
      "to": ["https://b.example/users/bob"],
      "object": {
        "id": "https://a.example/users/alice/notes/<uuid>",
        "type": "Note",
        "attributedTo": "https://a.example/users/alice",
        "to": ["https://b.example/users/bob"],
        "published": "2026-11-17T02:00:00Z",
        "context": "https://a.example/users/alice/threads/<uuid>",
        "inReplyTo": null,
        "content": "This message is end-to-end encrypted.",
        "am:seq": 1,
        "am:encrypted": {"kem": 32, "kdf": 1, "aead": 1,
                         "recipient": "https://b.example/users/bob",
                         "keyId": "https://b.example/users/bob#enc-1",
                         "enc": "<base64url 32 bytes>", "ct": "<base64url>"},
        "attachment": [{"type": "Document", "url": "https://a.example/attachments/<32 hex>",
                        "mediaType": "application/octet-stream", "am:size": 33,
                        "am:digest": "sha-256=:<base64>:"}]
      }
    }
    • content in the clear is always the fixed placeholder This message is end-to-end encrypted. (so a plain ActivityPub server shows something sensible). The real text is only in am:encrypted.
    • context is the thread id. inReplyTo is the Note answered, or null.
    • am:seq counts this actor's activities (Create, Add, Remove) in this thread, from 1.
    • attachment is optional (at most 10). Attachment URLs are on the actor's origin. mediaType on the wire is always application/octet-stream; the real type is inside the ciphertext.
    4.2 Add and Remove (group membership)
    {"@context": [...], "id": "<actor>/activities/<uuid>", "type": "Add",
     "actor": "<thread creator>", "object": "<member added>",
     "target": "<thread id>", "to": ["<every member after the change, except actor>"],
     "am:members": ["<full member list after the change, creator included>"],
     "am:seq": 4, "published": "..."}

    Remove is the same with object = the member removed; its to also includes the removed member. A member leaving sends Remove with object = actor. Only the creator (the actor before /threads/ in the thread id) may Add, or Remove someone else.

    4.3 Read (receipt, opt-in)
    {"@context": [...], "id": "<reader>/activities/<uuid>", "type": "Read",
     "actor": "<reader>", "object": "<Note id>", "to": ["<Note author>"], "published": "..."}

    Sent only by users who turned receipts on.

    4.4 Anything else

    Follow, Like, Delete, etc. get 422 unsupported_activity.

    5. Inbox responses and error codes

    StatuserrorWhen
    202({"status":"accepted"} or {"status":"duplicate"})Accepted, or already received
    400bad_requestMissing or malformed query / body
    400bad_activityActivity fails the shape rules above
    400digest_mismatchContent-Digest missing, not sha-256, or wrong
    401signature_missingNo Signature-Input/Signature with tag agent-mail
    401signature_invalidMalformed, missing components/params, wrong alg, or does not verify
    401signature_expiredcreated skewed by more than 300 s, or past expires
    401key_unavailablekeyid's actor cannot be fetched or does not list the key
    401replayed_nonce(keyid, nonce) seen in the last 15 minutes
    403actor_mismatchkeyid belongs to a different actor than actor
    403not_memberCreate in a known thread from a non-member
    403not_thread_ownerAdd/Remove of someone else by a non-creator
    403forbiddenAttachment GET by an actor not sent that attachment
    404not_foundUnknown user, attachment or route
    413too_largeInbox body over 256 KiB, attachment over 25 MiB
    415unsupported_media_typeWrong Content-Type
    422unsupported_activityType not supported
    422unsupported_encryptionHPKE ids not 32/1/1
    422group_too_largeMore than 50 members
    422not_addressedInbox owner not in to / not the am:encrypted.recipient
    429rate_limitedOver 120 inbox POSTs per minute from one host; Retry-After set

    Body: {"error":"<code>","detail":"<human text>"}, Content-Type: application/json.

    6. Doorbell body

    {"type":"agent-mail.doorbell","handle":"david@agent.example.com","unread":3,"requests":1,"at":"2026-11-17T02:00:05.000Z"}

    Nothing else. The header named in settings carries the configured value.

    # Protocol: agent-mail/0.1
    
    This file is normative. Every instance built from this spec must produce and
    accept exactly these shapes, so that separate builds interoperate.
    `test-vectors.json` has worked examples of each; a build passes them all.
    
    Documents are JSON in ActivityStreams 2.0 compact form. Consumers read the
    properties as written here; no JSON-LD expansion is needed or done. Unknown
    properties are ignored. URLs are `https`. (A test-only var allows
    `http://localhost` and `http://127.0.0.1` so two local instances can talk.)
    
    Base64url is RFC 4648 section 5 without padding. Base64 (in structured
    header byte sequences) is standard with padding.
    
    ## 1. Identity and discovery
    
    ### 1.1 WebFinger (RFC 7033)
    
    ```
    GET /.well-known/webfinger?resource=acct:alice@a.example
    200 Content-Type: application/jrd+json
    Access-Control-Allow-Origin: *
    
    {"subject":"acct:alice@a.example",
     "aliases":["https://a.example/users/alice"],
     "links":[{"rel":"self","type":"application/activity+json","href":"https://a.example/users/alice"}]}
    ```
    
    `resource` may also be the actor URL. The host part must equal the host of
    `SITE_URL` (including the port, if any). Unknown: 404 `not_found`.
    
    ### 1.2 Actor document
    
    `GET /users/<handle>` with `Content-Type: application/activity+json`:
    
    ```json
    {
      "@context": ["https://www.w3.org/ns/activitystreams",
                   "https://w3id.org/security/multikey/v1",
                   {"am": "https://spekkr.com/dwrtz/agent-mail/ns#",
                    "keyAgreement": {"@id": "https://w3id.org/security#keyAgreementMethod", "@type": "@id"}}],
      "id": "https://a.example/users/alice",
      "type": "Person",
      "preferredUsername": "alice",
      "name": "Alice",
      "inbox": "https://a.example/users/alice/inbox",
      "outbox": "https://a.example/users/alice/outbox",
      "assertionMethod": [{"id": "https://a.example/users/alice#sig-1", "type": "Multikey",
                           "controller": "https://a.example/users/alice", "publicKeyMultibase": "z6Mk..."}],
      "keyAgreement":    [{"id": "https://a.example/users/alice#enc-1", "type": "Multikey",
                           "controller": "https://a.example/users/alice", "publicKeyMultibase": "z6LS..."}],
      "am:protocol": "agent-mail/0.1",
      "am:readReceipts": false
    }
    ```
    
    - `assertionMethod`: Ed25519 signing keys (FEP-521a style). Multikey:
      `"z"` + base58btc(`0xed 0x01` + 32-byte public key).
    - `keyAgreement`: X25519 HPKE keys. Multikey: `"z"` + base58btc(`0xec 0x01`
      + 32-byte public key). Senders use the **last** entry. Empty until the
      user sets up encryption.
    - Key ids are `<actor>#sig-<n>` and `<actor>#enc-<n>`.
    - Every key's `controller` equals the actor `id`.
    - `GET /users/<handle>/outbox` returns an empty `OrderedCollection`
      (`{"@context":"https://www.w3.org/ns/activitystreams","id":"<outbox>","type":"OrderedCollection","totalItems":0,"orderedItems":[]}`);
      messages are never public.
    
    ### 1.3 Signing key derivation (this implementation's choice; not visible on the wire)
    
    `ed25519 seed = HKDF-SHA256(ikm = base64url-decode(SIGNING_SEED), salt = "agent-mail/0.1", info = "sig:<handle>:<version>", L = 32)`.
    Version starts at 1. Vector: `signing_key_derivation`.
    
    ## 2. Request signatures (RFC 9421 + RFC 9530)
    
    Every inbox POST and every attachment GET between instances is signed.
    
    **POST** headers:
    
    ```
    Content-Type: application/activity+json
    Content-Digest: sha-256=:<base64 SHA-256 of the body>:
    Signature-Input: am=("@method" "@target-uri" "content-type" "content-digest");created=<unix s>;expires=<created+300>;nonce="<base64url of 16 random bytes>";keyid="<actor>#sig-<n>";alg="ed25519";tag="agent-mail"
    Signature: am=:<base64 Ed25519 signature over the signature base>:
    ```
    
    **GET** (attachments): `Signature-Input: am=("@method" "@target-uri");created=...;expires=...;nonce="...";keyid="...";alg="ed25519";tag="agent-mail"`.
    
    - The signature base is built exactly as RFC 9421 section 2.5:
      one line `"<component>": <value>` per covered component in order, then
      `"@signature-params": <the Signature-Input value after "am=">`, joined by
      `\n` with no trailing newline. `@method` is upper case; `@target-uri` is
      the absolute URL the request is sent to, including any query; header
      values are trimmed.
    - Parameter order as shown. `alg` is always `ed25519`; `tag` is always
      `agent-mail`, and verifiers pick the Signature-Input member with
      `tag="agent-mail"` whatever its label.
    - Verifiers: clock skew 300 s; lifetime at most 300 s; nonce 16-64
      characters, remembered per keyid for 15 minutes; key looked up by
      fetching the keyid's document URL (part before `#`) with
      `Accept: application/activity+json` and finding the entry in
      `assertionMethod` whose `id` equals the keyid.
    - Vectors: `signed_post`, `signed_get`, and the RFC's own B.2.6 (Ed25519)
      and RFC 9530 example under `rfc_vectors`.
    
    ## 3. End-to-end encryption (HPKE, RFC 9180)
    
    - Suite: mode base, KEM `0x0020` DHKEM(X25519, HKDF-SHA256), KDF `0x0001`
      HKDF-SHA256, AEAD `0x0001` AES-128-GCM. Single-shot seal/open.
    - `info` = UTF-8 `agent-mail/0.1 note`.
    - `aad` = UTF-8 `<Note id>` + `\n` + `<recipient actor id>`. This binds each
      ciphertext to its Note and its recipient: it cannot be replayed into
      another message or to another member.
    - Plaintext = UTF-8 JSON:
    
    ```json
    {"v":1,
     "summary":"Lunch?",
     "content":"Are you free for lunch on Friday?",
     "attachments":[{"url":"https://a.example/attachments/6b0c...","name":"hello.txt","mediaType":"text/plain",
                     "size":17,"key":"<base64url 32 bytes>","iv":"<base64url 12 bytes>"}]}
    ```
    
    `summary` (subject) may be null. `content` is plain text, at most 65,536
    characters. `attachments[].size` is the plaintext size; one entry per
    `attachment` on the Note, matched by `url`.
    
    - Vector: `hpke` (with a fixed `ikmE` so the output is reproducible) and
      RFC 9180 A.1.1 under `rfc_vectors`.
    
    ### 3.1 Attachment encryption
    
    AES-256-GCM, a fresh random 32-byte key and 12-byte IV per file, no AAD.
    Stored bytes = ciphertext followed by the 16-byte tag. The Note's
    `am:size` and `am:digest` describe the stored bytes, so the fetcher checks
    them before decrypting. Vector: `attachment`.
    
    ## 4. Activities
    
    All activities have `"@context": ["https://www.w3.org/ns/activitystreams", {"am": "https://spekkr.com/dwrtz/agent-mail/ns#"}]`,
    an `id` on the actor's origin (`<actor>/activities/<uuid>`), `actor`, `to`
    (a non-empty array of actor ids, the members other than the actor, at most
    49) and `published` (ISO 8601 UTC).
    
    ### 4.1 Create (a message)
    
    One POST per recipient. Every copy has the same activity `id` and Note `id`;
    only `am:encrypted` differs.
    
    ```json
    {
      "@context": [...],
      "id": "https://a.example/users/alice/activities/<uuid>",
      "type": "Create",
      "actor": "https://a.example/users/alice",
      "published": "2026-11-17T02:00:00Z",
      "to": ["https://b.example/users/bob"],
      "object": {
        "id": "https://a.example/users/alice/notes/<uuid>",
        "type": "Note",
        "attributedTo": "https://a.example/users/alice",
        "to": ["https://b.example/users/bob"],
        "published": "2026-11-17T02:00:00Z",
        "context": "https://a.example/users/alice/threads/<uuid>",
        "inReplyTo": null,
        "content": "This message is end-to-end encrypted.",
        "am:seq": 1,
        "am:encrypted": {"kem": 32, "kdf": 1, "aead": 1,
                         "recipient": "https://b.example/users/bob",
                         "keyId": "https://b.example/users/bob#enc-1",
                         "enc": "<base64url 32 bytes>", "ct": "<base64url>"},
        "attachment": [{"type": "Document", "url": "https://a.example/attachments/<32 hex>",
                        "mediaType": "application/octet-stream", "am:size": 33,
                        "am:digest": "sha-256=:<base64>:"}]
      }
    }
    ```
    
    - `content` in the clear is always the fixed placeholder
      `This message is end-to-end encrypted.` (so a plain ActivityPub server
      shows something sensible). The real text is only in `am:encrypted`.
    - `context` is the thread id. `inReplyTo` is the Note answered, or null.
    - `am:seq` counts this actor's activities (Create, Add, Remove) in this
      thread, from 1.
    - `attachment` is optional (at most 10). Attachment URLs are on the
      actor's origin. `mediaType` on the wire is always
      `application/octet-stream`; the real type is inside the ciphertext.
    
    ### 4.2 Add and Remove (group membership)
    
    ```json
    {"@context": [...], "id": "<actor>/activities/<uuid>", "type": "Add",
     "actor": "<thread creator>", "object": "<member added>",
     "target": "<thread id>", "to": ["<every member after the change, except actor>"],
     "am:members": ["<full member list after the change, creator included>"],
     "am:seq": 4, "published": "..."}
    ```
    
    `Remove` is the same with `object` = the member removed; its `to` also
    includes the removed member. A member leaving sends `Remove` with
    `object` = `actor`. Only the creator (the actor before `/threads/` in the
    thread id) may Add, or Remove someone else.
    
    ### 4.3 Read (receipt, opt-in)
    
    ```json
    {"@context": [...], "id": "<reader>/activities/<uuid>", "type": "Read",
     "actor": "<reader>", "object": "<Note id>", "to": ["<Note author>"], "published": "..."}
    ```
    
    Sent only by users who turned receipts on.
    
    ### 4.4 Anything else
    
    `Follow`, `Like`, `Delete`, etc. get 422 `unsupported_activity`.
    
    ## 5. Inbox responses and error codes
    
    | Status | `error` | When |
    |---|---|---|
    | 202 | (`{"status":"accepted"}` or `{"status":"duplicate"}`) | Accepted, or already received |
    | 400 | `bad_request` | Missing or malformed query / body |
    | 400 | `bad_activity` | Activity fails the shape rules above |
    | 400 | `digest_mismatch` | Content-Digest missing, not sha-256, or wrong |
    | 401 | `signature_missing` | No Signature-Input/Signature with tag agent-mail |
    | 401 | `signature_invalid` | Malformed, missing components/params, wrong alg, or does not verify |
    | 401 | `signature_expired` | `created` skewed by more than 300 s, or past `expires` |
    | 401 | `key_unavailable` | keyid's actor cannot be fetched or does not list the key |
    | 401 | `replayed_nonce` | `(keyid, nonce)` seen in the last 15 minutes |
    | 403 | `actor_mismatch` | keyid belongs to a different actor than `actor` |
    | 403 | `not_member` | Create in a known thread from a non-member |
    | 403 | `not_thread_owner` | Add/Remove of someone else by a non-creator |
    | 403 | `forbidden` | Attachment GET by an actor not sent that attachment |
    | 404 | `not_found` | Unknown user, attachment or route |
    | 413 | `too_large` | Inbox body over 256 KiB, attachment over 25 MiB |
    | 415 | `unsupported_media_type` | Wrong Content-Type |
    | 422 | `unsupported_activity` | Type not supported |
    | 422 | `unsupported_encryption` | HPKE ids not 32/1/1 |
    | 422 | `group_too_large` | More than 50 members |
    | 422 | `not_addressed` | Inbox owner not in `to` / not the `am:encrypted.recipient` |
    | 429 | `rate_limited` | Over 120 inbox POSTs per minute from one host; `Retry-After` set |
    
    Body: `{"error":"<code>","detail":"<human text>"}`, `Content-Type: application/json`.
    
    ## 6. Doorbell body
    
    ```json
    {"type":"agent-mail.doorbell","handle":"david@agent.example.com","unread":3,"requests":1,"at":"2026-11-17T02:00:05.000Z"}
    ```
    
    Nothing else. The header named in settings carries the configured value.
    

    Open protocol.md as plain text

  • test-vectors.json Worked examples for every wire format element, plus RFC 9421, 9530 and 9180 vectors.
  • design.md Stack and libraries, Cloudflare config, deploy, data model, owner API, MCP tools, key file, CLI, screens, tests.

    Design

    Stack

    • TypeScript everywhere. Worker entry src/worker/index.ts; shared protocol code in src/shared/ (used by the Worker, the browser and the CLI); browser app in src/ui/ bundled with esbuild into a generated module src/worker/ui.gen.ts (export default { html, js, css }) that the Worker serves at /, /app.js, /app.css and, for any other non-API GET that accepts HTML, the same index.html (client routing).
    • Libraries (well-maintained, audited, pure JS, run in Workers, browsers and Node):

      • @noble/curves (Ed25519 sign/verify, X25519) and @noble/hashes (HKDF-SHA256).
      • @hpke/core + @hpke/dhkem-x25519 (hpke-js) for RFC 9180.
      • @scure/base for base58btc (Multikey).
      • Web Crypto for SHA-256, AES-GCM, PBKDF2 and random bytes.
      • No framework in the UI: small DOM helpers, hash-free history routing.
      • Dev: wrangler, vitest, esbuild, typescript, playwright.

    Cloudflare config (wrangler.jsonc)

    {
      "name": "agent-mail",
      "main": "src/worker/index.ts",
      "compatibility_date": "2026-11-16",
      "workers_dev": false,
      "preview_urls": false,
      "d1_databases": [{ "binding": "DB", "database_name": "agent-mail", "database_id": "<id>", "migrations_dir": "migrations" }],
      "r2_buckets": [{ "binding": "FILES", "bucket_name": "agent-mail-files" }],
      "queues": {
        "producers": [{ "binding": "DELIVERY", "queue": "agent-mail-delivery" }],
        "consumers": [{ "queue": "agent-mail-delivery", "max_batch_size": 10, "max_batch_timeout": 2, "max_retries": 8 }]
      },
      "vars": { "SITE_URL": "https://agent.example.com", "ALLOWED_EMAILS": "", "ALLOW_SIGNUP": "1", "ALLOW_HTTP_LOCALHOST": "0" },
      "triggers": { "crons": ["*/15 * * * *"] },
      "observability": { "enabled": true }
    }

    Secret: SIGNING_SEED = base64url of 32 random bytes (wrangler secret put SIGNING_SEED). Changing it changes every user's signing key. Local dev reads it from .dev.vars.

    The repo keeps wrangler.example.jsonc with placeholders; the real wrangler.jsonc with ids is git-ignored.

    Deploy

    1. npx wrangler d1 create agent-mail, npx wrangler r2 bucket create agent-mail-files, npx wrangler queues create agent-mail-delivery; put the D1 id in wrangler.jsonc.
    2. npx wrangler d1 migrations apply DB --remote.
    3. node -e "console.log(Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('base64url'))" | npx wrangler secret put SIGNING_SEED.
    4. Set SITE_URL, ALLOWED_EMAILS; add a Custom Domain (routes: [{ "pattern": "agent.example.com", "custom_domain": true }]).
    5. npm run build && npm run deploy. Sign up with an allowed email, choose the handle, set up encryption, download the key file.
    6. Optionally set ALLOW_SIGNUP to "0" afterwards.

    Two instances in the same Cloudflare zone can reach each other: a Worker's fetch to another Worker's Custom Domain works. A Worker fetching its own origin is routed internally to its own handler (see "Local delivery").

    Data model (migrations/0001_init.sql)

    CREATE TABLE users (
      id INTEGER PRIMARY KEY, handle TEXT NOT NULL UNIQUE, email TEXT NOT NULL UNIQUE COLLATE NOCASE,
      name TEXT NOT NULL, pw_hash TEXT NOT NULL, pw_salt TEXT NOT NULL,
      sig_version INTEGER NOT NULL DEFAULT 1, read_receipts INTEGER NOT NULL DEFAULT 0,
      doorbell_url TEXT, doorbell_header TEXT, doorbell_value TEXT, doorbell_next_at TEXT,
      doorbell_pending INTEGER NOT NULL DEFAULT 0 /* 1 while a delayed ring is queued */,
      created_at TEXT NOT NULL);
    CREATE TABLE enc_keys (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, n INTEGER NOT NULL,
      public_key TEXT NOT NULL /* base64url raw X25519 */, created_at TEXT NOT NULL, UNIQUE(user_id, n));
    CREATE TABLE sessions (token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL, expires_at TEXT NOT NULL);
    CREATE TABLE api_tokens (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, label TEXT NOT NULL,
      token_hash TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL, last_used_at TEXT);
    CREATE TABLE actor_cache (actor_id TEXT PRIMARY KEY, doc TEXT NOT NULL, fetched_at TEXT NOT NULL);
    CREATE TABLE nonces (k TEXT PRIMARY KEY /* keyid + ' ' + nonce */, expires_at TEXT NOT NULL);
    CREATE TABLE rate (host TEXT NOT NULL, minute TEXT NOT NULL, n INTEGER NOT NULL, PRIMARY KEY (host, minute));
    CREATE TABLE threads (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, uri TEXT NOT NULL, creator TEXT,
      members TEXT NOT NULL /* JSON array */, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, UNIQUE(user_id, uri));
    CREATE TABLE seqs (user_id INTEGER NOT NULL, thread TEXT NOT NULL, actor TEXT NOT NULL, last INTEGER NOT NULL,
      PRIMARY KEY (user_id, thread, actor));
    CREATE TABLE messages (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, direction TEXT NOT NULL /* in|out */,
      activity_id TEXT NOT NULL, type TEXT NOT NULL, note_id TEXT, thread TEXT, actor TEXT NOT NULL,
      activity TEXT NOT NULL /* JSON as received, or the sender's own copy for out */, published TEXT NOT NULL,
      state TEXT NOT NULL /* in: queued|request ; out: sent */, gap_before INTEGER NOT NULL DEFAULT 0,
      read_at TEXT, read_by TEXT NOT NULL DEFAULT '{}', received_at TEXT NOT NULL,
      UNIQUE(user_id, direction, activity_id));
    CREATE INDEX messages_thread ON messages(user_id, thread, published);
    CREATE INDEX messages_note ON messages(user_id, note_id);
    CREATE INDEX messages_state ON messages(user_id, direction, state);
    CREATE TABLE inbox_queue (cursor INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL,
      message_id INTEGER NOT NULL, created_at TEXT NOT NULL, acked_at TEXT);
    CREATE INDEX inbox_queue_user ON inbox_queue(user_id, acked_at, cursor);
    CREATE TABLE rules (user_id INTEGER NOT NULL, subject TEXT NOT NULL /* actor URL or domain:host */,
      action TEXT NOT NULL CHECK (action IN ('allow','block')), created_at TEXT NOT NULL, PRIMARY KEY (user_id, subject));
    CREATE TABLE attachments (id TEXT PRIMARY KEY /* 32 hex */, user_id INTEGER NOT NULL, size INTEGER NOT NULL,
      digest TEXT NOT NULL, created_at TEXT NOT NULL);
    CREATE TABLE attachment_grants (attachment_id TEXT NOT NULL, actor TEXT NOT NULL, PRIMARY KEY (attachment_id, actor));
    CREATE TABLE drafts (note_id TEXT PRIMARY KEY, user_id INTEGER NOT NULL, thread TEXT NOT NULL, in_reply_to TEXT,
      recipients TEXT NOT NULL /* JSON [{actor,inbox,keyId,publicKey}] */, members TEXT NOT NULL, seq INTEGER NOT NULL,
      new_thread INTEGER NOT NULL, expires_at TEXT NOT NULL);
    CREATE TABLE deliveries (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, message_id INTEGER NOT NULL,
      target TEXT NOT NULL, inbox TEXT NOT NULL, body TEXT NOT NULL, status TEXT NOT NULL /* queued|delivered|failed */,
      attempts INTEGER NOT NULL DEFAULT 0, last_error TEXT, updated_at TEXT NOT NULL);
    CREATE TABLE mcp_sessions (id TEXT PRIMARY KEY, user_id INTEGER NOT NULL, subscribed INTEGER NOT NULL DEFAULT 0,
      created_at TEXT NOT NULL, last_seen_at TEXT NOT NULL);

    Requests are messages rows with direction='in' and state='request'. A sent message is one messages row (direction='out', activity = the Create with the sender's own am:encrypted copy, encrypted to the sender's key with aad = <Note id>\n<sender actor>) and one deliveries row per recipient (the exact JSON body sent).

    Doorbell bookkeeping: doorbell_next_at is the end of the current 30 s window; doorbell_pending is 1 while a delayed {kind:"doorbell"} queue message is waiting to ring at that time, so at most one is queued.

    Cron (every 15 min): delete expired nonces, sessions, drafts, rate rows older than 2 minutes, actor cache older than 1 day, MCP sessions idle for a day.

    Local delivery

    federatedFetch(url, init): when new URL(url).origin === SITE_URL, the Worker calls its own fetch handler with a Request instead of going to the network (no network round trip, and it works the same in local dev). The request is still signed and goes through every inbox check. Actor lookups for local actors use the same path.

    Owner API

    All JSON; session cookie (web app) or Authorization: Bearer connector token. 401 unauthorized if neither.

    Method and pathBody / queryAnswer
    GET /api/config(no auth){host,origin}
    POST /api/auth/signup{email,password,handle,name}{ok:true} + cookie
    POST /api/auth/login{email,password}{ok:true} + cookie
    POST /api/auth/logout{}
    GET /api/me{user:{handle,name,email,actor,address,readReceipts,encKeys:[{n,keyId,publicKey}],doorbell:{url,header,valueSet},unread,requests,latestCursor,unreadMessages}}
    PUT /api/keys/encryption{publicKey} (base64url raw X25519){keyId}; same key twice is a no-op
    DELETE /api/keys/encryption/:n{} (cannot delete the only key or the newest key)
    PUT /api/settings{name?,readReceipts?,doorbellUrl?,doorbellHeader?,doorbellValue?} (header name: trim, strip a trailing colon; header value: trim, strip a leading <header>: if present){user}
    POST /api/doorbell/test{status}
    GET /api/tokens, POST /api/tokens, DELETE /api/tokens/:id{label}{tokens} / {token} (shown once) / {}
    POST /api/resolve{to:[handle or actor URL]}{actors:[{actor,handle,name,inbox,keyId,publicKey}]}
    POST /api/outbox/prepare{to?:[...], replyTo?: noteId, threadId?: string}{noteId,activityId,threadId,seq,recipients:[{actor,keyId,publicKey}],self:{actor,keyId,publicKey},info,aadFormat}
    POST /users/:handle/outbox{noteId,payloads:[{recipient,keyId,enc,ct}],selfPayload:{keyId,enc,ct},attachments?:[{url,size,digest}]}202 {noteId,threadId,deliveries:[{target,status}]}
    POST /api/threads/members{uri, add?:[...], remove?:[...]} (creator only, or remove self){members}
    GET /api/threads[{uri,creator,members,updatedAt,unread,last:{direction,published,activity}}] (threads holding only requests are left out)
    GET /api/threads/messages?uri=[{id,direction,type,actor,activity,published,gapBefore,readAt,readBy,deliveries:[{target,status,attempts,last_error}]}]
    GET /api/queue?since=&limit={items,nextCursor,more}
    POST /api/queue/ack{upTo?} or {ids?}{acked,unread}
    GET /api/requests{items}
    POST /api/requests/approve, /block{actor}{moved} / {dropped}
    GET /api/rules, PUT /api/rules, DELETE /api/rules?subject={subject,action}
    POST /api/messages/read{noteIds:[...]}{marked,receiptsSent}
    POST /api/attachmentsraw bytes, Content-Type: application/octet-stream{url,size,digest}
    POST /api/attachments/fetch{url,size,digest}bytes

    unread, requests and latestCursor describe the agent queue (unacked items); unreadMessages counts received messages the owner has not opened and is the web app's Inbox badge. The two are independent: an agent acking its queue does not mark messages read, and reading in the web app does not ack the queue.

    Prepare for a reply: thread = the Note's thread; recipients = its members minus the user. Prepare for a new thread: thread id SITE_URL/users/<handle>/threads/<uuid>. threadId without to posts to an existing thread's members.

    MCP server (/mcp)

    JSON-RPC over Streamable HTTP. POST /mcp takes one request or notification and answers application/json (no SSE on POST). Methods: initialize, notifications/initialized, ping, tools/list, tools/call, resources/list, resources/read, resources/subscribe, resources/unsubscribe. GET /mcp (SSE) as in R12. DELETE /mcp ends the session. Tool results are {"content":[{"type":"text","text":"<JSON>"}],"structuredContent":<same JSON>}.

    ToolInputOutput
    whoami{address, actor, encKeyId, readReceipts}
    pull{since?: int, limit?: 1-100}{items:[{cursor,kind,sender,thread,receivedAt,gapBefore,activity}], nextCursor, more}
    ack{upTo?: int, ids?: int[]}{acked, unread}
    list_requests{items:[{id,sender,thread,receivedAt,activity}]}
    approve / block{actor}{moved} / {dropped}
    list_threadsas GET /api/threads
    prepare_message{to?: string[], replyTo?: string, threadId?: string}as prepare
    send_message{noteId, payloads, selfPayload, attachments?}as outbox POST
    mark_read{noteIds: string[]}{marked, receiptsSent}
    fetch_attachment{url,size,digest}{base64} (stored, still encrypted; max 5 MiB here)

    The design notes' reply is prepare_message with replyTo then send_message.

    Key file

    {"type":"agent-mail-key","v":1,"address":"david@agent.example.com","actor":"https://agent.example.com/users/david",
     "keyId":"https://agent.example.com/users/david#enc-1","privateKey":"<base64url 32 bytes>","publicKey":"<base64url 32 bytes>"}

    Downloaded as <handle>@<host>.agent-mail-key.json. Anyone with it can read the user's messages: keep it like a password.

    CLI helper (cli/agent-mail.mjs)

    Node 20+, no install beyond the repo's dependencies (bundled by npm run build:cli into cli/agent-mail.mjs). Env AGENT_MAIL_URL, AGENT_MAIL_TOKEN, AGENT_MAIL_KEY (path to the key file). Commands: pull [--since N] (pull + decrypt, prints JSON), ack <upTo>, send --to a@b,c@d [--subject S] [--attach file] <text>, reply <noteId> <text>, requests, approve <actor>, read <noteId>, attachment <url> <size> <digest> <key> <iv> <outfile>. It talks to /mcp.

    Screens

    Look: system font stack, white background, 1px #e5e7eb borders, 8px radius, accent brand_color on primary buttons and the unread dot, max width 960px, left nav on desktop (Inbox, Requests, Compose, Contacts, Settings, with counts) and a compact top bar on mobile (brand, then a wrapping row of links with small inline badges).

    • Sign in / Sign up (/login, /signup): email, password; sign-up adds handle (shows @<host> after it) and display name.
    • Set up encryption (shown instead of any screen when the browser has no private key for the user's latest #enc-n): "Create a new key" (generates, publishes, then shows "Download key file") and "Use an existing key file" (file input; checks its public key is listed).
    • Inbox (/): threads, newest first: members (handles), decrypted subject or first line, time, unread dot. Empty: "No messages yet."
    • Thread (/thread?uri=): messages oldest first; each shows sender, time, subject, text, attachments (download decrypts), "Read by …" under sent ones when receipts arrive, delivery state for sent ones, gap notices. Reply box at the bottom. Members panel (creator can add/remove; anyone can "Leave thread"). Opening marks unread messages read (R11).
    • Compose (/compose): To (comma-separated handles), Subject, Message, Attach files, Send. Errors such as no_encryption_key are shown in words.
    • Requests (/requests): sender, time, decrypted preview, Approve and Block.
    • Contacts (/contacts): rules table, add an actor or domain:host as Allow or Block, remove.
    • Settings (/settings): your address; display name; "Send read receipts" switch; encryption keys (download key file, create new key, remove old keys); doorbell URL, header name, header value (with a note that the value field takes only the value, for example "Bearer …", and that a full header line is also accepted), "Send test ring"; connector tokens (create, shown once, revoke) with the MCP URL.

    Tests

    • tests/vectors.test.ts: every vector in test-vectors.json (Vitest, plain Node; no Worker runtime needed).
    • tests/activity.test.ts: activity validation (R9 shapes, member caps, addressing).
    • tests/doorbell.test.ts: doorbell header and value normalization (R13).
    • e2e/e2e.ts (npm run e2e): builds the UI, starts two wrangler dev instances (ports 8787 and 8788, separate --persist-to dirs, ALLOW_HTTP_LOCALHOST=1, TEST_ROUTES=1), and runs e2e/suite.ts then e2e/ui.ts against them. The suite covers R4-R13 over HTTP and MCP; every R6 row is exercised over the network (T5 forged signature, T6 replay, T7 the remaining rows, T8 block, T9/T9b group rules), not in unit tests. e2e/ui.ts is a Playwright (Chromium) pass over the web app that writes the screenshots.
    • e2e/live.ts: the same suite and UI pass against two deployed instances (AM_A, AM_B origins; AM_PROBE the probe key file).
    Test-only routes

    When the var TEST_ROUTES is "1" (never on a real instance) the Worker also serves:

    • GET /__test/probe: a stand-in remote actor (no inbox) whose Ed25519 #sig-1 key is the Multikey in the var TEST_PROBE_KEY. The tests hold the matching private key and use it to send hand-built signed requests for the R6 rows (forged, replayed, stale, wrong digest and so on).
    • POST /__test/sink, GET /__test/sink, DELETE /__test/sink: a doorbell target. A POST stores the body and the SHA-256 of the doorbell header value (never the value) in R2 under sink/; GET lists them; DELETE clears them.

    Deploy notes from the reference deployment

    • Two Workers in the same zone with Custom Domains reach each other with plain fetch (no 522 or loop errors); the live suite passed on that setup.
    • The reference deployment used D1, R2 and Queues on an account that already had Queues available; no other paid features are used.
    # Design
    
    ## Stack
    
    - TypeScript everywhere. Worker entry `src/worker/index.ts`; shared
      protocol code in `src/shared/` (used by the Worker, the browser and the
      CLI); browser app in `src/ui/` bundled with esbuild into a generated
      module `src/worker/ui.gen.ts` (`export default { html, js, css }`) that
      the Worker serves at `/`, `/app.js`, `/app.css` and, for any other
      non-API GET that accepts HTML, the same `index.html` (client routing).
    - Libraries (well-maintained, audited, pure JS, run in Workers, browsers
      and Node):
      - `@noble/curves` (Ed25519 sign/verify, X25519) and `@noble/hashes`
        (HKDF-SHA256).
      - `@hpke/core` + `@hpke/dhkem-x25519` (hpke-js) for RFC 9180.
      - `@scure/base` for base58btc (Multikey).
      - Web Crypto for SHA-256, AES-GCM, PBKDF2 and random bytes.
      - No framework in the UI: small DOM helpers, hash-free history routing.
      - Dev: `wrangler`, `vitest`, `esbuild`, `typescript`, `playwright`.
    
    ## Cloudflare config (`wrangler.jsonc`)
    
    ```jsonc
    {
      "name": "agent-mail",
      "main": "src/worker/index.ts",
      "compatibility_date": "2026-11-16",
      "workers_dev": false,
      "preview_urls": false,
      "d1_databases": [{ "binding": "DB", "database_name": "agent-mail", "database_id": "<id>", "migrations_dir": "migrations" }],
      "r2_buckets": [{ "binding": "FILES", "bucket_name": "agent-mail-files" }],
      "queues": {
        "producers": [{ "binding": "DELIVERY", "queue": "agent-mail-delivery" }],
        "consumers": [{ "queue": "agent-mail-delivery", "max_batch_size": 10, "max_batch_timeout": 2, "max_retries": 8 }]
      },
      "vars": { "SITE_URL": "https://agent.example.com", "ALLOWED_EMAILS": "", "ALLOW_SIGNUP": "1", "ALLOW_HTTP_LOCALHOST": "0" },
      "triggers": { "crons": ["*/15 * * * *"] },
      "observability": { "enabled": true }
    }
    ```
    
    Secret: `SIGNING_SEED` = base64url of 32 random bytes
    (`wrangler secret put SIGNING_SEED`). Changing it changes every user's
    signing key. Local dev reads it from `.dev.vars`.
    
    The repo keeps `wrangler.example.jsonc` with placeholders; the real
    `wrangler.jsonc` with ids is git-ignored.
    
    ## Deploy
    
    1. `npx wrangler d1 create agent-mail`, `npx wrangler r2 bucket create agent-mail-files`,
       `npx wrangler queues create agent-mail-delivery`; put the D1 id in `wrangler.jsonc`.
    2. `npx wrangler d1 migrations apply DB --remote`.
    3. `node -e "console.log(Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('base64url'))" | npx wrangler secret put SIGNING_SEED`.
    4. Set `SITE_URL`, `ALLOWED_EMAILS`; add a Custom Domain (`routes: [{ "pattern": "agent.example.com", "custom_domain": true }]`).
    5. `npm run build && npm run deploy`. Sign up with an allowed email, choose the handle, set up encryption, download the key file.
    6. Optionally set `ALLOW_SIGNUP` to `"0"` afterwards.
    
    Two instances in the same Cloudflare zone can reach each other: a Worker's
    `fetch` to another Worker's Custom Domain works. A Worker fetching its own
    origin is routed internally to its own handler (see "Local delivery").
    
    ## Data model (`migrations/0001_init.sql`)
    
    ```sql
    CREATE TABLE users (
      id INTEGER PRIMARY KEY, handle TEXT NOT NULL UNIQUE, email TEXT NOT NULL UNIQUE COLLATE NOCASE,
      name TEXT NOT NULL, pw_hash TEXT NOT NULL, pw_salt TEXT NOT NULL,
      sig_version INTEGER NOT NULL DEFAULT 1, read_receipts INTEGER NOT NULL DEFAULT 0,
      doorbell_url TEXT, doorbell_header TEXT, doorbell_value TEXT, doorbell_next_at TEXT,
      doorbell_pending INTEGER NOT NULL DEFAULT 0 /* 1 while a delayed ring is queued */,
      created_at TEXT NOT NULL);
    CREATE TABLE enc_keys (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, n INTEGER NOT NULL,
      public_key TEXT NOT NULL /* base64url raw X25519 */, created_at TEXT NOT NULL, UNIQUE(user_id, n));
    CREATE TABLE sessions (token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL, expires_at TEXT NOT NULL);
    CREATE TABLE api_tokens (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, label TEXT NOT NULL,
      token_hash TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL, last_used_at TEXT);
    CREATE TABLE actor_cache (actor_id TEXT PRIMARY KEY, doc TEXT NOT NULL, fetched_at TEXT NOT NULL);
    CREATE TABLE nonces (k TEXT PRIMARY KEY /* keyid + ' ' + nonce */, expires_at TEXT NOT NULL);
    CREATE TABLE rate (host TEXT NOT NULL, minute TEXT NOT NULL, n INTEGER NOT NULL, PRIMARY KEY (host, minute));
    CREATE TABLE threads (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, uri TEXT NOT NULL, creator TEXT,
      members TEXT NOT NULL /* JSON array */, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, UNIQUE(user_id, uri));
    CREATE TABLE seqs (user_id INTEGER NOT NULL, thread TEXT NOT NULL, actor TEXT NOT NULL, last INTEGER NOT NULL,
      PRIMARY KEY (user_id, thread, actor));
    CREATE TABLE messages (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, direction TEXT NOT NULL /* in|out */,
      activity_id TEXT NOT NULL, type TEXT NOT NULL, note_id TEXT, thread TEXT, actor TEXT NOT NULL,
      activity TEXT NOT NULL /* JSON as received, or the sender's own copy for out */, published TEXT NOT NULL,
      state TEXT NOT NULL /* in: queued|request ; out: sent */, gap_before INTEGER NOT NULL DEFAULT 0,
      read_at TEXT, read_by TEXT NOT NULL DEFAULT '{}', received_at TEXT NOT NULL,
      UNIQUE(user_id, direction, activity_id));
    CREATE INDEX messages_thread ON messages(user_id, thread, published);
    CREATE INDEX messages_note ON messages(user_id, note_id);
    CREATE INDEX messages_state ON messages(user_id, direction, state);
    CREATE TABLE inbox_queue (cursor INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL,
      message_id INTEGER NOT NULL, created_at TEXT NOT NULL, acked_at TEXT);
    CREATE INDEX inbox_queue_user ON inbox_queue(user_id, acked_at, cursor);
    CREATE TABLE rules (user_id INTEGER NOT NULL, subject TEXT NOT NULL /* actor URL or domain:host */,
      action TEXT NOT NULL CHECK (action IN ('allow','block')), created_at TEXT NOT NULL, PRIMARY KEY (user_id, subject));
    CREATE TABLE attachments (id TEXT PRIMARY KEY /* 32 hex */, user_id INTEGER NOT NULL, size INTEGER NOT NULL,
      digest TEXT NOT NULL, created_at TEXT NOT NULL);
    CREATE TABLE attachment_grants (attachment_id TEXT NOT NULL, actor TEXT NOT NULL, PRIMARY KEY (attachment_id, actor));
    CREATE TABLE drafts (note_id TEXT PRIMARY KEY, user_id INTEGER NOT NULL, thread TEXT NOT NULL, in_reply_to TEXT,
      recipients TEXT NOT NULL /* JSON [{actor,inbox,keyId,publicKey}] */, members TEXT NOT NULL, seq INTEGER NOT NULL,
      new_thread INTEGER NOT NULL, expires_at TEXT NOT NULL);
    CREATE TABLE deliveries (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, message_id INTEGER NOT NULL,
      target TEXT NOT NULL, inbox TEXT NOT NULL, body TEXT NOT NULL, status TEXT NOT NULL /* queued|delivered|failed */,
      attempts INTEGER NOT NULL DEFAULT 0, last_error TEXT, updated_at TEXT NOT NULL);
    CREATE TABLE mcp_sessions (id TEXT PRIMARY KEY, user_id INTEGER NOT NULL, subscribed INTEGER NOT NULL DEFAULT 0,
      created_at TEXT NOT NULL, last_seen_at TEXT NOT NULL);
    ```
    
    Requests are `messages` rows with `direction='in'` and `state='request'`.
    A sent message is one `messages` row (`direction='out'`, `activity` = the
    Create with the sender's own `am:encrypted` copy, encrypted to the sender's
    key with `aad = <Note id>\n<sender actor>`) and one `deliveries` row per
    recipient (the exact JSON body sent).
    
    Doorbell bookkeeping: `doorbell_next_at` is the end of the current 30 s
    window; `doorbell_pending` is 1 while a delayed `{kind:"doorbell"}` queue
    message is waiting to ring at that time, so at most one is queued.
    
    Cron (every 15 min): delete expired nonces, sessions, drafts, `rate` rows
    older than 2 minutes, actor cache older than 1 day, MCP sessions idle for a
    day.
    
    ## Local delivery
    
    `federatedFetch(url, init)`: when `new URL(url).origin === SITE_URL`, the
    Worker calls its own fetch handler with a `Request` instead of going to the
    network (no network round trip, and it works the same in local dev). The request is still
    signed and goes through every inbox check. Actor lookups for local actors use
    the same path.
    
    ## Owner API
    
    All JSON; session cookie (web app) or `Authorization: Bearer` connector
    token. 401 `unauthorized` if neither.
    
    | Method and path | Body / query | Answer |
    |---|---|---|
    | GET /api/config | (no auth) | `{host,origin}` |
    | POST /api/auth/signup | `{email,password,handle,name}` | `{ok:true}` + cookie |
    | POST /api/auth/login | `{email,password}` | `{ok:true}` + cookie |
    | POST /api/auth/logout | | `{}` |
    | GET /api/me | | `{user:{handle,name,email,actor,address,readReceipts,encKeys:[{n,keyId,publicKey}],doorbell:{url,header,valueSet},unread,requests,latestCursor,unreadMessages}}` |
    | PUT /api/keys/encryption | `{publicKey}` (base64url raw X25519) | `{keyId}`; same key twice is a no-op |
    | DELETE /api/keys/encryption/:n | | `{}` (cannot delete the only key or the newest key) |
    | PUT /api/settings | `{name?,readReceipts?,doorbellUrl?,doorbellHeader?,doorbellValue?}` (header name: trim, strip a trailing colon; header value: trim, strip a leading `<header>:` if present) | `{user}` |
    | POST /api/doorbell/test | | `{status}` |
    | GET /api/tokens, POST /api/tokens, DELETE /api/tokens/:id | `{label}` | `{tokens}` / `{token}` (shown once) / `{}` |
    | POST /api/resolve | `{to:[handle or actor URL]}` | `{actors:[{actor,handle,name,inbox,keyId,publicKey}]}` |
    | POST /api/outbox/prepare | `{to?:[...], replyTo?: noteId, threadId?: string}` | `{noteId,activityId,threadId,seq,recipients:[{actor,keyId,publicKey}],self:{actor,keyId,publicKey},info,aadFormat}` |
    | POST /users/:handle/outbox | `{noteId,payloads:[{recipient,keyId,enc,ct}],selfPayload:{keyId,enc,ct},attachments?:[{url,size,digest}]}` | 202 `{noteId,threadId,deliveries:[{target,status}]}` |
    | POST /api/threads/members | `{uri, add?:[...], remove?:[...]}` (creator only, or remove self) | `{members}` |
    | GET /api/threads | | `[{uri,creator,members,updatedAt,unread,last:{direction,published,activity}}]` (threads holding only requests are left out) |
    | GET /api/threads/messages?uri= | | `[{id,direction,type,actor,activity,published,gapBefore,readAt,readBy,deliveries:[{target,status,attempts,last_error}]}]` |
    | GET /api/queue?since=&limit= | | `{items,nextCursor,more}` |
    | POST /api/queue/ack | `{upTo?}` or `{ids?}` | `{acked,unread}` |
    | GET /api/requests | | `{items}` |
    | POST /api/requests/approve, /block | `{actor}` | `{moved}` / `{dropped}` |
    | GET /api/rules, PUT /api/rules, DELETE /api/rules?subject= | `{subject,action}` | |
    | POST /api/messages/read | `{noteIds:[...]}` | `{marked,receiptsSent}` |
    | POST /api/attachments | raw bytes, `Content-Type: application/octet-stream` | `{url,size,digest}` |
    | POST /api/attachments/fetch | `{url,size,digest}` | bytes |
    
    `unread`, `requests` and `latestCursor` describe the agent queue (unacked
    items); `unreadMessages` counts received messages the owner has not opened
    and is the web app's Inbox badge. The two are independent: an agent acking
    its queue does not mark messages read, and reading in the web app does not
    ack the queue.
    
    Prepare for a reply: thread = the Note's thread; recipients = its members
    minus the user. Prepare for a new thread: thread id
    `SITE_URL/users/<handle>/threads/<uuid>`. `threadId` without `to` posts to
    an existing thread's members.
    
    ## MCP server (`/mcp`)
    
    JSON-RPC over Streamable HTTP. `POST /mcp` takes one request or
    notification and answers `application/json` (no SSE on POST). Methods:
    `initialize`, `notifications/initialized`, `ping`, `tools/list`,
    `tools/call`, `resources/list`, `resources/read`, `resources/subscribe`,
    `resources/unsubscribe`. `GET /mcp` (SSE) as in R12. `DELETE /mcp` ends the
    session. Tool results are `{"content":[{"type":"text","text":"<JSON>"}],"structuredContent":<same JSON>}`.
    
    | Tool | Input | Output |
    |---|---|---|
    | `whoami` | | `{address, actor, encKeyId, readReceipts}` |
    | `pull` | `{since?: int, limit?: 1-100}` | `{items:[{cursor,kind,sender,thread,receivedAt,gapBefore,activity}], nextCursor, more}` |
    | `ack` | `{upTo?: int, ids?: int[]}` | `{acked, unread}` |
    | `list_requests` | | `{items:[{id,sender,thread,receivedAt,activity}]}` |
    | `approve` / `block` | `{actor}` | `{moved}` / `{dropped}` |
    | `list_threads` | | as GET /api/threads |
    | `prepare_message` | `{to?: string[], replyTo?: string, threadId?: string}` | as prepare |
    | `send_message` | `{noteId, payloads, selfPayload, attachments?}` | as outbox POST |
    | `mark_read` | `{noteIds: string[]}` | `{marked, receiptsSent}` |
    | `fetch_attachment` | `{url,size,digest}` | `{base64}` (stored, still encrypted; max 5 MiB here) |
    
    The design notes' `reply` is `prepare_message` with `replyTo` then
    `send_message`.
    
    ## Key file
    
    ```json
    {"type":"agent-mail-key","v":1,"address":"david@agent.example.com","actor":"https://agent.example.com/users/david",
     "keyId":"https://agent.example.com/users/david#enc-1","privateKey":"<base64url 32 bytes>","publicKey":"<base64url 32 bytes>"}
    ```
    
    Downloaded as `<handle>@<host>.agent-mail-key.json`. Anyone with it can read
    the user's messages: keep it like a password.
    
    ## CLI helper (`cli/agent-mail.mjs`)
    
    Node 20+, no install beyond the repo's dependencies (bundled by
    `npm run build:cli` into `cli/agent-mail.mjs`). Env `AGENT_MAIL_URL`,
    `AGENT_MAIL_TOKEN`, `AGENT_MAIL_KEY` (path to the key file).
    Commands: `pull [--since N]` (pull + decrypt, prints JSON), `ack <upTo>`,
    `send --to a@b,c@d [--subject S] [--attach file] <text>`,
    `reply <noteId> <text>`, `requests`, `approve <actor>`, `read <noteId>`,
    `attachment <url> <size> <digest> <key> <iv> <outfile>`. It talks to `/mcp`.
    
    ## Screens
    
    Look: system font stack, white background, 1px `#e5e7eb` borders, 8px
    radius, accent `brand_color` on primary buttons and the unread dot,
    max width 960px, left nav on desktop (Inbox, Requests, Compose, Contacts,
    Settings, with counts) and a compact top bar on mobile (brand, then a wrapping row of links with small inline badges).
    
    - **Sign in / Sign up** (`/login`, `/signup`): email, password; sign-up
      adds handle (shows `@<host>` after it) and display name.
    - **Set up encryption** (shown instead of any screen when the browser has
      no private key for the user's latest `#enc-n`): "Create a new key"
      (generates, publishes, then shows "Download key file") and
      "Use an existing key file" (file input; checks its public key is listed).
    - **Inbox** (`/`): threads, newest first: members (handles), decrypted
      subject or first line, time, unread dot. Empty: "No messages yet."
    - **Thread** (`/thread?uri=`): messages oldest first; each shows sender,
      time, subject, text, attachments (download decrypts), "Read by …" under
      sent ones when receipts arrive, delivery state for sent ones, gap
      notices. Reply box at the bottom. Members panel (creator can add/remove;
      anyone can "Leave thread"). Opening marks unread messages read (R11).
    - **Compose** (`/compose`): To (comma-separated handles), Subject, Message,
      Attach files, Send. Errors such as `no_encryption_key` are shown in words.
    - **Requests** (`/requests`): sender, time, decrypted preview, Approve and
      Block.
    - **Contacts** (`/contacts`): rules table, add an actor or `domain:host`
      as Allow or Block, remove.
    - **Settings** (`/settings`): your address; display name; "Send read
      receipts" switch; encryption keys (download key file, create new key,
      remove old keys); doorbell URL, header name, header value (with a note
      that the value field takes only the value, for example "Bearer …", and
      that a full header line is also accepted), "Send test ring"; connector
      tokens (create, shown once, revoke) with the MCP URL.
    
    ## Tests
    
    - `tests/vectors.test.ts`: every vector in `test-vectors.json` (Vitest,
      plain Node; no Worker runtime needed).
    - `tests/activity.test.ts`: activity validation (R9 shapes, member caps,
      addressing).
    - `tests/doorbell.test.ts`: doorbell header and value normalization (R13).
    - `e2e/e2e.ts` (`npm run e2e`): builds the UI, starts two `wrangler dev`
      instances (ports 8787 and 8788, separate `--persist-to` dirs,
      `ALLOW_HTTP_LOCALHOST=1`, `TEST_ROUTES=1`), and runs `e2e/suite.ts` then
      `e2e/ui.ts` against them. The suite covers R4-R13 over HTTP and MCP;
      every R6 row is exercised over the network (T5 forged signature, T6
      replay, T7 the remaining rows, T8 block, T9/T9b group rules), not in
      unit tests. `e2e/ui.ts` is a Playwright (Chromium) pass over the web app
      that writes the screenshots.
    - `e2e/live.ts`: the same suite and UI pass against two deployed instances
      (`AM_A`, `AM_B` origins; `AM_PROBE` the probe key file).
    
    ### Test-only routes
    
    When the var `TEST_ROUTES` is `"1"` (never on a real instance) the Worker
    also serves:
    
    - `GET /__test/probe`: a stand-in remote actor (no inbox) whose Ed25519
      `#sig-1` key is the Multikey in the var `TEST_PROBE_KEY`. The tests hold
      the matching private key and use it to send hand-built signed requests
      for the R6 rows (forged, replayed, stale, wrong digest and so on).
    - `POST /__test/sink`, `GET /__test/sink`, `DELETE /__test/sink`: a
      doorbell target. A POST stores the body and the SHA-256 of the doorbell
      header value (never the value) in R2 under `sink/`; GET lists them;
      DELETE clears them.
    
    ## Deploy notes from the reference deployment
    
    - Two Workers in the same zone with Custom Domains reach each other with
      plain `fetch` (no 522 or loop errors); the live suite passed on that
      setup.
    - The reference deployment used D1, R2 and Queues on an account that
      already had Queues available; no other paid features are used.
    

    Open design.md as plain text

  • tasks.md Build order, each step with a check.

    Tasks

    Work in this order. Finish each check before the next task.

    1. Set up. npm package, wrangler.jsonc from design.md, .dev.vars with a test SIGNING_SEED, src/shared, src/worker, src/ui, the UI build script. Check: npm run dev serves a page titled app_name.
    2. Protocol library (src/shared). Base64url, Multikey, Content-Digest, RFC 9421 sign/verify, HPKE seal/open, attachment AES-GCM, HKDF signing keys, activity validation. Check: tests/vectors.test.ts passes every vector in test-vectors.json, including the three RFC vectors.
    3. Schema and accounts (R1, R2). Migration, sign-up/in/out, sessions, allow-list, Origin check. Check: allowed vs not-allowed sign-up.
    4. Keys and discovery (R3, R4). Actor document, WebFinger, encryption key publish/remove. Check: R4's check.
    5. Inbox checks (R6). In the table's order, plus the test-only routes (design.md). Check: an e2e case per row.
    6. Policy, queue, threads (R7, R8, R9). Check: R7-R9 checks in the e2e suite.
    7. Sending (R5). Resolve, prepare, outbox, queue consumer with retries, local delivery. Check: two local instances exchange a message.
    8. Attachments (R10) and read receipts (R11).
    9. MCP (R12), doorbell (R13), CLI helper.
    10. Web app (R14).
    11. E2E. npm run e2e across two instances; screenshots.
    12. Deploy and live test. Deploy two instances (design.md, "Deploy") and run e2e/live.ts against them.
    # Tasks
    
    Work in this order. Finish each check before the next task.
    
    1. **Set up.** npm package, `wrangler.jsonc` from `design.md`, `.dev.vars`
       with a test `SIGNING_SEED`, `src/shared`, `src/worker`, `src/ui`, the UI
       build script. Check: `npm run dev` serves a page titled `app_name`.
    2. **Protocol library (`src/shared`).** Base64url, Multikey, Content-Digest,
       RFC 9421 sign/verify, HPKE seal/open, attachment AES-GCM, HKDF signing
       keys, activity validation. Check: `tests/vectors.test.ts` passes every
       vector in `test-vectors.json`, including the three RFC vectors.
    3. **Schema and accounts (R1, R2).** Migration, sign-up/in/out, sessions,
       allow-list, Origin check. Check: allowed vs not-allowed sign-up.
    4. **Keys and discovery (R3, R4).** Actor document, WebFinger, encryption
       key publish/remove. Check: R4's check.
    5. **Inbox checks (R6).** In the table's order, plus the test-only routes
       (`design.md`). Check: an e2e case per row.
    6. **Policy, queue, threads (R7, R8, R9).** Check: R7-R9 checks in the
       e2e suite.
    7. **Sending (R5).** Resolve, prepare, outbox, queue consumer with retries,
       local delivery. Check: two local instances exchange a message.
    8. **Attachments (R10) and read receipts (R11).**
    9. **MCP (R12), doorbell (R13), CLI helper.**
    10. **Web app (R14).**
    11. **E2E.** `npm run e2e` across two instances; screenshots.
    12. **Deploy and live test.** Deploy two instances (`design.md`, "Deploy")
        and run `e2e/live.ts` against them.
    

    Open tasks.md as plain text

  • research.md The standards it rests on, fediverse interop limits and the 0.1 choices.

Is it for me?

Platforms
web, backend
Tools
TypeScript, Cloudflare Workers, Cloudflare D1, Cloudflare R2, Cloudflare Queues, Wrangler, hpke-js, noble-curves, esbuild, Vitest, Playwright

What does it need?

Agent permissions
shell, network
Commands it runs
npm install npx wrangler d1 migrations apply DB --local npx wrangler dev npm test npm run e2e npx playwright install chromium
Secrets it reads
SIGNING_SEED

What changed?

  • 0.1.317 Nov 2026Mobile nav no longer stretches the unread badge into a tall pill or leaves large gaps in the header; links sit in a compact wrapping top bar. Addresses in the sidebar and member list wrap at natural breaks. New screenshots.
  • 0.1.217 Nov 2026Doorbell settings normalize a pasted full header line (Authorization: Bearer …) to just the value, and strip a trailing colon from the header name. The settings form mentions this.
  • 0.1.117 Nov 2026Matches the deployed reference build: doorbell_pending column and message indexes, /api/config, owner API answer shapes, unreadMessages as the Inbox badge, retry backoff wording, test-only routes and the e2e and live suites (R6 rows tested over the network), localStorage key store, deploy notes, screenshots from the live deployment.
  • 0.1.017 Nov 2026First version.

For agents: start.md says how to build this spec, spec.json holds everything on this page, and bundle.tar.gz holds its files.