diff --git a/.claude/rules/trust-boundaries.md b/.claude/rules/trust-boundaries.md index 0f8a50d..08810a8 100644 --- a/.claude/rules/trust-boundaries.md +++ b/.claude/rules/trust-boundaries.md @@ -29,6 +29,9 @@ paths: - "shared/original.ts" - "shared/live.ts" - "shared/sending.ts" + - "shared/rules.ts" + - "shared/rules-schema.ts" + - "workers/lib/rule-facts.ts" - "migrations/**" - ".github/**" - ".claude/settings.json" diff --git a/.claude/skills/podbay-security/SKILL.md b/.claude/skills/podbay-security/SKILL.md index 734caa3..deed544 100644 --- a/.claude/skills/podbay-security/SKILL.md +++ b/.claude/skills/podbay-security/SKILL.md @@ -22,12 +22,12 @@ Find the paths you changed. A path may sit on more than one boundary. | Path | Boundary | |---|---| -| `workers/lib/inbound.ts`, `workers/lib/filenames.ts`, the `email` handler in `workers/app.ts`, `receiveEmail` in `workers/arrival.ts`, `workers/lib/original.ts` (the key of an original, the platform's `Authentication-Results` field), any use of the mail parser, `shared/log.ts` and any log call | B1 | +| `workers/lib/inbound.ts`, `workers/lib/filenames.ts`, the `email` handler in `workers/app.ts`, `receiveEmail` in `workers/arrival.ts`, `workers/lib/original.ts` (the key of an original, the platform's `Authentication-Results` field), the rules a mailbox runs on mail that arrives (`shared/rules.ts`, `workers/lib/rule-facts.ts`, `workers/durableObject/rules.ts`), any use of the mail parser, `shared/log.ts` and any log call | B1 | | `app/lib/mail-html.ts`, `app/components/EmailIframe.tsx`, anything that puts message content in the DOM, the attachment route in `workers/index.ts`, `workers/lib/attachments.ts`, the original of a message: `workers/routes/original.ts`, `shared/original.ts`, `app/lib/original-text.ts`, `app/lib/original.ts`, `app/components/email-panel/OriginalMessage.tsx` | B2 | | `workers/auth/options.ts`, `workers/auth/used-codes.ts`, `workers/auth/instance.ts`, `workers/routes/account.ts` (sign-in, setup), the origin check, the check of a WebSocket handshake (`upgradeRefusal`) and the session lookup in `workers/auth/middleware.ts`, the optional Access check in `workers/app.ts`, `migrations/0001_auth.sql`, cookies, response headers | B3 | | `workers/auth/authorize.ts`, `workers/auth/route-table.ts`, `workers/auth/middleware.ts` (the guard), `workers/auth/store.ts`, `workers/routes/mailboxes.ts`, every route under `/api/v1/mailboxes/`, `workers/durableObject/`, the connection to the open app (`workers/routes/live.ts`, `workers/durableObject/live.ts`, `shared/live.ts`, `app/lib/live.ts`), `migrations/0002_index.sql`, any place that builds a Durable Object name or an R2 key | B4 | | `workers/agent/`, `workers/mcp/`, `workers/lib/tools.ts`, `workers/lib/ai.ts`, `workers/lib/features.ts`, the `/mcp` and `/agents` routes | B5 | -| `workers/email-sender.ts`, `validateSender` in `workers/lib/email-helpers.ts`, `workers/routes/reply-forward.ts`, the send route in `workers/index.ts`, `workers/lib/outgoing.ts` and `outgoing-message.ts`, `workers/routes/sending.ts` (`unsend`, `reschedule`), in the mailbox object `leaving.ts` (the one function that lets mail leave), `submissions.ts` (the states and the handover), `alarm.ts` and `sending.ts` (the caps), `workers/auth/standing.ts`, `shared/sending.ts`, `scripts/checks/sender.ts` | B6 | +| `workers/email-sender.ts`, `validateSender` in `workers/lib/email-helpers.ts`, `workers/routes/reply-forward.ts`, the send route in `workers/index.ts`, `workers/lib/outgoing.ts` and `outgoing-message.ts`, `workers/routes/sending.ts` (`unsend`, `reschedule`), in the mailbox object `leaving.ts` (the one function that lets mail leave), `submissions.ts` (the states and the handover), `alarm.ts` and `sending.ts` (the caps), `auto-reply.ts` (the reply a mailbox sends by itself, ADR-0008), `workers/auth/standing.ts`, `shared/sending.ts`, `scripts/checks/sender.ts` | B6 | | Bindings, variables and secrets in `wrangler.jsonc`, `.dev.vars.example`, later the health, setup and operator routes | B7 | | Later: queue producers and consumers, the export code, the scheduled handler | B8 | | `package.json`, `pnpm-lock.yaml`, `pnpm-workspace.yaml`, `copies.json`, `NOTICE`, `.claude/skills/security-audit/` | B9 | @@ -38,7 +38,7 @@ Unsure? Treat it as a boundary change. A new entry point (a route, a tool, a han ## 2. The trust boundaries -State on 2026-11-17: accounts, sign-in, memberships, the MCP keys, the content policies and the attachment rules are built and tested. Queues, exports and releases are **not built yet**; their rows say so. The original of a received message is kept in R2 since ADR-0015 was built on 2026-11-17. Since ADR-0016 was built on 2026-11-18, a message that is sent waits in the mailbox and leaves from the mailbox object's alarm, by one function. No full audit has run yet. Do not read a planned control as a control that exists. +State on 2026-11-17: accounts, sign-in, memberships, the MCP keys, the content policies and the attachment rules are built and tested. Queues, exports and releases are **not built yet**; their rows say so. The original of a received message is kept in R2 since ADR-0015 was built on 2026-11-17. Since ADR-0016 was built on 2026-11-18, a message that is sent waits in the mailbox and leaves from the mailbox object's alarm, by one function. Since ADR-0008 was built on 2026-11-18, a mailbox has rules that run when mail arrives (filters, blocked senders) and an automatic reply, the one mail that leaves with nobody pressing Send. No full audit has run yet. Do not read a planned control as a control that exists. | # | Boundary | Rules | Proof today | |---|---|---|---| @@ -60,8 +60,8 @@ Each boundary below has the same five lines: what crosses it, the invariant, the - **Crosses:** a raw message from anyone on the internet, through Email Routing into the `email` handler. Envelope, headers, body, attachments and file names are all written by the sender. - **Invariant:** the envelope recipient picks the mailbox, never a header. Nothing from a message becomes a Durable Object name or an R2 key without passing `workers/lib/inbound.ts` or `workers/lib/filenames.ts`. Parsing happens in one place, with size and time bounds, and its output is validated before it is stored. Logs carry opaque ids, never a body, a subject or an address. -- **Code today:** `mailboxAddressFor` and `routeInbound` in `workers/lib/inbound.ts`; `storageFilename` in `workers/lib/filenames.ts`; `shared/log.ts`, the only module that writes logs. **Arrival** (ADR-0015; `receiveEmail` in `workers/arrival.ts`, `workers/durableObject/originals.ts`): the mailbox is picked by the envelope before a byte is read; a declared size outside 1 byte to 25 MiB is refused with `setReject`; a row in `arrivals` is written, then the bytes are stored exactly and without metadata under a key made from 16 random bytes (`newRawKey` in `workers/lib/original.ts`), which holds nothing of the message; a stream of another length than declared is a failure that removes what was written and makes the handler throw. That is the line: after it the handler neither throws nor rejects. The message is parsed inside the handler, once; one transaction writes the message's row with the key and the size read from the arrival's own row, its attachment rows (marked `uploading_since`) and removes the arrival; then the files' bytes are written. A message the parser refuses, or whose text is too large for a row, is filed with its original alone (`unparsed`), joins no conversation and wakes no assistant. An arrival older than fifteen minutes is taken up by the next one, three at a time, each by a call that counts the attempt: parsed on the first, filed as `interrupted` from the second, removed when its bytes are not there. **Authentication** (`platformStatement` in `workers/lib/original.ts`): the first `Authentication-Results` field is read from the message's headers, cut at the first comma outside a quoted string or a comment, and kept only when its identifier is exactly `mx.cloudflare.net`; it is stored and, until the live check of decision 19 is recorded, said to nobody (`AUTHENTICATION_SHOWN` in `shared/original.ts`). **Known addresses** (ADR-0012): nothing on the way of incoming mail writes to `known_addresses`. A mailbox learns an address in one step, `learn` in `workers/durableObject/known.ts`, which the mailbox object calls only where it stores a message a person sent; an arriving message is filed by `fileArrival`, which does not pass it. -- **Proof today:** `test/unit/inbound.test.ts`, `test/unit/filenames.test.ts`, and `test/workerd/inbound.test.ts` (the `To` header cannot pick a mailbox; a message without `To` is delivered; unknown and malformed recipients are rejected and nothing is stored). `test/unit/log.test.ts` (an address in a log field is masked); `pnpm static ratchets` counts `console.*` calls outside the log module. **Conversations:** `In-Reply-To` and `References` are the sender's claim. A message joins a conversation only when a message with one of those ids is in the mailbox and has the same subject (`workers/durableObject/threads.ts`; `test/workerd/inbound.test.ts`: joins, is refused with another subject, keeps answers to unknown mail together, survives 400 references). **Arrival** (`test/workerd/original.test.ts`): the object equals what was sent byte for byte, also when it is not text, and has no metadata; the key matches its shape for a message full of path characters; the arrival's row is there when the bytes are written and a file's row when its bytes are; a size outside the limits is rejected and the stream is not read; a shorter or longer stream, and a bucket that fails, leave no row and no object and the handler throws; a message nested deeper than the parser goes, and one larger than a row, arrive as `unparsed` with the envelope sender and their originals; a handler stopped before filing leaves a row the next arrival finishes, a second attempt is filed as `interrupted`, a row without bytes is removed; the same message twice is two messages. **Authentication** (`test/workerd/original-routes.test.ts`, `test/unit/original.test.ts`): a second field with the platform's identifier is not taken, a first field with another identifier keeps nothing even when the platform's follows, and a quoted string or comment that never closes keeps nothing. **Known addresses** (`test/workerd/known-addresses.test.ts`): after mail arrives with a crafted From, Reply-To and Cc, in the inbox and moved to Spam, the mailbox's table is empty and the completion offers nothing for any of them; `test/unit/known-addresses.test.ts` holds that neither the arrival nor the originals module names the step, and that the mailbox object calls it in exactly two places. +- **Code today:** `mailboxAddressFor` and `routeInbound` in `workers/lib/inbound.ts`; `storageFilename` in `workers/lib/filenames.ts`; `shared/log.ts`, the only module that writes logs. **Arrival** (ADR-0015; `receiveEmail` in `workers/arrival.ts`, `workers/durableObject/originals.ts`): the mailbox is picked by the envelope before a byte is read; a declared size outside 1 byte to 25 MiB is refused with `setReject`; a row in `arrivals` is written, then the bytes are stored exactly and without metadata under a key made from 16 random bytes (`newRawKey` in `workers/lib/original.ts`), which holds nothing of the message; a stream of another length than declared is a failure that removes what was written and makes the handler throw. That is the line: after it the handler neither throws nor rejects. The message is parsed inside the handler, once; one transaction writes the message's row with the key and the size read from the arrival's own row, its attachment rows (marked `uploading_since`) and removes the arrival; then the files' bytes are written. A message the parser refuses, or whose text is too large for a row, is filed with its original alone (`unparsed`), joins no conversation and wakes no assistant. An arrival older than fifteen minutes is taken up by the next one, three at a time, each by a call that counts the attempt: parsed on the first, filed as `interrupted` from the second, removed when its bytes are not there. **Authentication** (`platformStatement` in `workers/lib/original.ts`): the first `Authentication-Results` field is read from the message's headers, cut at the first comma outside a quoted string or a comment, and kept only when its identifier is exactly `mx.cloudflare.net`; it is stored and, until the live check of decision 19 is recorded, said to nobody (`AUTHENTICATION_SHOWN` in `shared/original.ts`). **Known addresses** (ADR-0012): nothing on the way of incoming mail writes to `known_addresses`. A mailbox learns an address in one step, `learn` in `workers/durableObject/known.ts`, which the mailbox object calls only where it stores a message a person sent; an arriving message is filed by `fileArrival`, which does not pass it. **Rules** (ADR-0008; `shared/rules.ts`, `workers/lib/rule-facts.ts`, `workers/durableObject/rules.ts`): a mailbox's filters and blocked senders run once, in the step that files an arrival, after the message was parsed and before its row is written. What they are told of a message is built in one place (`factsOfParsed`) and cut to fixed lengths (`FACT_LIMITS`): the address and name it says it is from, the addresses of To and Cc, the subject, the first 20,000 characters of its text, whether a file came along, its `Auto-Submitted` field and whether it names a list. One pure function (`evaluate`) goes from the rules and those facts to an outcome. A condition is text compared after folding case, with `===` and `includes`: nothing a stranger or a person wrote becomes a regular expression, a `LIKE` pattern or part of a statement, and every query of the module is a constant with bound values. A rule that cannot be evaluated is skipped and counted; the function does not throw, and what surrounds it is guarded (`outcomeFor`), so a rule can change where a message is filed and can never stop it from being stored. A label is given only when it is a label of this mailbox and the place is neither Spam nor Trash. +- **Proof today:** `test/unit/rules.test.ts` (the vocabulary, the order, each kind of broken rule, hostile text in bounded time, the facts of a parsed message) and `test/workerd/rules.test.ts` (mail filed by a filter and by a block; a wildcard and a statement in a rule and in a message are words; a stored rule that is not one, and the rules table gone, leave the message stored, nothing rejected and nothing thrown; nothing runs on stored mail). `test/unit/inbound.test.ts`, `test/unit/filenames.test.ts`, and `test/workerd/inbound.test.ts` (the `To` header cannot pick a mailbox; a message without `To` is delivered; unknown and malformed recipients are rejected and nothing is stored). `test/unit/log.test.ts` (an address in a log field is masked); `pnpm static ratchets` counts `console.*` calls outside the log module. **Conversations:** `In-Reply-To` and `References` are the sender's claim. A message joins a conversation only when a message with one of those ids is in the mailbox and has the same subject (`workers/durableObject/threads.ts`; `test/workerd/inbound.test.ts`: joins, is refused with another subject, keeps answers to unknown mail together, survives 400 references). **Arrival** (`test/workerd/original.test.ts`): the object equals what was sent byte for byte, also when it is not text, and has no metadata; the key matches its shape for a message full of path characters; the arrival's row is there when the bytes are written and a file's row when its bytes are; a size outside the limits is rejected and the stream is not read; a shorter or longer stream, and a bucket that fails, leave no row and no object and the handler throws; a message nested deeper than the parser goes, and one larger than a row, arrive as `unparsed` with the envelope sender and their originals; a handler stopped before filing leaves a row the next arrival finishes, a second attempt is filed as `interrupted`, a row without bytes is removed; the same message twice is two messages. **Authentication** (`test/workerd/original-routes.test.ts`, `test/unit/original.test.ts`): a second field with the platform's identifier is not taken, a first field with another identifier keeps nothing even when the platform's follows, and a quoted string or comment that never closes keeps nothing. **Known addresses** (`test/workerd/known-addresses.test.ts`): after mail arrives with a crafted From, Reply-To and Cc, in the inbox and moved to Spam, the mailbox's table is empty and the completion offers nothing for any of them; `test/unit/known-addresses.test.ts` holds that neither the arrival nor the originals module names the step, and that the mailbox object calls it in exactly two places. - **Open:** the live check of decision 19 (a forged field sent to a real domain; until it is in the ledger nothing is said about authentication), and a development instance, where nothing checks authentication and a field the sender wrote is believed. The queue consumer as the only parser, the hostile-message corpus, the static check on the parser import, validation of parsed output, the test that feeds marked content through every handler and scans the log output, the CPU budget. ### B2. Mail HTML and attachments in the browser @@ -85,25 +85,25 @@ Each boundary below has the same five lines: what crosses it, the invariant, the - **Crosses:** a mailbox, message or attachment id in a request, and the identity of the caller. - **Invariant:** deny by default. One `authorize(actor, action, resource)` decides for every route, tool and connection, from one table. A non-member gets "not found". **Managing is not reading:** an owner or administrator without a membership cannot open a mailbox, and granting themselves one needs step-up, is audited and is visible to the mailbox's owners. An id from a request is resolved to an opaque id before it touches storage. Deleting a message or a mailbox removes its rows, its Durable Object data and its R2 objects. -- **Code today:** `authorize` in `workers/auth/authorize.ts` decides; `ROUTE_TABLE` in `workers/auth/route-table.ts` names the right of every API route; the guard in `workers/auth/middleware.ts` runs in front of all of `/api/*`, refuses a route that is not in the table, resolves the mailbox through the D1 index with the caller's membership, and names the Durable Object after the address stored in the index, never after the request. A non-member gets 404, whatever their instance role, with one exception that `authorize` names: `mailbox.members.read` and `mailbox.members.manage` are also allowed to an owner or administrator of the instance without a membership. The guard looks the mailbox up with the caller's membership or none (`mailboxFor`), sets the storage stub only when there is a membership, and lets `authorize` decide; so a manager reaches the member routes (`workers/routes/people.ts`) and the registry (`GET /api/v1/registry/mailboxes`: address, owners, member count) and nothing else. Every member change needs fresh proof and is recorded with whose membership, which role and in which capacity it was made (`membershipDetail`: `as: owner` or `as: manager`, `self:` for one's own); `memberHistory` reads that record back for the mailbox's owners, including a manager who added and removed themselves. A mailbox always keeps an owner. Deleting a mailbox purges its Durable Object and its attachments (`purge` in `workers/durableObject/index.ts`). The agent connection checks a session and the right to change mail in that mailbox (`mailboxDecision`). **One message moved** (`POST …/emails/:id/move`, `moveEmail` in the mailbox object): Sent is never a target, Scheduled neither a source nor a target, and Drafts takes only a message the mailbox wrote and that never left (`writtenHere` in `workers/durableObject/drafts.ts`: no Message-ID, header list, original or `unparsed`), which is how the app undoes deleting a draft; `test/workerd/move.test.ts`. **Many conversations at once** (ADR-0014; `workers/routes/bulk.ts`, `workers/durableObject/deeds.ts` and `deed-steps.ts`): three routes, each `mailbox.write` in the route table. The request is parsed by one schema the app takes its types from (`shared/bulk.ts`): it names no target but Inbox, Archive, Spam and Trash and no change but a move, read, a star and labels, so nothing in it deletes for good or sends. A filter is the search route's own conditions (`buildSearchConditions`) and is only counted by the request that names it; acting is a second call that names the deed, whose id is opaque and is looked up in the database of the mailbox the guard picked. What a deed changed is kept for an hour as ids, places and marks, never content, and goes row by row with a message that is deleted for good. A filter deed is written to the audit log when it starts and when it is undone (`mailbox.bulk`, `mailbox.bulk_undone`) with who, which mailbox, which change and how many, never the filter. **The original of a message** (ADR-0015): both routes are `mailbox.read` in the route table. The message id only looks a row up in the database of the mailbox the guard picked (`originalOf` in `workers/durableObject/originals.ts`), and the key of the object comes from that row and from nowhere else: no code builds the key of an original. `raw_key` and `auth_results` never leave the mailbox object in an answer about a message (`shownMessage`), which says `has_original`, `raw_size` and `unparsed`. **Deletion** (rule S13): objects go before rows. One function deletes a message (`deleteMessage` in `workers/lib/messages.ts`: its files, its original, then its rows); emptying a place names a batch and its objects, deletes the objects, then the rows of that batch (`workers/durableObject/emptying.ts`); deleting a mailbox reads the keys of every file, every original and every arrival (`allKeys`), deletes the objects a thousand at a time, and only then empties the mailbox object. A failure leaves rows that can be deleted again, never an object no row names. **Known addresses** (ADR-0012; `workers/routes/known-addresses.ts`): completing an address is part of writing, so `GET …/known-addresses?q=` and forgetting one need `mailbox.write`, and forgetting them all `mailbox.manage`, which is audited by the mailbox and a number, never an address. The query is 1 to 64 characters, compared with `substr` and never put into a pattern; the answer is at most 8 entries of id, address and name, with no paging, total, count or date. The addresses are in the mailbox's own database, so they are deleted with it. **A person's choices** are not a mailbox's and not a manager's: see B3. **The mailbox tells the open app** (ADR-0013; `workers/routes/live.ts`, `workers/durableObject/live.ts`, `shared/live.ts`): being told that a mailbox changed is a way of reading it, so `GET …/live` is `mailbox.read` in the route table: a reader listens, and someone without a membership is told 404 whatever their instance role. **Nothing on the connection is mail:** the object sends one shape, a version and four counters, built by `liveMessage` from the list of kinds and from nothing else, at most 256 bytes; what changed is read through the ordinary routes, each authorised as before. The signal is raised by the write itself: `watch` wraps every method of the mailbox object where the class is defined, asks SQLite how many rows changed, and moves the counters the method is about (`ABOUT`; mail when it says nothing), so no caller can forget it or raise it without writing. **The object is told who by the Worker:** the route hands it a request it builds (`liveRequest`), with the person's id and the time the guard allowed it and nothing of the browser's; the object keeps the id as the connection's tag and the time as its attachment, and no session and no role. **A right that ends, ends here too:** the routes that remove a member or change a role close that person's connections in the same request, after the index is written (`closeLiveOf`, also for someone who manages the instance and has no membership: the one call reads nothing); deleting a mailbox closes them all (`purge`); and whatever the Worker did not know about ends at five minutes (B3). The app says `ping`, which the platform answers; any other message closes the connection (1008). Eight connections for a person in a mailbox, two hundred for a mailbox. Logs name the object's id and the account's id, never a message. **Outgoing mail** (ADR-0016; `workers/routes/sending.ts`, `workers/durableObject/submissions.ts`): `POST …/emails/:id/unsend` and `…/reschedule` are `mailbox.send` in the route table, like the three send routes; seeing Scheduled is `mailbox.read`. The id only looks a row up in the database of the mailbox the guard picked. **A message enters and leaves the place Scheduled only by being sent, taken back or let go:** the mailbox object's own methods refuse a waiting message (`inScheduled`) wherever one is moved, deleted, marked or labelled, and refuse Scheduled as a target, so no route and no tool can do it by another way; a deed on many conversations that names one is refused whole, and one on a conversation or a search passes over it. Deleting a mailbox takes its alarm off and deletes every row, the ones that wait among them, so nothing is sent afterwards. -- **Proof today:** `test/workerd/sending-routes.test.ts` (outgoing mail: an owner and a sender send, take back and give a new time; a reader sees Scheduled and is refused all of it; someone without a membership, whatever they manage, gets 404, nobody is served without a session or from another origin; a waiting message of another mailbox is 404; every route that changes mail refuses a waiting message with 409 `SCHEDULED` and changes nothing; nothing can be moved into Scheduled; after a mailbox is deleted no row, no object and no alarm is left and the send binding was never called); `test/workerd/original-routes.test.ts` and `test/workerd/original.test.ts` (the original: a reader is served and a non-member gets 404 on both routes, 401 without a session; a message id of another mailbox the caller is also a member of is 404; no answer of the message, list, thread, search and original routes contains `raw_key`, `auth_results` or the key itself; a sent message, a draft and old mail answer `NO_ORIGINAL`, a row whose object is gone `ORIGINAL_MISSING`; after deleting a message for good, emptying Trash and deleting the mailbox the bucket holds nothing of it, an arrival's object included; a bucket that fails leaves the rows; the migration is run from the release before it and rewrites nothing); `test/workerd/bulk.test.ts` (acting on many conversations: a reader is refused and a non-member told nothing on all three routes; a message, a label and a deed of another mailbox do not exist here; over a limit, an empty filter, both or neither scope, an unknown change, and Sent or Drafts as a target are refused with nothing changed; a filter request changes nothing, and a deed is not run without it, later than ten minutes, or after its scope grew; mail stored after the asking is never taken; undo is refused after the hour and never undoes a later change; a deleted message leaves no row in the record; the audit rows carry no word of the search) and `test/unit/bulk.test.ts` (the schema and its limits); `test/workerd/emptying.test.ts` (emptying takes Trash and Spam only, refuses a reader and tells a non-member nothing, and leaves no row or object of what was there); `test/unit/authorize.test.ts` (the whole rights matrix, the table's shape) and `test/workerd/access.test.ts`: every registered route is in the table and the table names no missing route; each mailbox route answers 404 to a signed-in non-member and to an administrator without a membership, 401 without a session, 403 to a reader where it changes anything, 403 to a sender where it manages; a crafted address is 404; an administrator can create a mailbox for someone else and then cannot open it; deletion removes mail, attachments, the index row and memberships, and a new mailbox at the same address starts empty. `test/workerd/members.test.ts`: an owner adds by address, changes and removes; a non-owner member sees the list and changes nothing; a non-member gets 404 on every member route; an administrator without a membership sees members, history and the registry but gets 404 on mail, settings, folders and deletion; their self-grant opens the mailbox and is on the record, which stays after they leave; the last owner cannot be removed or demoted by anyone; every change is refused without fresh proof; the audit rows carry the capacity. `test/workerd/access.test.ts` pins that the member routes are the only mailbox routes an administrator without a membership passes. **Labels** (ADR-0007): `test/workerd/labels.test.ts`: a reader sees labels and changes none, someone without a membership is told nothing, a label of another mailbox does not exist here, a label that is asked for and is not one finds nothing, deleting a label deletes no mail, deleting a message leaves no label row, and nobody makes, renames or removes a place; `test/unit/labels.test.ts` (ids, names). `test/workerd/known-addresses.test.ts` (known addresses: 404 on all three routes to someone without a membership and to an administrator without one, 403 to a reader, 401 without a session, 403 from another origin; a sender completes and forgets one and is refused forgetting all; an owner forgets all, on the record without an address; another mailbox's addresses never appear and its ids are nothing here; what is typed is never a pattern, also when it is longer than a pattern may be; no empty and no over-long query; never more than 8, and no way to the rest; forgetting after two years and above 5,000; deleting a sent message forgets nothing; deleting the mailbox leaves no row; the migration is run from the release before it and reads nothing back). `test/workerd/choices.test.ts` (managing is not reading: no route gives an owner or an administrator another person's choices). **The connection** (`test/workerd/live.test.ts`): an owner, a sender and a reader listen; someone without a membership and an administrator without one get 404, as does a mailbox that is not there or a crafted name; 401 without a session (and the generic loops of `test/workerd/access.test.ts` now ask it as a handshake). Removing a member closes that person's connections and no other's by the time the request has answered, and what happens next is told to the owner only; a changed role closes them and the person comes back through the guard; a refused change closes nothing; an administrator without a membership who removes a member closes them too and still cannot listen; deleting the mailbox closes every connection. After the object was put out of memory a connection is found by its tag, belongs to the same person, and is told once and closed as before. The ninth connection of a person closes their oldest; the two hundred and first is 503 and closes nobody; the object refuses a request that is not the Worker's handshake; `ping` is answered and anything else, bytes included, is closed with 1008 and tells nobody. The log lines carry opaque ids and no address, counter or word. **What is told** (`test/workerd/live-signal.test.ts`): marked content fed through every kind of write appears in no message of either tab, every message is the one shape under 256 bytes, no state is sent twice, each counter moves for exactly what it should and none for a read or a refusal; the test lists the object's methods, fails for one that is neither a known read nor known by what it is about, calls each read and fails if it changes a row, and shows a method written without knowledge of the signal raising it; the migration is run from the release before it. `pnpm e2e` `live.spec.ts`: in a real browser the frames are counters only. +- **Code today:** `authorize` in `workers/auth/authorize.ts` decides; `ROUTE_TABLE` in `workers/auth/route-table.ts` names the right of every API route; the guard in `workers/auth/middleware.ts` runs in front of all of `/api/*`, refuses a route that is not in the table, resolves the mailbox through the D1 index with the caller's membership, and names the Durable Object after the address stored in the index, never after the request. A non-member gets 404, whatever their instance role, with one exception that `authorize` names: `mailbox.members.read` and `mailbox.members.manage` are also allowed to an owner or administrator of the instance without a membership. The guard looks the mailbox up with the caller's membership or none (`mailboxFor`), sets the storage stub only when there is a membership, and lets `authorize` decide; so a manager reaches the member routes (`workers/routes/people.ts`) and the registry (`GET /api/v1/registry/mailboxes`: address, owners, member count) and nothing else. Every member change needs fresh proof and is recorded with whose membership, which role and in which capacity it was made (`membershipDetail`: `as: owner` or `as: manager`, `self:` for one's own); `memberHistory` reads that record back for the mailbox's owners, including a manager who added and removed themselves. A mailbox always keeps an owner. Deleting a mailbox purges its Durable Object and its attachments (`purge` in `workers/durableObject/index.ts`). The agent connection checks a session and the right to change mail in that mailbox (`mailboxDecision`). **One message moved** (`POST …/emails/:id/move`, `moveEmail` in the mailbox object): Sent is never a target, Scheduled neither a source nor a target, and Drafts takes only a message the mailbox wrote and that never left (`writtenHere` in `workers/durableObject/drafts.ts`: no Message-ID, header list, original or `unparsed`), which is how the app undoes deleting a draft; `test/workerd/move.test.ts`. **Many conversations at once** (ADR-0014; `workers/routes/bulk.ts`, `workers/durableObject/deeds.ts` and `deed-steps.ts`): three routes, each `mailbox.write` in the route table. The request is parsed by one schema the app takes its types from (`shared/bulk.ts`): it names no target but Inbox, Archive, Spam and Trash and no change but a move, read, a star and labels, so nothing in it deletes for good or sends. A filter is the search route's own conditions (`buildSearchConditions`) and is only counted by the request that names it; acting is a second call that names the deed, whose id is opaque and is looked up in the database of the mailbox the guard picked. What a deed changed is kept for an hour as ids, places and marks, never content, and goes row by row with a message that is deleted for good. A filter deed is written to the audit log when it starts and when it is undone (`mailbox.bulk`, `mailbox.bulk_undone`) with who, which mailbox, which change and how many, never the filter. **The original of a message** (ADR-0015): both routes are `mailbox.read` in the route table. The message id only looks a row up in the database of the mailbox the guard picked (`originalOf` in `workers/durableObject/originals.ts`), and the key of the object comes from that row and from nowhere else: no code builds the key of an original. `raw_key` and `auth_results` never leave the mailbox object in an answer about a message (`shownMessage`), which says `has_original`, `raw_size` and `unparsed`. **Deletion** (rule S13): objects go before rows. One function deletes a message (`deleteMessage` in `workers/lib/messages.ts`: its files, its original, then its rows); emptying a place names a batch and its objects, deletes the objects, then the rows of that batch (`workers/durableObject/emptying.ts`); deleting a mailbox reads the keys of every file, every original and every arrival (`allKeys`), deletes the objects a thousand at a time, and only then empties the mailbox object. A failure leaves rows that can be deleted again, never an object no row names. **Known addresses** (ADR-0012; `workers/routes/known-addresses.ts`): completing an address is part of writing, so `GET …/known-addresses?q=` and forgetting one need `mailbox.write`, and forgetting them all `mailbox.manage`, which is audited by the mailbox and a number, never an address. The query is 1 to 64 characters, compared with `substr` and never put into a pattern; the answer is at most 8 entries of id, address and name, with no paging, total, count or date. The addresses are in the mailbox's own database, so they are deleted with it. **A person's choices** are not a mailbox's and not a manager's: see B3. **The mailbox tells the open app** (ADR-0013; `workers/routes/live.ts`, `workers/durableObject/live.ts`, `shared/live.ts`): being told that a mailbox changed is a way of reading it, so `GET …/live` is `mailbox.read` in the route table: a reader listens, and someone without a membership is told 404 whatever their instance role. **Nothing on the connection is mail:** the object sends one shape, a version and four counters, built by `liveMessage` from the list of kinds and from nothing else, at most 256 bytes; what changed is read through the ordinary routes, each authorised as before. The signal is raised by the write itself: `watch` wraps every method of the mailbox object where the class is defined, asks SQLite how many rows changed, and moves the counters the method is about (`ABOUT`; mail when it says nothing), so no caller can forget it or raise it without writing. **The object is told who by the Worker:** the route hands it a request it builds (`liveRequest`), with the person's id and the time the guard allowed it and nothing of the browser's; the object keeps the id as the connection's tag and the time as its attachment, and no session and no role. **A right that ends, ends here too:** the routes that remove a member or change a role close that person's connections in the same request, after the index is written (`closeLiveOf`, also for someone who manages the instance and has no membership: the one call reads nothing); deleting a mailbox closes them all (`purge`); and whatever the Worker did not know about ends at five minutes (B3). The app says `ping`, which the platform answers; any other message closes the connection (1008). Eight connections for a person in a mailbox, two hundred for a mailbox. Logs name the object's id and the account's id, never a message. **Outgoing mail** (ADR-0016; `workers/routes/sending.ts`, `workers/durableObject/submissions.ts`): `POST …/emails/:id/unsend` and `…/reschedule` are `mailbox.send` in the route table, like the three send routes; seeing Scheduled is `mailbox.read`. The id only looks a row up in the database of the mailbox the guard picked. **A message enters and leaves the place Scheduled only by being sent, taken back or let go:** the mailbox object's own methods refuse a waiting message (`inScheduled`) wherever one is moved, deleted, marked or labelled, and refuse Scheduled as a target, so no route and no tool can do it by another way; a deed on many conversations that names one is refused whole, and one on a conversation or a search passes over it. Deleting a mailbox takes its alarm off and deletes every row, the ones that wait among them, so nothing is sent afterwards. **Rules for incoming mail** (ADR-0008; `workers/routes/rules.ts`): in a shared mailbox a rule decides where everyone's mail goes, so seeing rules is `mailbox.read` and changing them is `mailbox.manage` in the route table: `PUT …/rules`, `POST` and `DELETE …/blocked-senders`, and `PUT …/auto-reply`, which is also marked `fresh` because it makes the mailbox send. A body is read up to 256 KiB and no further (`workers/lib/body.ts`) and held to the strict schemas of `shared/rules-schema.ts`: a key the vocabulary does not have refuses the request. A sender to block or unblock is named in the body, never in the address of the request, and with `kind: "address"` nothing but one whole address is taken, so the block a message offers never becomes a domain's. A rule's id only names a row in the database of the mailbox the guard picked. Every change is in the audit log with who, which mailbox and a number or a kind (`mailbox.rules_changed`, `mailbox.sender_blocked`, `mailbox.sender_unblocked`, `mailbox.auto_reply_changed`), never a condition, an address or the words of the reply. The rules are rows of the mailbox's own database and go with it. +- **Proof today:** `test/workerd/rules.test.ts` and `test/workerd/auto-reply.test.ts`, `auto-reply-standing.test.ts` (rules: a reader and a sender see them and change nothing; someone without a membership, whatever they manage, gets 404 on all six routes; 401 without a session, 403 from another origin; an older session is refused the automatic reply and still reads it; one mailbox's rules are not another's and its rule ids are nothing there; the limits; the audit rows carry no word of a rule; after the mailbox is deleted no rule is left; the migration is run from the release before it). `test/workerd/sending-routes.test.ts` (outgoing mail: an owner and a sender send, take back and give a new time; a reader sees Scheduled and is refused all of it; someone without a membership, whatever they manage, gets 404, nobody is served without a session or from another origin; a waiting message of another mailbox is 404; every route that changes mail refuses a waiting message with 409 `SCHEDULED` and changes nothing; nothing can be moved into Scheduled; after a mailbox is deleted no row, no object and no alarm is left and the send binding was never called); `test/workerd/original-routes.test.ts` and `test/workerd/original.test.ts` (the original: a reader is served and a non-member gets 404 on both routes, 401 without a session; a message id of another mailbox the caller is also a member of is 404; no answer of the message, list, thread, search and original routes contains `raw_key`, `auth_results` or the key itself; a sent message, a draft and old mail answer `NO_ORIGINAL`, a row whose object is gone `ORIGINAL_MISSING`; after deleting a message for good, emptying Trash and deleting the mailbox the bucket holds nothing of it, an arrival's object included; a bucket that fails leaves the rows; the migration is run from the release before it and rewrites nothing); `test/workerd/bulk.test.ts` (acting on many conversations: a reader is refused and a non-member told nothing on all three routes; a message, a label and a deed of another mailbox do not exist here; over a limit, an empty filter, both or neither scope, an unknown change, and Sent or Drafts as a target are refused with nothing changed; a filter request changes nothing, and a deed is not run without it, later than ten minutes, or after its scope grew; mail stored after the asking is never taken; undo is refused after the hour and never undoes a later change; a deleted message leaves no row in the record; the audit rows carry no word of the search) and `test/unit/bulk.test.ts` (the schema and its limits); `test/workerd/emptying.test.ts` (emptying takes Trash and Spam only, refuses a reader and tells a non-member nothing, and leaves no row or object of what was there); `test/unit/authorize.test.ts` (the whole rights matrix, the table's shape) and `test/workerd/access.test.ts`: every registered route is in the table and the table names no missing route; each mailbox route answers 404 to a signed-in non-member and to an administrator without a membership, 401 without a session, 403 to a reader where it changes anything, 403 to a sender where it manages; a crafted address is 404; an administrator can create a mailbox for someone else and then cannot open it; deletion removes mail, attachments, the index row and memberships, and a new mailbox at the same address starts empty. `test/workerd/members.test.ts`: an owner adds by address, changes and removes; a non-owner member sees the list and changes nothing; a non-member gets 404 on every member route; an administrator without a membership sees members, history and the registry but gets 404 on mail, settings, folders and deletion; their self-grant opens the mailbox and is on the record, which stays after they leave; the last owner cannot be removed or demoted by anyone; every change is refused without fresh proof; the audit rows carry the capacity. `test/workerd/access.test.ts` pins that the member routes are the only mailbox routes an administrator without a membership passes. **Labels** (ADR-0007): `test/workerd/labels.test.ts`: a reader sees labels and changes none, someone without a membership is told nothing, a label of another mailbox does not exist here, a label that is asked for and is not one finds nothing, deleting a label deletes no mail, deleting a message leaves no label row, and nobody makes, renames or removes a place; `test/unit/labels.test.ts` (ids, names). `test/workerd/known-addresses.test.ts` (known addresses: 404 on all three routes to someone without a membership and to an administrator without one, 403 to a reader, 401 without a session, 403 from another origin; a sender completes and forgets one and is refused forgetting all; an owner forgets all, on the record without an address; another mailbox's addresses never appear and its ids are nothing here; what is typed is never a pattern, also when it is longer than a pattern may be; no empty and no over-long query; never more than 8, and no way to the rest; forgetting after two years and above 5,000; deleting a sent message forgets nothing; deleting the mailbox leaves no row; the migration is run from the release before it and reads nothing back). `test/workerd/choices.test.ts` (managing is not reading: no route gives an owner or an administrator another person's choices). **The connection** (`test/workerd/live.test.ts`): an owner, a sender and a reader listen; someone without a membership and an administrator without one get 404, as does a mailbox that is not there or a crafted name; 401 without a session (and the generic loops of `test/workerd/access.test.ts` now ask it as a handshake). Removing a member closes that person's connections and no other's by the time the request has answered, and what happens next is told to the owner only; a changed role closes them and the person comes back through the guard; a refused change closes nothing; an administrator without a membership who removes a member closes them too and still cannot listen; deleting the mailbox closes every connection. After the object was put out of memory a connection is found by its tag, belongs to the same person, and is told once and closed as before. The ninth connection of a person closes their oldest; the two hundred and first is 503 and closes nobody; the object refuses a request that is not the Worker's handshake; `ping` is answered and anything else, bytes included, is closed with 1008 and tells nobody. The log lines carry opaque ids and no address, counter or word. **What is told** (`test/workerd/live-signal.test.ts`): marked content fed through every kind of write appears in no message of either tab, every message is the one shape under 256 bytes, no state is sent twice, each counter moves for exactly what it should and none for a read or a refusal; the test lists the object's methods, fails for one that is neither a known read nor known by what it is about, calls each read and fails if it changes a row, and shows a method written without knowledge of the signal raising it; the migration is run from the release before it. `pnpm e2e` `live.spec.ts`: in a real browser the frames are counters only. - **Open:** a session that ended is told for up to five minutes on a connection opened before, and the object cannot tell (B3); nothing limits how often one person opens the connection beyond the limits of a mailbox; opaque storage ids (the Durable Object and attachment keys are still named after the address and the message id; the key of an original is random and read from its row); mail that arrives while its mailbox is being deleted can still write into the emptied mailbox object; a mailbox's owners are not notified when someone who manages the instance changes its members, they see it when they look; the record is read from audit rows by address; the assistant's chat history is not purged with the mailbox. A member can walk the alphabet through the completion, a few answers at a time: it shows nothing Sent does not, except an address whose messages were deleted for good, and the route is not rate-limited (ADR-0012, accepted there). ### B5. The agent and MCP - **Crosses:** mail content into a model prompt, and tool calls from a model or an MCP client back into mailboxes. - **Invariant:** both are off unless `AGENT_ENABLED` or `MCP_ENABLED` is exactly `"true"`. They hold the caller's rights only, and less when the key says so. Neither can send or forward: the only way mail leaves is a person sending a draft in the UI. An MCP request is authenticated by its own key and never by a browser session; a mailbox a key cannot reach looks exactly like one that does not exist. Mail content given to a model is data, never instructions; the injection scan is advisory. Tests and local development never call a model. -- **Code today:** `workers/lib/features.ts` and the gates in `workers/app.ts`: the assistant's connection needs the app's own origin on a WebSocket handshake and on anything that changes (`sameOrigin`; a browser sends the cookie with a handshake from any page of the same site), then a session and the right to change mail in the mailbox it names (`mailboxDecision`). MCP (`workers/mcp/server.ts`) is stateless: `workers/app.ts` resolves `Authorization: Bearer pbk_…` to a key that is neither revoked nor expired and whose owner is still admitted (`workers/auth/keys.ts`), and a server is built for that one request. Every tool call reads the key's mailboxes joined with its owner's memberships again (`keyMailboxes`), so losing a membership or deleting a mailbox takes effect on the next call; a tool that changes anything also needs `keyAllows` (a write key and a role of owner or sender). Keys are made from the person's own memberships only (`workers/routes/keys.ts`), stored as a SHA-256 digest with a four-character hint, shown once, capped per person, optional expiry, creation and revocation audited. The handler allows only the request's own hostname as a browser Origin and sends no CORS headers. The assistant's tools (`workers/agent/tools.ts`) run with `withoutSend(env)`, an environment whose send binding refuses, so no tool can send whatever the model asks; they only save drafts. Since ADR-0016 the working send binding sits in the mailbox object, which every tool can reach, so a binding that refuses is no longer enough by itself: the same environment hands out a handle on a mailbox without the methods by which mail is sent (`SENDING_METHODS`: `submit`, `unsend`, `reschedule` and the alarm), however the handle is made. No tool sends later, sends now, takes back or changes a time: scheduling is sending. A tool reads Scheduled as it reads any place and changes nothing in it: the mailbox object itself refuses. The automatic draft (`workers/agent/auto-draft.ts`) scans the sender, the subject and the body before any of it reaches the chat model, and fails closed: only a clear NO passes. Fixed rules follow every system prompt, including a mailbox's own (`workers/agent/prompt.ts`). Every model id is in `workers/lib/models.ts`. The tools shared by both (`workers/lib/tools.ts`) contain no function that sends; MCP runs them with `withoutSend(env)` as well. **What a tool answers about a message is built from a list of named fields** (`TOOL_MESSAGE_FIELDS`, `TOOL_LINE_FIELDS`, `TOOL_FILE_FIELDS`; ADR-0015, decision 21), so a new column of the mailbox's database does not reach a model or a client by itself. No tool returns the original of a message, its text, its key, its size, whether it has one, or what the platform said about its authentication, and no tool downloads; `raw_headers` stays in the answers as before. **What a tool writes is told like any other write** (ADR-0013, decision 6): the signal is raised inside the mailbox object by the write itself, so the assistant and an MCP client can neither forget it nor raise it without writing, and nothing they wrote is on the connection. A program's key opens no connection: the route takes a session from the app's own page. The assistant's own WebSocket is not changed by that record: it is not closed when a membership ends and has no five minutes. -- **Proof today:** `test/unit/features.test.ts`; "optional features are off by default" in `test/workerd/inbound.test.ts`; `test/workerd-agent/gate.test.ts` (with both features on: a handshake from another origin, a sibling host or no origin answers 403 before the session is looked at; 401 without a session, 404 to a non-member and to an administrator without a membership, 403 to a reader, a crafted mailbox name refused, MCP answering 401 to every role's session); `test/workerd-agent/mcp.test.ts` (no key, a made-up key and a session are refused; the token is not in D1 or in the key list; a key cannot be made for a mailbox its maker is not a member of, whatever their instance role; the tool list has no send, forward or delete; out-of-scope, missing and crafted mailbox ids give one identical error; a read-only key and a reader's write key change nothing; a sender's write key saves a draft and Sent stays empty; `update_draft` refuses a message that is not a draft and saves a draft as given, without a model; no move to Sent; membership removed, key revoked, key expired and mailbox deleted each stop the key at once; answers are `no-store` with the security headers and no CORS header); `test/unit/keys.test.ts`; `test/unit/agent-no-send.test.ts` (a model that asks to send reaches no send binding, and Sent stays empty; the tools' handle on a mailbox has none of the methods that send while the mailbox's own handle has them, and both tool sets are built from that environment); `test/workerd-agent/sending.test.ts` (ADR-0016, decision 20: the tool lists are what they were and nothing in them is about sending; in the Workers runtime the guarded environment reaches neither `submit`, `unsend`, `reschedule` nor the alarm by `get`, `getByName` or the shared helper, and changes nothing; an MCP client and the assistant list and read what waits, are refused `update_draft`, `discard_draft`, every move, marking and labelling of it and Scheduled as a target, and what leaves is what the person wrote; each was seen to fail with the guard taken out); `test/unit/agent-ai.test.ts`, `agent-auto-draft.test.ts`, `agent-prompt.test.ts` and `agent-models.test.ts`, all against the fake model in `test/helpers/fake-ai.ts`. Labels through a key: `list_labels` reads, `label_email` needs a key and a membership that may change the mailbox, a label of an unreachable mailbox is refused without naming it, and no tool makes, renames or deletes a label (`test/workerd-agent/mcp.test.ts`). The assistant has the same two label tools and no more (`test/unit/agent-no-send.test.ts`: a label that is not one, a label of no mailbox and a message that is not there are each refused). The original (ADR-0015, decision 21): `test/workerd-agent/mcp.test.ts` pins the fields of `get_email` and of a list line for a message that has an original, and finds neither the key, the size, `has_original`, `unparsed`, the platform's field nor a byte of the original in the answers of `get_email`, `get_thread`, `list_emails` and `search_emails`; `test/unit/agent-no-send.test.ts` does the same for the assistant's tools, with a column added to the row that must not come through. No tool acts on many conversations (ADR-0014, decision 22): the routes of `workers/routes/bulk.ts` are reached over HTTP with a session only, and the tool lists the tests pin did not change. `test/workerd-agent/mcp.test.ts` also shows (ADR-0012) that a client's drafts teach the mailbox no address, that no tool is about known addresses or a person's choices, and that a key opens neither their routes nor any route of the API; `test/unit/known-addresses.test.ts` that no file of the assistant, of MCP or of their shared tools names them. `test/workerd-agent/live.test.ts` (ADR-0013): every tool of an MCP client and of the assistant that writes moves `mail` and is told to an open tab, every tool that reads moves nothing, marked content given to each appears in no message, both tool lists are pinned there, and a key opens no connection without an origin (403), with the app's origin (401) or in the address (401). +- **Code today:** `workers/lib/features.ts` and the gates in `workers/app.ts`: the assistant's connection needs the app's own origin on a WebSocket handshake and on anything that changes (`sameOrigin`; a browser sends the cookie with a handshake from any page of the same site), then a session and the right to change mail in the mailbox it names (`mailboxDecision`). MCP (`workers/mcp/server.ts`) is stateless: `workers/app.ts` resolves `Authorization: Bearer pbk_…` to a key that is neither revoked nor expired and whose owner is still admitted (`workers/auth/keys.ts`), and a server is built for that one request. Every tool call reads the key's mailboxes joined with its owner's memberships again (`keyMailboxes`), so losing a membership or deleting a mailbox takes effect on the next call; a tool that changes anything also needs `keyAllows` (a write key and a role of owner or sender). Keys are made from the person's own memberships only (`workers/routes/keys.ts`), stored as a SHA-256 digest with a four-character hint, shown once, capped per person, optional expiry, creation and revocation audited. The handler allows only the request's own hostname as a browser Origin and sends no CORS headers. The assistant's tools (`workers/agent/tools.ts`) run with `withoutSend(env)`, an environment whose send binding refuses, so no tool can send whatever the model asks; they only save drafts. Since ADR-0016 the working send binding sits in the mailbox object, which every tool can reach, so a binding that refuses is no longer enough by itself: the same environment hands out a handle on a mailbox without the methods by which mail is sent (`SENDING_METHODS`: `submit`, `unsend`, `reschedule` and the alarm), however the handle is made. No tool sends later, sends now, takes back or changes a time: scheduling is sending. A tool reads Scheduled as it reads any place and changes nothing in it: the mailbox object itself refuses. The automatic draft (`workers/agent/auto-draft.ts`) scans the sender, the subject and the body before any of it reaches the chat model, and fails closed: only a clear NO passes. Fixed rules follow every system prompt, including a mailbox's own (`workers/agent/prompt.ts`). Every model id is in `workers/lib/models.ts`. The tools shared by both (`workers/lib/tools.ts`) contain no function that sends; MCP runs them with `withoutSend(env)` as well. **What a tool answers about a message is built from a list of named fields** (`TOOL_MESSAGE_FIELDS`, `TOOL_LINE_FIELDS`, `TOOL_FILE_FIELDS`; ADR-0015, decision 21), so a new column of the mailbox's database does not reach a model or a client by itself. No tool returns the original of a message, its text, its key, its size, whether it has one, or what the platform said about its authentication, and no tool downloads; `raw_headers` stays in the answers as before. **What a tool writes is told like any other write** (ADR-0013, decision 6): the signal is raised inside the mailbox object by the write itself, so the assistant and an MCP client can neither forget it nor raise it without writing, and nothing they wrote is on the connection. A program's key opens no connection: the route takes a session from the app's own page. The assistant's own WebSocket is not changed by that record: it is not closed when a membership ends and has no five minutes. **The rules of a mailbox are not a tool's** (ADR-0008 says nothing of a tool, so there is none): the handle the tools get also refuses `getRules`, `setRules`, `blockSender`, `unblockSender`, `getAutoReply` and `setAutoReply`, and `beginArrival` and `fileArrival` (`RULE_METHODS`): filing an arrival is what the automatic reply answers, so a tool that could file one could make the mailbox send to an address of its choosing. +- **Proof today:** `test/workerd-agent/rules.test.ts` (no tool is about rules, blocking or an automatic reply; the guarded environment reaches none of the eight methods by `get`, `getByName` or the shared helper and changes nothing; the control: the mailbox's own handle files an arrival and it is answered; a program's key opens none of the six routes) and `test/unit/agent-no-send.test.ts`. `test/unit/features.test.ts`; "optional features are off by default" in `test/workerd/inbound.test.ts`; `test/workerd-agent/gate.test.ts` (with both features on: a handshake from another origin, a sibling host or no origin answers 403 before the session is looked at; 401 without a session, 404 to a non-member and to an administrator without a membership, 403 to a reader, a crafted mailbox name refused, MCP answering 401 to every role's session); `test/workerd-agent/mcp.test.ts` (no key, a made-up key and a session are refused; the token is not in D1 or in the key list; a key cannot be made for a mailbox its maker is not a member of, whatever their instance role; the tool list has no send, forward or delete; out-of-scope, missing and crafted mailbox ids give one identical error; a read-only key and a reader's write key change nothing; a sender's write key saves a draft and Sent stays empty; `update_draft` refuses a message that is not a draft and saves a draft as given, without a model; no move to Sent; membership removed, key revoked, key expired and mailbox deleted each stop the key at once; answers are `no-store` with the security headers and no CORS header); `test/unit/keys.test.ts`; `test/unit/agent-no-send.test.ts` (a model that asks to send reaches no send binding, and Sent stays empty; the tools' handle on a mailbox has none of the methods that send while the mailbox's own handle has them, and both tool sets are built from that environment); `test/workerd-agent/sending.test.ts` (ADR-0016, decision 20: the tool lists are what they were and nothing in them is about sending; in the Workers runtime the guarded environment reaches neither `submit`, `unsend`, `reschedule` nor the alarm by `get`, `getByName` or the shared helper, and changes nothing; an MCP client and the assistant list and read what waits, are refused `update_draft`, `discard_draft`, every move, marking and labelling of it and Scheduled as a target, and what leaves is what the person wrote; each was seen to fail with the guard taken out); `test/unit/agent-ai.test.ts`, `agent-auto-draft.test.ts`, `agent-prompt.test.ts` and `agent-models.test.ts`, all against the fake model in `test/helpers/fake-ai.ts`. Labels through a key: `list_labels` reads, `label_email` needs a key and a membership that may change the mailbox, a label of an unreachable mailbox is refused without naming it, and no tool makes, renames or deletes a label (`test/workerd-agent/mcp.test.ts`). The assistant has the same two label tools and no more (`test/unit/agent-no-send.test.ts`: a label that is not one, a label of no mailbox and a message that is not there are each refused). The original (ADR-0015, decision 21): `test/workerd-agent/mcp.test.ts` pins the fields of `get_email` and of a list line for a message that has an original, and finds neither the key, the size, `has_original`, `unparsed`, the platform's field nor a byte of the original in the answers of `get_email`, `get_thread`, `list_emails` and `search_emails`; `test/unit/agent-no-send.test.ts` does the same for the assistant's tools, with a column added to the row that must not come through. No tool acts on many conversations (ADR-0014, decision 22): the routes of `workers/routes/bulk.ts` are reached over HTTP with a session only, and the tool lists the tests pin did not change. `test/workerd-agent/mcp.test.ts` also shows (ADR-0012) that a client's drafts teach the mailbox no address, that no tool is about known addresses or a person's choices, and that a key opens neither their routes nor any route of the API; `test/unit/known-addresses.test.ts` that no file of the assistant, of MCP or of their shared tools names them. `test/workerd-agent/live.test.ts` (ADR-0013): every tool of an MCP client and of the assistant that writes moves `mail` and is told to an open tab, every tool that reads moves nothing, marked content given to each appears in no message, both tool lists are pinned there, and a key opens no connection without an origin (403), with the app's origin (401) or in the address (401). - **Open:** the assistant's connection outlives a membership that ended until it is closed from the other side, and its handshake reads the session from the cookie's copy (found while building ADR-0013, not changed: that record leaves the assistant's connection alone); MCP has keys only: OAuth 2.1 with a consent screen and per-tool grants is not built (ADR-0004); there is no per-key rate limit and no audit record per call; a key is a bearer secret, so a leaked key works until it is revoked or expires. Mail read through MCP is not scanned, so a hostile message can talk a client into moving mail to Trash or saving a draft. In chat, mail read through a tool is not scanned, so a hostile message can still make the assistant move mail to Trash or discard drafts. The assistant has not been run against a real model since its model ids changed. ### B6. The outbound sender -- **Crosses:** `From`, recipients, headers, body and attachments from a caller to the `send_email` binding, and from there to the internet under the domain's reputation. Since ADR-0016 also a time: the request says when the message leaves, up to a year ahead, and it leaves with nobody at the screen. +- **Crosses:** `From`, recipients, headers, body and attachments from a caller to the `send_email` binding, and from there to the internet under the domain's reputation. Since ADR-0016 also a time: the request says when the message leaves, up to a year ahead, and it leaves with nobody at the screen. Since ADR-0008 also a stranger's message: with the automatic reply on, mail that arrives makes the mailbox send, to an address the stranger chose. - **Invariant:** one send path. A message leaves only if `From` is an address of a mailbox the caller may send as, and the per-mailbox and per-instance caps allow it. The real binding is reachable only through the adapter. Tests and local development never send real mail. A message leaves at most once by Podbay's own doing, and the rules hold at the time of leaving, not of pressing. -- **Code today** (ADR-0016). **Sending is two steps.** A send route (`workers/lib/outgoing.ts`, for sending, answering and forwarding) checks the request (`SendEmailRequestSchema`, `validateSender`, the limits of a message, the caps for an ordinary send), stores the message in the place Scheduled with a `waiting` row in `submissions` and a time, and answers. It calls no sending service. **One function lets mail leave:** `leaveOne` in `workers/durableObject/leaving.ts`, run from the mailbox object's alarm, is the only code that reads the send binding and the only caller of the adapter (`workers/email-sender.ts`). It reads the message from the stored rows (`workers/lib/outgoing-message.ts`) and its files from the bucket; nothing of a request reaches it. **At most once:** the handover (`handOver` in `submissions.ts`) changes `waiting` to `sending` only if the row is still as it was read, counts the message against the caps in the same transaction, and is on disk before the service is called; a row that is `sending` is never handed over again by anything. No answer within 60 seconds, an error without a code, an answer without an id and a row found `sending` fifteen minutes after its attempt began are `failed` with `unknown`: the service takes no idempotency key, so a second handover would be a second message, and a person decides. **The answer decides:** `{ messageId }` is `sent`; three codes read as "not now" and are tried after 1, 5 and 15 minutes, 1 hour and 4 hours; every other code is final and brings the message back to Drafts with the code. **The rules at leaving** (decision 15), in this order: the mailbox is still in the index (else nothing leaves); the person who sent it still holds `mailbox.send` by `authorize`, and their account was not recovered since (`workers/auth/standing.ts`); `From` is still the mailbox's address; the message still fits; the caps allow one more (else it waits). A message 24 hours past its time does not leave. **The caps** (`workers/durableObject/sending.ts`) count what left, in `send_log`: a time and a kind, nothing of a message, not shortened by deleting or moving mail. **Taking back and a new time** (`workers/routes/sending.ts`) are writes in the same object that would send, so the two cannot both win; both need `mailbox.send`. **The alarm** (`workers/durableObject/alarm.ts`) is set by one function to the earliest of all times; the handler catches its own errors and always sets the next. **Logs** of a handover carry the mailbox's object id, the message's id, a state and a code, never the service's own words, which may hold an address. **Recording whom a message went to** (ADR-0012, decision 17): the mailbox records To, Cc and Bcc, except its own address, when the message has left, in `leaveOne`, once. It changes nothing that is sent and cannot fail a send: what cannot be recorded is skipped, counted and logged as a number. -- **Proof today:** `pnpm static sender` (`scripts/checks/sender.ts`: one reader of the send binding, one caller of the adapter, one caller of the handover; `test/unit/sending.test.ts` tries it against a second of each). `test/unit/sender.test.ts` (`From` must be the mailbox's own address). `test/workerd/sending.test.ts`, with a send binding of the tests that answers what it is told and counts every call: a send calls no service and the message waits in Scheduled; it leaves at its time and is in Sent with the service's id; the place and the state are held together through every change; a second alarm, three runs at once, a repeated request, a retry before its time and a row found `sending` hand nothing over again; no answer is `unknown` and never a resend; each "not now" code, each kind of final refusal, the six attempts and their times; a final failure returns the message to Drafts with its files and the reason; undo inside the window, after it, and by the state rather than the clock; send later, a new time, send now, cancel, and the limits. `test/workerd/leaving.test.ts`: each question at leaving and its reason, the 24 hours, the caps (counted in `send_log`, not freed by deleting or moving sent mail, holding a message and letting it go later in the order of the times, two messages never taking the last place), and the alarm (the earliest time, set again by every change and run, ten messages in a run, its own errors caught, set again at a wake). `test/workerd/sending-limit.test.ts` (the hour and the day in time). `test/workerd/sending-routes.test.ts` (a log line of every kind of end carries no word of the mail, no address and nothing the service said). `test/workerd/known-addresses.test.ts`: each of the three sending routes, with and without a draft, records its recipients once when the message has left and never the mailbox's own address; a message that waits, is taken back or is refused teaches nothing; with the table gone the message still leaves. `test/workerd/vitest.config.ts` sets `remoteBindings: false`, so no test can send. Each of the handover's guard, the "no answer" rule, the right at leaving and the refusal of a waiting message was taken out once and seen to fail its test. -- **Open:** what cannot be known: a handover the service took and whose answer was lost stands as `failed` with `unknown` until a person looks, and sending it again may send it twice (ADR-0016, decision 7). The per-instance cap. Delivery, bounce and complaint events, and settling an `unknown` from them. A notice for a person whose app is closed when a send fails. None of the service's refusals was seen on Cloudflare's network: they are tried with a send binding of the tests. Mail the Worker sends by itself (the automatic reply of ADR-0008, not built) leaves through the same function with the kind `auto` and must not teach the mailbox an address. Replying to all teaches every recipient, also one a stranger put in Cc (accepted in ADR-0012). +- **Code today** (ADR-0016). **Sending is two steps.** A send route (`workers/lib/outgoing.ts`, for sending, answering and forwarding) checks the request (`SendEmailRequestSchema`, `validateSender`, the limits of a message, the caps for an ordinary send), stores the message in the place Scheduled with a `waiting` row in `submissions` and a time, and answers. It calls no sending service. **One function lets mail leave:** `leaveOne` in `workers/durableObject/leaving.ts`, run from the mailbox object's alarm, is the only code that reads the send binding and the only caller of the adapter (`workers/email-sender.ts`). It reads the message from the stored rows (`workers/lib/outgoing-message.ts`) and its files from the bucket; nothing of a request reaches it. **At most once:** the handover (`handOver` in `submissions.ts`) changes `waiting` to `sending` only if the row is still as it was read, counts the message against the caps in the same transaction, and is on disk before the service is called; a row that is `sending` is never handed over again by anything. No answer within 60 seconds, an error without a code, an answer without an id and a row found `sending` fifteen minutes after its attempt began are `failed` with `unknown`: the service takes no idempotency key, so a second handover would be a second message, and a person decides. **The answer decides:** `{ messageId }` is `sent`; three codes read as "not now" and are tried after 1, 5 and 15 minutes, 1 hour and 4 hours; every other code is final and brings the message back to Drafts with the code. **The rules at leaving** (decision 15), in this order: the mailbox is still in the index (else nothing leaves); the person who sent it still holds `mailbox.send` by `authorize`, and their account was not recovered since (`workers/auth/standing.ts`); `From` is still the mailbox's address; the message still fits; the caps allow one more (else it waits). A message 24 hours past its time does not leave. **The caps** (`workers/durableObject/sending.ts`) count what left, in `send_log`: a time and a kind, nothing of a message, not shortened by deleting or moving mail. **Taking back and a new time** (`workers/routes/sending.ts`) are writes in the same object that would send, so the two cannot both win; both need `mailbox.send`. **The alarm** (`workers/durableObject/alarm.ts`) is set by one function to the earliest of all times; the handler catches its own errors and always sets the next. **Logs** of a handover carry the mailbox's object id, the message's id, a state and a code, never the service's own words, which may hold an address. **Recording whom a message went to** (ADR-0012, decision 17): the mailbox records To, Cc and Bcc, except its own address, when the message has left, in `leaveOne`, once. It changes nothing that is sent and cannot fail a send: what cannot be recorded is skipped, counted and logged as a number. **The automatic reply** (ADR-0008; `workers/durableObject/auto-reply.ts`, `replyOwed` in `shared/rules.ts`): one object for the mailbox, saved by an owner with fresh proof. Whether a reply is owed is one pure function, asked in the step that files an arrival and only for a message that was read: the reply is on and inside its dates; the message was not filed in Spam or Trash, its sender is not blocked, and neither is the envelope sender, whatever `From` says; it has no `Auto-Submitted` other than `no`; it names no list and is not bulk mail; the mailbox's address is in To or Cc; the envelope sender is one whole address, not the mailbox's own, not `MAILER-DAEMON`, `owner-…` or `…-request`; that sender was not answered in seven days (`auto_reply_log`: an address and a time); and the reply's own caps (10 in an hour, 50 in a day) and the mailbox's have room. The reply goes to the envelope sender and nobody else, and is made of the person's own subject and words: nothing of the message that arrived is read where it is built, not even its id. It is not sent there: it is taken as a message that waits (`take`) and leaves by `leaveOne` like any other, which knows it by the `Auto-Submitted` entry of its own stored header list (only the reply writes one; a message taken back to Drafts loses it), hands it over with the kind `auto`, sends `Auto-Submitted: auto-replied`, teaches the mailbox no address, and removes it instead of returning it to Drafts when it does not leave. At leaving it is asked again whether the reply is still on and inside its dates, and the standing asked is that of the person who saved it, as of the time they saved it, for `mailbox.manage`, the right saving it needs (`AUTO_REPLY_RIGHT`); a reply that does not leave for one of those, or another reason of the mailbox's, takes back its record that the sender was answered. While it waits, `unsend` and `reschedule` answer 404 for it (`mailboxOwn` in `submissions.ts`), so nobody makes it their draft or their send. The text and the HTML of the reply are taken together only when the text is the text of the HTML. Turning it off empties `auto_reply_log`. A reply that cannot be made or recorded is not made; the message that arrived is stored either way. Only mail filed in the Inbox wakes the assistant (`Filing` in `workers/durableObject/rules.ts`, `finish` in `workers/arrival.ts`). +- **Proof today:** `test/workerd/auto-reply.test.ts`, `auto-reply-standing.test.ts` (ADR-0008, with a send binding of the tests: every refusal above with a message that really arrives; the one call it makes, field by field; marked content of the incoming message in no call and in no stored row; the caps of its own and the mailbox's; no known address; a refusal and a missing answer of the service leave no draft and no second try; the person who saved it taken out of the mailbox, lowered to sender, and their account recovered; a reply turned off or past its end while it waited; a waiting reply refused to `unsend` and `reschedule` by a sender and an owner; a text and HTML that disagree; fresh proof; the message and its file stored when the record cannot be written) and `test/unit/auto-reply.test.ts`. Each guard was taken out once and seen to fail its test (`docs/status.md`, section 3). `pnpm static sender` (`scripts/checks/sender.ts`: one reader of the send binding, one caller of the adapter, one caller of the handover; `test/unit/sending.test.ts` tries it against a second of each). `test/unit/sender.test.ts` (`From` must be the mailbox's own address). `test/workerd/sending.test.ts`, with a send binding of the tests that answers what it is told and counts every call: a send calls no service and the message waits in Scheduled; it leaves at its time and is in Sent with the service's id; the place and the state are held together through every change; a second alarm, three runs at once, a repeated request, a retry before its time and a row found `sending` hand nothing over again; no answer is `unknown` and never a resend; each "not now" code, each kind of final refusal, the six attempts and their times; a final failure returns the message to Drafts with its files and the reason; undo inside the window, after it, and by the state rather than the clock; send later, a new time, send now, cancel, and the limits. `test/workerd/leaving.test.ts`: each question at leaving and its reason, the 24 hours, the caps (counted in `send_log`, not freed by deleting or moving sent mail, holding a message and letting it go later in the order of the times, two messages never taking the last place), and the alarm (the earliest time, set again by every change and run, ten messages in a run, its own errors caught, set again at a wake). `test/workerd/sending-limit.test.ts` (the hour and the day in time). `test/workerd/sending-routes.test.ts` (a log line of every kind of end carries no word of the mail, no address and nothing the service said). `test/workerd/known-addresses.test.ts`: each of the three sending routes, with and without a draft, records its recipients once when the message has left and never the mailbox's own address; a message that waits, is taken back or is refused teaches nothing; with the table gone the message still leaves. `test/workerd/vitest.config.ts` sets `remoteBindings: false`, so no test can send. Each of the handover's guard, the "no answer" rule, the right at leaving and the refusal of a waiting message was taken out once and seen to fail its test. +- **Open:** what cannot be known: a handover the service took and whose answer was lost stands as `failed` with `unknown` until a person looks, and sending it again may send it twice (ADR-0016, decision 7). The per-instance cap. Delivery, bounce and complaint events, and settling an `unknown` from them. A notice for a person whose app is closed when a send fails. None of the service's refusals was seen on Cloudflare's network: they are tried with a send binding of the tests. The automatic reply (ADR-0008) was not seen on Cloudflare's network: that the service takes `Auto-Submitted` is from its documentation. A blocked sender and a filter go by the address a message says it is from, which the sender writes; and the reply goes to the envelope sender, which a stranger can forge, so a stranger can make a mailbox with the reply on send one message in seven days to an address of their choosing, with the owner's words and nothing of theirs, up to the reply's caps (the record sends it to the envelope sender, as RFC 3834 asks). Replying to all teaches every recipient, also one a stranger put in Cc (accepted in ADR-0012). ### B7. The setup and operator tokens diff --git a/.claude/skills/podbay-testing/SKILL.md b/.claude/skills/podbay-testing/SKILL.md index 6e20aa6..0d6d518 100644 --- a/.claude/skills/podbay-testing/SKILL.md +++ b/.claude/skills/podbay-testing/SKILL.md @@ -19,7 +19,7 @@ Put a test in the lowest tier that can prove the rule. A rule about access is pr ## 2. What exists already -**Tier 3, `test/workerd/helpers.ts`:** `migrate`, `setupOwner`, `seedUser`, `seedMembership`, `signIn`, `request` (sends the app's own `Origin`), `createMailbox`, `mime` and `inbound` (a message for the `email` handler), `ageSessions` (make a session old instead of waiting), and `Browser`: a cookie-keeping client with a client address of its own, so the per-address sign-in limits do not couple tests. `enableApp`, `registerPasskey` and `passkeySignIn` do the second step and passkeys as a person's devices do. +**Tier 3, `test/workerd/helpers.ts`:** `migrate`, `setupOwner`, `seedUser`, `seedMembership`, `signIn`, `request` (sends the app's own `Origin`), `createMailbox`, `mime` and `inbound` (a message for the `email` handler), `ageSessions` (make a session old instead of waiting), and `Browser`: a cookie-keeping client with a client address of its own, so the per-address sign-in limits do not couple tests. `enableApp`, `registerPasskey` and `passkeySignIn` do the second step and passkeys as a person's devices do. `test/workerd/sending-helpers.ts` has a send binding of the tests (`fakeSender`) and `letLeave`, which runs the mailbox's alarm until nothing is due; `test/workerd/rules-helpers.ts` has one mailbox with an owner, a sender, a reader and two people without a membership, `deliver` with an envelope sender of the test's choosing, and `audited`. **Doubles, `test/helpers/`:** `authenticator.ts` (a software passkey that makes real attestations and signatures, and `totpCode`), `fake-ai.ts` (the model; no test ever calls a real one). diff --git a/.claude/skills/podbay-ui/SKILL.md b/.claude/skills/podbay-ui/SKILL.md index f9ea370..910be04 100644 --- a/.claude/skills/podbay-ui/SKILL.md +++ b/.claude/skills/podbay-ui/SKILL.md @@ -31,7 +31,7 @@ The app is a single-page app served as static assets. It shows strangers' mail i ## 3. How a mailbox behaves -The mail screens follow what a person expects from a first-class web mail client (the bar is the mail people know from Gmail and Google Workspace). The behaviour was studied on the live product and written down here in our own words; nothing of it is copied: no code, no text, no asset. These are decisions; `test/e2e/mailbox.spec.ts` holds each one, `test/e2e/writing.spec.ts` the ones about writing a message, `test/e2e/bulk.spec.ts` the ones about acting on many conversations and the order of a list, `test/e2e/original.spec.ts` the ones about the original of a message, `test/e2e/remembered.spec.ts` the ones about what is remembered beyond one browser: a person's choices and the addresses a mailbox has written to, `test/e2e/live.spec.ts` the ones about what an open tab learns without being asked, and `test/e2e/sending.spec.ts` the ones about what happens after Send. +The mail screens follow what a person expects from a first-class web mail client (the bar is the mail people know from Gmail and Google Workspace). The behaviour was studied on the live product and written down here in our own words; nothing of it is copied: no code, no text, no asset. These are decisions; `test/e2e/mailbox.spec.ts` holds each one, `test/e2e/writing.spec.ts` the ones about writing a message, `test/e2e/bulk.spec.ts` the ones about acting on many conversations and the order of a list, `test/e2e/original.spec.ts` the ones about the original of a message, `test/e2e/remembered.spec.ts` the ones about what is remembered beyond one browser: a person's choices and the addresses a mailbox has written to, `test/e2e/live.spec.ts` the ones about what an open tab learns without being asked, `test/e2e/sending.spec.ts` the ones about what happens after Send, and `test/e2e/rules.spec.ts` the ones about a mailbox's rules for incoming mail. ### The frame @@ -98,7 +98,7 @@ A message is in one place and carries any number of labels. Places are fixed; ev | A conversation is read **oldest first**. Its newest message and whatever is still unread are open, the rest are folded to one line each; the conversation's menu opens or folds all of them. A message deleted or reported from a conversation is no longer shown in it | `EmailPanel.tsx`, `ThreadMessage.tsx` | | A conversation of five messages or more keeps its middle (between the first and the last two) behind one line that says how many are there | `EmailPanel.tsx` | | Every message is as tall as it is: the conversation scrolls, never a message inside it. **Quoted text at the end of a reply is folded** behind "Show quoted text", inside the mail frame, and opens without script | `foldQuote` in `app/lib/mail-html.ts` (the renderer: load `podbay-security` before touching it) | -| **Each message has its own header and menu**: who wrote it (the name opens what can be done with the sender: write to them, find their mail, copy the address), "to" with the full details one click away, a star, Reply, and a menu: reply, reply to all, forward, delete this message, mark as unread, report spam, find messages from this sender, print, and then "Show original" and "Download message" for a message whose original is kept, or "Show headers" for one that has none. They act on that message, not on the conversation | `email-panel/MessageHeader.tsx`; `messageActions` in `EmailPanel.tsx` | +| **Each message has its own header and menu**: who wrote it (the name opens what can be done with the sender: write to them, find their mail, copy the address), "to" with the full details one click away, a star, Reply, and a menu: reply, reply to all, forward, delete this message, mark as unread, report spam, find messages from this sender, print, and then "Show original" and "Download message" for a message whose original is kept, or "Show headers" for one that has none. They act on that message, not on the conversation. For an owner of the mailbox the menu also has **"Block the sender"** (in the sender's own menu too), which asks first in the app's dialog and then sends that address's next mail to Spam, "Unblock the sender" in its place once the address is blocked, and **"Filter messages like this"**, which opens a new filter that starts with the sender (ADR-0008). Anyone else is offered neither: changing a mailbox's rules is the owner's, and the Worker decides it | `email-panel/MessageHeader.tsx`; `messageActions` in `EmailPanel.tsx`; `useSenderRules` in `app/hooks/useSenderRules.tsx` | | **The original of a message** (ADR-0015) is the bytes it arrived as. "Show original" opens them as text, the first 256 KB, and says of how much: the header block, then what follows it. It is text and only text: text nodes in one preformatted block, never markup, never the mail frame, no link; a control character, and a character that changes the direction of text or takes no room, is drawn as a mark with its code point (`U+202E`), and the block is laid out left to right whatever it holds, so a line reads in the order of its bytes. "Download message" saves all of them as `message-YYYYMMDD-xxxxxxxx.eml`, a name the app makes; before that the app says, in its own dialog, that the file holds the whole message with every attachment and that another program opens it without Podbay's protections, and it names the attachments that can do harm. Only a received message has an original, and the Worker says which (`has_original`): a sent message and mail from before originals were kept offer "Show headers" instead, which says what the list is and why there is no original. What the platform recorded about SPF, DKIM and DMARC is written as the platform's statement, in a sentence, without a tick, a colour or a word of Podbay's own, and only under "Show original"; it is drawn only when the Worker gives it (`AUTHENTICATION_SHOWN` in `shared/original.ts`, off until the live check of the record is done) | `email-panel/OriginalMessage.tsx`; `markOriginal` and `authenticationWords` in `app/lib/original-text.ts`; `app/lib/original.ts`; `email-panel/EmailPanelDialogs.tsx` (the headers); `workers/routes/original.ts` | | **A message Podbay could not read** (its structure, a text too large to keep, or a handler stopped twice) is in the inbox with the sender of the envelope, no subject and no text. Where its body would be, the app says that it could not read it and why, and offers the original to see and to save. It is never drawn in the mail frame | `email-panel/UnreadMessage.tsx`; `unparsed` in a message's answer | | Mail from a list offers **Unsubscribe** beside the sender, when the message says how in `List-Unsubscribe`. The header is the sender's, so only an `https:` page without credentials, or a `mailto:` to one address, is taken. A page is opened by the person after the app says where it leads; a message is written for the person to send. Podbay contacts nobody by itself | `app/lib/unsubscribe.ts`, `leaveList` in `EmailPanel.tsx` | @@ -138,7 +138,9 @@ A message is in one place and carries any number of labels. Places are fixed; ev | **Notifications**, when asked for and allowed by the browser, announce mail that arrives while Podbay is open in a tab: the sender and the subject, nothing of the message, and nothing for what was already there. The mailbox says when mail arrived and the app then asks once for the top of the inbox; a move, a label or anything else that is told makes it ask for nothing. Only while nothing is telling the tab does it look every half minute. Nothing is pushed to a closed app | `NewMailNotifier.tsx`; its look has a query key of its own (`newMailKey` in `app/hooks/useLive.ts`) | | Light or dark is the `data-mode` attribute on the document, set before the first paint; "as this device" follows the device while the app is open. A message keeps the colours its sender gave it | `showAppearance` in `useDisplay.ts` | | What belongs to the mailbox is saved to it with its own button, by an owner; others see it and are told who can change it: the name mail is sent under, the signature, the assistant's prompt. Labels are managed here as well as in the rail. The Mailbox tab also says that the mailbox remembers the addresses it has written to, and lets an owner have it forget them all, after the app asked (ADR-0012, decision 20) | `MailboxDetails.tsx`, `SignatureSettings.tsx`, `AssistantSettings.tsx`, `LabelSettings.tsx` | -| A setting is never shown for something the Worker does not do. Forwarding and an automatic reply have a stored shape and no behaviour, so they have no screen | The roadmap, section 4 | +| **Filters and blocked senders** is a tab of its own (ADR-0008). A filter is made and changed in one dialog: what it looks for (the sender and a recipient, each "contains" or "is exactly"; the subject; words of the message; an attachment) and what it does (where the message goes, read, a star, labels). It is listed in words, one line for each condition and each action, each a whole message of the catalog; the list has the order the filters run in, and arrows move one up or down. The dialog says that a filter acts on mail that arrives and not on mail that is here. Blocked senders are listed under the filters, an address or "Everyone at" a domain, with a field to block one and Unblock on each. Everyone who reads the mailbox sees the tab; only an owner gets its buttons | `settings/FilterSettings.tsx`, `rules/FilterDialog.tsx`; the words of a rule are pure functions in `app/lib/rule-words.ts`; `app/queries/rules.ts`; the vocabulary and limits come from `shared/rules.ts` | +| **Automatic reply** is a tab of its own (ADR-0008): on or off, a beginning and an end in this device's time zone (what travels is the instant in UTC), a subject and a message. The tab says in plain words who is never answered. Saving it is a sensitive change: it goes through `useFreshProof()`, and the Worker decides. When the person who turned it on may no longer send from the mailbox, the tab says that nothing is being answered | `settings/AutoReplySettings.tsx`; `GET` and `PUT …/auto-reply` | +| A setting is never shown for something the Worker does not do. Forwarding has no behaviour, so it has no screen | The roadmap, section 4 | ### What changes elsewhere (ADR-0013) @@ -147,7 +149,7 @@ The mailbox tells the open app that something changed, and nothing more. What ch | Behaviour | How it is built | |---|---| | **New mail, a move, a label and read state appear by themselves**, in every open tab and for every member of a shared mailbox, within about a second and without a reload. Nothing on the screen says that there is a connection, and nothing is different when there is none except the wait | `useLive` in `app/hooks/useLive.ts`, mounted once by the frame (`app/routes/mailbox.tsx`): one connection for the mailbox on screen, open while the tab is, seen or not | -| The connection carries **four counters and no mail** (`delivery`, `mail`, `labels`, `settings`). The app compares each with the one it holds and reads again what that kind can have touched: lists, searches, the places' counts and the labels for `mail` and `labels`, the mailbox for `settings`, the notifier's look for `delivery`. Never draw anything from the message itself: it has nothing to draw | `shared/live.ts` is the schema, for the object and the app; `refetchMoved` in `useLive.ts` | +| The connection carries **four counters and no mail** (`delivery`, `mail`, `labels`, `settings`). The app compares each with the one it holds and reads again what that kind can have touched: lists, searches, the places' counts and the labels for `mail` and `labels`, the mailbox and its rules for `settings`, the notifier's look for `delivery`. Never draw anything from the message itself: it has nothing to draw | `shared/live.ts` is the schema, for the object and the app; `refetchMoved` in `useLive.ts` | | **The connection is never trusted to be there.** A list asks by itself every half minute without one, as it always did, and every five minutes with one. A screen that needs to be current asks `useAskEvery(mailboxId)` for its interval and never assumes a signal | `useAskEvery` and `useLiveConnected` in `useLive.ts`; `routes/email-list.tsx` | | When it drops the app tries again after a second, then double the wait up to a minute, each time by a random part less, and from the start once a connection held for ten seconds. It says `ping` once a minute and takes ten seconds without an answer for a connection that is gone. After about four minutes it opens a new one, through the guard again, and closes the old one when the new one has spoken, so a person never sees it. A burst of messages is one refetch at once and then at most one a second | `LiveConnection` in `app/lib/live.ts`: no React, the browser handed in, so every rule is a unit test (`test/unit/live.test.ts`) | | A failed handshake tells a page nothing, so the app **does not guess why** and shows no error for it: the ordinary requests answer 401 or 404, and what the app does with those takes over. A message of a version the app does not know ends the connection for this tab, which goes on asking | `LiveConnection`; `readLiveMessage` in `shared/live.ts` | @@ -212,6 +214,9 @@ The app speaks English and Turkish. Every word a person reads or hears goes thro | A keyboard shortcut | `useShortcuts` in `app/hooks/useShortcuts.ts`; add it to `SHORTCUT_HELP` so the `?` dialog lists it | | Sending a message from anywhere, with Undo and the mailbox's own word afterwards | `useSending` in `app/hooks/useSending.ts`. Never say "sent" yourself | | Choosing a time | `SendLater.tsx` (a menu of times and a dialog with a date and time, each shown back) | +| A dialog with a form of several fields and a list that is saved whole | `rules/FilterDialog.tsx` | +| A setting of the mailbox whose save needs fresh proof | `settings/AutoReplySettings.tsx` | +| A thing said in words from data, a whole message for each part | `app/lib/rule-words.ts` | ## 6. A new screen diff --git a/AGENTS.md b/AGENTS.md index 6edec4e..16fd2b0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -48,9 +48,9 @@ curl -X POST 'http://localhost:5173/cdn-cgi/local/email?from=a@sender.test&to=he ## Layout -- `workers/` — the Worker: `app.ts` (entry, `fetch` and `email`), `index.ts` (API routes), `arrival.ts` (inbound mail: the original kept, then parsed and filed), `auth/` (Better Auth configuration, `authorize.ts`, the route table, the guard, the D1 index store, invitations and members, `keys.ts` for program keys, `fresh.ts` for fresh proof, `used-codes.ts` so an authenticator code is used once, `recovery.ts` for recovery links), `routes/` (account and setup, mailbox registry, people, keys, recovery, reply and forward, the original of a message, the connection to the open app), `durableObject/` (`MailboxDO`; `live.ts` wraps its every method, so a write tells the open app; outgoing mail waits there and leaves from its one alarm: `submissions.ts` has the states, `leaving.ts` the one function that calls the send binding, `alarm.ts` the one that sets the alarm), `lib/` (pure helpers: `inbound.ts`, `filenames.ts`, `features.ts`, `list-options.ts`, `mailbox-rpc.ts`, `secrets.ts`, `models.ts` with every Workers AI model id, `ai.ts`), `agent/` (the assistant: `tools.ts`, `auto-draft.ts`, `prompt.ts`) and `mcp/server.ts` (the MCP endpoint; its tool list is `shared/mcp-tools.ts`), both optional features. +- `workers/` — the Worker: `app.ts` (entry, `fetch` and `email`), `index.ts` (API routes), `arrival.ts` (inbound mail: the original kept, then parsed and filed), `auth/` (Better Auth configuration, `authorize.ts`, the route table, the guard, the D1 index store, invitations and members, `keys.ts` for program keys, `fresh.ts` for fresh proof, `used-codes.ts` so an authenticator code is used once, `recovery.ts` for recovery links), `routes/` (account and setup, mailbox registry, people, keys, recovery, reply and forward, the original of a message, the connection to the open app), `durableObject/` (`MailboxDO`; `live.ts` wraps its every method, so a write tells the open app; outgoing mail waits there and leaves from its one alarm: `submissions.ts` has the states, `leaving.ts` the one function that calls the send binding, `alarm.ts` the one that sets the alarm; a mailbox's rules for incoming mail run where a message is filed: `rules.ts`, and `auto-reply.ts` for the reply the mailbox sends by itself), `lib/` (pure helpers: `inbound.ts`, `filenames.ts`, `features.ts`, `list-options.ts`, `mailbox-rpc.ts`, `secrets.ts`, `models.ts` with every Workers AI model id, `ai.ts`), `agent/` (the assistant: `tools.ts`, `auto-draft.ts`, `prompt.ts`) and `mcp/server.ts` (the MCP endpoint; its tool list is `shared/mcp-tools.ts`), both optional features. - `app/` — the single-page app: `router.tsx` (the route tree), `routes/`, `components/`, `queries/` (TanStack Query), `services/api.ts`, and `lib/mail-html.ts`, the only renderer of mail HTML. -- `shared/` — code both sides import: `log.ts` (the only module that writes logs), `live.ts` (the one message a mailbox sends the open app: four counters, no mail), `html-text.ts` (text of an HTML fragment, no DOM), `security-headers.ts` (the response headers and the two content policies; `public/_headers` is generated from it), `mail-frame.ts` (the one inline script, with the hash the page's policy names), `attachment-risk.ts` (which attachments can do harm, and the type a file is served as), `mcp-tools.ts`, `fresh-proof.ts`, `choices.ts` (the schema of a person's choices; `choices-schema.ts` is its strict half, loaded by the Worker only), `known-addresses.ts`. No Node-only and no browser-only API. +- `shared/` — code both sides import: `log.ts` (the only module that writes logs), `live.ts` (the one message a mailbox sends the open app: four counters, no mail), `html-text.ts` (text of an HTML fragment, no DOM), `security-headers.ts` (the response headers and the two content policies; `public/_headers` is generated from it), `mail-frame.ts` (the one inline script, with the hash the page's policy names), `attachment-risk.ts` (which attachments can do harm, and the type a file is served as), `mcp-tools.ts`, `fresh-proof.ts`, `choices.ts` (the schema of a person's choices; `choices-schema.ts` is its strict half, loaded by the Worker only), `known-addresses.ts`, `rules.ts` (a mailbox's filters, blocked senders and automatic reply: the vocabulary, the limits and the two pure functions that decide; `rules-schema.ts` is its strict half). No Node-only and no browser-only API. - `migrations/` — D1: `0001_auth.sql` is generated by Better Auth and never edited; `0002_index.sql` is Podbay's index (roles, mailboxes, memberships, audit); `0003` to `0006` add invitations, keys, the second step (generated, like `0001`) and recovery links; `0007` adds a person's choices. Additive only. - `test/unit/` — tier 0, pure code in Node (the mail renderer runs against jsdom; the assistant runs against the fake model in `test/helpers/fake-ai.ts`). `test/workerd/` — tier 3, the Workers runtime; `test/workerd-agent/` — the same with the assistant and MCP switched on: their gates (`gate.test.ts`) and the MCP endpoint with its keys end to end (`mcp.test.ts`). `test/e2e/` — tier 6, the built app in a real browser (`pnpm e2e`): `scripts/e2e-server.ts` builds it, gives it secrets of its own and a fresh state directory and serves it with every binding local; `fixtures.ts` watches each page from outside (requests, messages, dialogs, new windows, policy violations) and `proxy.ts` is the browser's only way out, so "no request left" is a fact about the whole browser and not about what a debugger happened to see. - `scripts/` — Node-only tooling: `pins.ts`, `check-static.ts`, `checks/`. diff --git a/app/components/EmailPanel.tsx b/app/components/EmailPanel.tsx index 4f682af..d517aa2 100644 --- a/app/components/EmailPanel.tsx +++ b/app/components/EmailPanel.tsx @@ -22,6 +22,7 @@ import { LabelChips } from "~/components/LabelChip"; import { useConversationActions } from "~/hooks/useConversationActions"; import { useDisplay } from "~/hooks/useDisplay"; import { useOpenConversation } from "~/hooks/useOpenConversation"; +import { useSenderRules } from "~/hooks/useSenderRules"; import { useSending } from "~/hooks/useSending"; import { useShortcuts } from "~/hooks/useShortcuts"; import { useUIStore } from "~/hooks/useUIStore"; @@ -73,6 +74,7 @@ export default function EmailPanel({ emailId, siblings = [], inPane = false }: E const { data: currentMailbox } = useMailbox(mailboxId) as { data?: Mailbox; }; + const senderRules = useSenderRules(mailboxId, currentMailbox); const { closePanel, startCompose } = useUIStore(); const toastManager = useKumoToastManager(); const confirm = useConfirm(); @@ -406,6 +408,8 @@ export default function EmailPanel({ emailId, siblings = [], inPane = false }: E onShowOriginal: msg.has_original ? () => setOriginalOf(msg) : undefined, onDownloadOriginal: msg.has_original ? () => setSavingOf(msg) : undefined, onUnsubscribe: leaveList(msg), + // Blocking the sender and filtering mail like this change the mailbox's rules (ADR-0008). + ...senderRules.actionsFor(msg), }); const allExpanded = allMessages.every((msg) => expandedMessages.has(msg.id)); // With five messages or more, the ones between the first and the last two that are folded @@ -584,6 +588,7 @@ export default function EmailPanel({ emailId, siblings = [], inPane = false }: E setSavingOf(msg); }} /> + {senderRules.dialog} void; /** Only for mail from a list that says how to leave it. */ onUnsubscribe?: () => void; + /** Only for an owner of the mailbox (ADR-0008): mail from this sender goes to Spam. */ + onBlockSender?: () => void; + /** In place of blocking, for a sender whose address is blocked. */ + onUnblockSender?: () => void; + /** Only for an owner: opens a new filter that starts with this sender. */ + onFilterLikeThis?: () => void; } interface MessageHeaderProps { @@ -163,6 +171,16 @@ export default function MessageHeader({ > {t("Copy the address")} + {actions.onBlockSender && ( + + {t("Block the sender")} + + )} + {actions.onUnblockSender && ( + + {t("Unblock the sender")} + + )} @@ -259,7 +277,22 @@ export default function MessageHeader({ {t("Report spam")} )} + {actions.onBlockSender && ( + + {t("Block the sender")} + + )} + {actions.onUnblockSender && ( + + {t("Unblock the sender")} + + )} + {actions.onFilterLikeThis && ( + + {t("Filter messages like this")} + + )} {t("Find messages from this sender")} diff --git a/app/components/rules/FilterDialog.tsx b/app/components/rules/FilterDialog.tsx new file mode 100644 index 0000000..1712720 --- /dev/null +++ b/app/components/rules/FilterDialog.tsx @@ -0,0 +1,328 @@ +// Copyright 2026 Cloudhal and the Podbay contributors +// Licensed under the Apache 2.0 license found in the LICENSE file. + +import { Input, LayerDialog } from "@cloudflare/kumo"; +import { type FormEvent, useEffect, useState } from "react"; +import { + RULE_LIMITS, + type Rule, + type RuleActions, + type RuleConditions, + type RuleMatch, + type RulePlace, +} from "shared/rules"; +import { t } from "~/i18n"; +import { labelDot } from "~/lib/labels"; +import { useLabels } from "~/queries/labels"; +import { type RuleDraft, useSaveRules } from "~/queries/rules"; + +const NATIVE_FIELD = + "h-9 rounded-lg border border-kumo-line bg-kumo-control px-2 text-sm text-kumo-default"; + +interface Form { + fromMatch: RuleMatch; + from: string; + toMatch: RuleMatch; + to: string; + subject: string; + words: string; + hasAttachment: boolean; + place: "inbox" | RulePlace; + read: boolean; + star: boolean; + labels: string[]; +} + +function formOf(conditions: RuleConditions = {}, actions: RuleActions = {}): Form { + return { + fromMatch: conditions.from?.match ?? "contains", + from: conditions.from?.value ?? "", + toMatch: conditions.to?.match ?? "contains", + to: conditions.to?.value ?? "", + subject: conditions.subject ?? "", + words: conditions.words ?? "", + hasAttachment: conditions.hasAttachment === true, + place: actions.place ?? "inbox", + read: actions.read === true, + star: actions.star === true, + labels: actions.labels ?? [], + }; +} + +/** The rule a filled form is. A field left empty is no condition. */ +function ruleOf(form: Form): { conditions: RuleConditions; actions: RuleActions } { + const conditions: RuleConditions = {}; + if (form.from.trim() !== "") conditions.from = { match: form.fromMatch, value: form.from.trim() }; + if (form.to.trim() !== "") conditions.to = { match: form.toMatch, value: form.to.trim() }; + if (form.subject.trim() !== "") conditions.subject = form.subject.trim(); + if (form.words.trim() !== "") conditions.words = form.words.trim(); + if (form.hasAttachment) conditions.hasAttachment = true; + const actions: RuleActions = {}; + if (form.place !== "inbox") actions.place = form.place; + if (form.read) actions.read = true; + if (form.star) actions.star = true; + if (form.labels.length > 0) actions.labels = form.labels; + return { conditions, actions }; +} + +function Match({ + name, + value, + onChange, +}: { + name: string; + value: RuleMatch; + onChange: (value: RuleMatch) => void; +}) { + return ( + + ); +} + +/** + * Make a filter, or change one (ADR-0008). A filter is what the form says and nothing else: + * its conditions are plain words, compared without regard to case, and all of them must hold. + * It acts on mail that arrives from now on, never on mail that is already here. + */ +export default function FilterDialog({ + open, + onOpenChange, + mailboxId, + rules, + rule, + like, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; + mailboxId: string; + /** The filters the mailbox has now: the one that is saved joins or replaces one of them. */ + rules: readonly Rule[]; + /** The filter to change; leave out to make a new one. */ + rule?: Rule; + /** What a new filter starts with: "Filter messages like this". */ + like?: RuleConditions; +}) { + const { data: labels = [] } = useLabels(mailboxId); + const saveRules = useSaveRules(); + const [form, setForm] = useState
(formOf()); + const [error, setError] = useState(null); + const set = (change: Partial) => setForm((held) => ({ ...held, ...change })); + + // biome-ignore lint/correctness/useExhaustiveDependencies: filled once, when the dialog opens + useEffect(() => { + if (!open) return; + setForm(rule ? formOf(rule.conditions, rule.actions) : formOf(like)); + setError(null); + }, [open]); + + const made = ruleOf(form); + const noCondition = Object.keys(made.conditions).length === 0; + const noAction = Object.keys(made.actions).length === 0; + const full = rule === undefined && rules.length >= RULE_LIMITS.rules; + + async function submit(event: FormEvent) { + event.preventDefault(); + event.stopPropagation(); + if (noCondition || noAction || full) return; + setError(null); + const next: RuleDraft[] = rule + ? rules.map((one) => (one.id === rule.id ? { id: rule.id, ...made } : one)) + : [...rules, made]; + try { + await saveRules.mutateAsync({ mailboxId, rules: next }); + onOpenChange(false); + } catch { + setError(t("The filter could not be saved.")); + } + } + + const toggleLabel = (id: string, give: boolean) => + set({ labels: give ? [...form.labels, id] : form.labels.filter((one) => one !== id) }); + + return ( + + + {rule ? t("Edit filter") : t("New filter")} + + {t( + "A filter acts on mail when it arrives, not on mail that is already here. Words are compared as they are written, without regard to capitals.", + )} + + + +
+ + {t("When a message arrives and all of this is true")} + +
+ set({ fromMatch })} + /> +
+ set({ from: event.target.value })} + /> +
+
+
+ set({ toMatch })} + /> +
+ set({ to: event.target.value })} + /> +
+
+ set({ subject: event.target.value })} + /> + set({ words: event.target.value })} + /> + +
+ +
+ + {t("Do this")} + +
+ + +
+ + + {labels.length > 0 && ( +
+ + {t("Give it these labels")} + +
+ {labels.map((label) => { + const given = form.labels.includes(label.id); + return ( + + ); + })} +
+
+ )} +
+ + {(noCondition || noAction) && ( +

+ {noCondition + ? t("Say at least one thing the filter looks for.") + : t("Say at least one thing the filter does.")} +

+ )} + {full && ( +

+ {t("This mailbox has as many filters as it can hold.")} +

+ )} + {error && ( +

+ {error} +

+ )} + +
+ + + {rule ? t("Save") : t("Create filter")} + + +
+
+ ); +} diff --git a/app/components/settings/AutoReplySettings.tsx b/app/components/settings/AutoReplySettings.tsx new file mode 100644 index 0000000..82058c9 --- /dev/null +++ b/app/components/settings/AutoReplySettings.tsx @@ -0,0 +1,214 @@ +// Copyright 2026 Cloudhal and the Podbay contributors +// Licensed under the Apache 2.0 license found in the LICENSE file. + +import { Button, Input, useKumoToastManager } from "@cloudflare/kumo"; +import { type FormEvent, useEffect, useState } from "react"; +import { plainTextOf } from "shared/html-text"; +import { AUTO_REPLY, type AutoReply } from "shared/rules"; +import { useFreshProof } from "~/components/FreshProof"; +import { t } from "~/i18n"; +import { fieldValue } from "~/lib/sending-words"; +import { useAutoReply, useSaveAutoReply } from "~/queries/rules"; +import Row from "./Row"; + +const NATIVE_FIELD = + "h-9 w-full rounded-lg border border-kumo-line bg-kumo-control px-3 text-sm text-kumo-default"; + +/** An instant as the date and time field of this device shows it; empty for none. */ +const shown = (instant: string | null): string => + instant === null || Number.isNaN(Date.parse(instant)) ? "" : fieldValue(new Date(instant)); +/** What the field holds as an instant in UTC; `null` for an empty field. */ +const instantOf = (field: string): string | null => + field === "" || Number.isNaN(Date.parse(field)) ? null : new Date(field).toISOString(); + +/** + * The words the screen shows: the text of the reply, or the text of its HTML when it has only + * HTML. The server keeps the two in agreement, so what is shown is what is sent. + */ +const shownText = (reply: Pick): string => + reply.textBody ?? (reply.htmlBody === null ? "" : plainTextOf(reply.htmlBody)); + +/** + * The automatic reply of the mailbox (ADR-0008): a message the mailbox sends by itself to + * people who write to it, while it is on. It is the one way mail leaves without a person + * pressing Send, so saving it is the owner's and asks who they are; the Worker decides both. + */ +export default function AutoReplySettings({ + mailboxId, + canChange, +}: { + mailboxId: string; + /** Only an owner of the mailbox changes its automatic reply. */ + canChange: boolean; +}) { + const { data, isError } = useAutoReply(mailboxId); + const saveAutoReply = useSaveAutoReply(); + const withFreshProof = useFreshProof(); + const toasts = useKumoToastManager(); + const [enabled, setEnabled] = useState(false); + const [from, setFrom] = useState(""); + const [until, setUntil] = useState(""); + const [subject, setSubject] = useState(""); + const [text, setText] = useState(""); + const [error, setError] = useState(null); + + // Filled when the reply arrives, and again when it is saved. + useEffect(() => { + if (!data) return; + setEnabled(data.isEnabled); + setFrom(shown(data.fromDate)); + setUntil(shown(data.toDate)); + setSubject(data.subject ?? ""); + setText(shownText(data)); + }, [data]); + + const backwards = from !== "" && until !== "" && new Date(until) <= new Date(from); + const empty = enabled && text.trim() === "" && !data?.htmlBody; + + async function save(event: FormEvent) { + event.preventDefault(); + setError(null); + if (backwards || empty) return; + const reply: AutoReply = { + isEnabled: enabled, + fromDate: instantOf(from), + toDate: instantOf(until), + subject: subject.trim() === "" ? null : subject.trim(), + textBody: text.trim() === "" ? null : text, + // A body written elsewhere as HTML is kept as long as its text, which is what this screen + // shows, was not changed here. The server takes the two together only when they agree. + htmlBody: data?.htmlBody && text === shownText(data) ? data.htmlBody : null, + }; + try { + await withFreshProof(() => saveAutoReply.mutateAsync({ mailboxId, reply })); + toasts.add({ + title: enabled ? t("The automatic reply is on") : t("The automatic reply is off"), + }); + } catch { + setError(t("The automatic reply could not be saved.")); + } + } + + if (isError) { + return ( +

+ {t("The automatic reply could not be loaded.")} +

+ ); + } + + return ( +
+

+ {t( + "While it is on, this mailbox answers people who write to it, by itself and in its own name. A sender is answered once in seven days. Lists, automatic mail, mail in Spam and mail that does not name this address are never answered, and nothing of the message that arrived is in the answer.", + )} +

+ {data?.stopped && ( +

+ {t( + "It is on, but nothing is being answered: the person who turned it on is no longer an owner of this mailbox, or their account was recovered since. An owner saves it again to turn it on.", + )} +

+ )} +
+ + + + +
+
+ + setFrom(event.target.value)} + /> +
+
+ + setUntil(event.target.value)} + /> +
+
+ {backwards && ( +

+ {t("The end must be after the beginning.")} +

+ )} +
+ +
+
+ setSubject(event.target.value)} + /> +
+
+
+ +