@joelincc/mailroom 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +207 -2
  3. package/SECURITY.md +11 -0
  4. package/bin/mailroom.mjs +26 -0
  5. package/dist/broadcast/config.js +79 -0
  6. package/dist/broadcast/explain.js +50 -0
  7. package/dist/cli/args.js +29 -0
  8. package/dist/cli/errors.js +31 -0
  9. package/dist/cli/main.js +475 -0
  10. package/dist/compose/clicks.js +29 -0
  11. package/dist/compose/compose.js +224 -0
  12. package/dist/compose/index.js +8 -0
  13. package/dist/compose/markdown.js +637 -0
  14. package/dist/compose/personalize.js +123 -0
  15. package/dist/compose/preflight.js +251 -0
  16. package/dist/compose/preview.js +41 -0
  17. package/dist/compose/render.js +136 -0
  18. package/dist/compose/template.js +118 -0
  19. package/docs/broadcast.md +199 -0
  20. package/docs/composing.md +135 -0
  21. package/docs/desk-commands.md +52 -0
  22. package/docs/export.md +51 -0
  23. package/docs/lists.md +66 -0
  24. package/docs/security-model.md +82 -0
  25. package/docs/ses.md +116 -0
  26. package/docs/unsubscribe.md +117 -0
  27. package/migrations/0001_init.sql +42 -0
  28. package/migrations/0002_tier.sql +4 -0
  29. package/migrations/0003_rate.sql +9 -0
  30. package/migrations/0004_last_error.sql +2 -0
  31. package/migrations/0005_lists.sql +41 -0
  32. package/migrations/0006_broadcast.sql +154 -0
  33. package/migrations/0007_unsubscribe.sql +12 -0
  34. package/package.json +64 -4
  35. package/src/alert.ts +123 -0
  36. package/src/aws-sigv4.ts +100 -0
  37. package/src/broadcast/audience.ts +96 -0
  38. package/src/broadcast/campaigns.ts +339 -0
  39. package/src/broadcast/config.ts +136 -0
  40. package/src/broadcast/dispatch.ts +766 -0
  41. package/src/broadcast/events.ts +107 -0
  42. package/src/broadcast/explain.ts +73 -0
  43. package/src/broadcast/freeze.ts +93 -0
  44. package/src/broadcast/index.ts +21 -0
  45. package/src/broadcast/postman.ts +229 -0
  46. package/src/broadcast/reconcile.ts +120 -0
  47. package/src/broadcast/routes.ts +181 -0
  48. package/src/broadcast/ses.ts +181 -0
  49. package/src/broadcast/stats.ts +59 -0
  50. package/src/broadcast/status.ts +60 -0
  51. package/src/broadcast/test-send.ts +88 -0
  52. package/src/broadcast/warmup.ts +150 -0
  53. package/src/broadcast/worker.ts +177 -0
  54. package/src/cf-events.ts +84 -0
  55. package/src/cli/args.ts +27 -0
  56. package/src/cli/errors.ts +33 -0
  57. package/src/cli/main.ts +466 -0
  58. package/src/compose/clicks.ts +45 -0
  59. package/src/compose/compose.ts +257 -0
  60. package/src/compose/index.ts +8 -0
  61. package/src/compose/markdown.ts +624 -0
  62. package/src/compose/personalize.ts +130 -0
  63. package/src/compose/preflight.ts +250 -0
  64. package/src/compose/preview.ts +58 -0
  65. package/src/compose/render.ts +153 -0
  66. package/src/compose/template.ts +197 -0
  67. package/src/core.ts +328 -0
  68. package/src/export.ts +184 -0
  69. package/src/feedback.ts +111 -0
  70. package/src/http.ts +17 -0
  71. package/src/index.ts +378 -0
  72. package/src/list-routes.ts +42 -0
  73. package/src/lists.ts +370 -0
  74. package/src/ses-events.ts +426 -0
  75. package/src/transport.ts +193 -0
  76. package/src/unsub-wiring.ts +64 -0
  77. package/src/unsub.ts +499 -0
  78. package/src/webhook.ts +101 -0
  79. package/wrangler.example.jsonc +56 -0
package/docs/lists.md ADDED
@@ -0,0 +1,66 @@
1
+ # Newsletter lists
2
+
3
+ Lists are the source of truth for "who gets the newsletter". They live in the same D1 database as the ledger
4
+ (migration `0005_lists.sql`: `contacts`, `lists`, `list_members`). Sending is a separate step and is not covered here.
5
+
6
+ ## Model
7
+
8
+ - `contacts`: one row per address, shared by every list. Addresses are trimmed and lower-cased.
9
+ - `lists`: one row per newsletter (`weekly`, `promo`, ...). Create one with `PUT /v1/lists/{id}`.
10
+ - `list_members`: a person's state on one list: `subscribed` or `unsubscribed`, where they came from, an optional engagement group.
11
+ - `suppressions` (existing): global refusals. It only holds hard bounces, complaints and "no newsletters at all".
12
+ **Unsubscribing from one list is recorded in `list_members` only**, so someone on two lists can leave one and keep the other.
13
+
14
+ ## Rules
15
+
16
+ 1. **Subscribe** is refused (`blocked`) when the address has any suppression (`hard_bounce`, `complaint`, `unsubscribe`).
17
+ Lift one deliberately with `POST /v1/unsuppress`.
18
+ 2. **Re-subscribe**: a person who unsubscribed can subscribe again. Only the person's own subscribe action does this:
19
+ status goes back to `subscribed`, the unsubscribe fields are cleared and `source` records the new entry point.
20
+ 3. **Imports and syncs never turn `unsubscribed` into `subscribed`.** They can only make someone "not sent to".
21
+ 4. Unsubscribing twice is harmless: the first timestamp and source are kept.
22
+ 5. New members get `segment = '新進觀察群'` ("new, unobserved") until a real group is written in.
23
+
24
+ ## Internal interface (service binding)
25
+
26
+ ```ts
27
+ env.MAILROOM.listSubscribe({ list, email, source, consentVersion, name? }) // 'subscribed' | 'already' | 'blocked'
28
+ env.MAILROOM.listUnsubscribe({ list, email, source }) // 'unsubscribed' | 'not_member'
29
+ env.MAILROOM.listStatus({ list, email }) // 'subscribed' | 'unsubscribed' | 'not_found' | 'blocked'
30
+ env.MAILROOM.listMembers({ list, status?, cursor?, limit? }) // { members, next }, 1,000 per page
31
+ ```
32
+
33
+ Each `listMembers` row has `suppressed` (the address is on the global suppression list, same meaning as `listStatus` = `blocked`) and `unsubReason`.
34
+ Bad input returns `{ status: 'rejected', reason }` (`bad_email`, `bad_list`, `unknown_list`, `bad_source`, ...) instead of throwing.
35
+ `listStatus` reports `blocked` for a subscribed member who is on the global suppression list; an unsubscribed member always shows `unsubscribed`.
36
+ `source` for unsubscribe is one of `link`, `one_click`, `mailto`, `api`, `import`, `import-removed`, `complaint` (default `api`).
37
+
38
+ ## Admin endpoints (bearer `DRILL_TOKEN`, shared admin rate limit)
39
+
40
+ | Request | Body | Notes |
41
+ |---|---|---|
42
+ | `PUT /v1/lists/{id}` | `{ name, fromAddr?, replyTo?, welcomeTemplate? }` | create or update |
43
+ | `POST /v1/lists/{id}/segments` | `{ items: [{ email, segment, segmentLabel? }] }` | up to 5,000 per call; updates existing members only; idempotent |
44
+ | `POST /v1/lists/{id}/import` | `{ importedFrom, rows, dryRun?, expected? }` | up to 2,000 rows per call; see below |
45
+
46
+ ## Importing
47
+
48
+ Each row is `{ email, status, name?, subscribedAt?, unsubscribedAt?, source?, consentVersion? }` with `status` one of:
49
+
50
+ | Status | Where it lands |
51
+ |---|---|
52
+ | `subscribed` | `list_members` subscribed. Skipped if the address is suppressed (`blocked`) or already unsubscribed (`kept_unsubscribed`). |
53
+ | `unsubscribed` | `list_members` unsubscribed, `unsub_source = 'import'`. |
54
+ | `removed` | `list_members` unsubscribed, `unsub_source = 'import-removed'`. Not sent to, but **not** added to the global suppression list. |
55
+ | `bounced` | `suppressions` `hard_bounce`, `source = 'import'`. No list membership. |
56
+ | `complained` | `suppressions` `complaint`, `source = 'import'`. No list membership. |
57
+
58
+ - The whole call is validated first. Any invalid row (bad address, unknown status) or an `expected` count that does not match
59
+ the de-duplicated input rejects the call with nothing written. `expected` is `{ subscribed: n, ... }` and is for reconciliation against the source system.
60
+ - The same address twice in one call: the most restrictive status wins (`complained` > `bounced` > `removed` > `unsubscribed` > `subscribed`); counted in `duplicates`.
61
+ - Re-running the same import changes nothing and creates no duplicates.
62
+ - `dryRun: true` returns the same report without writing.
63
+ - Large imports: split into calls of at most 2,000 rows; each call is idempotent, so a failed call can simply be repeated.
64
+ The report's `outcomes` are for that call only; add them up across calls to reconcile.
65
+
66
+ A leaked `DRILL_TOKEN` can also add, remove and re-label list members through these endpoints (it cannot read recipients' mail or the ledger). Treat it as described in the README.
@@ -0,0 +1,82 @@
1
+ # Security model and data handling
2
+
3
+ Read this before you deploy mailroom or connect an app to it. It says what mailroom trusts, what it stores,
4
+ what each secret can do if it leaks, and what you should harden.
5
+
6
+ ## Trust boundaries
7
+
8
+ | Caller | How it is identified | What it can do |
9
+ |---|---|---|
10
+ | A Worker on the same Cloudflare account (service binding) | Not authenticated — being bound **is** the trust. `site` is whatever the caller says. | `send`, `lookup` (full ledger row, including recipient), `drill`. No rate limit. |
11
+ | An app elsewhere (`POST /v1/send`) | Its own `HTTP_KEY_*`. The key decides `site`; a `site` in the body is ignored. | Send mail from the addresses allowed for it, to any recipient, with any content, within its rate limits. |
12
+ | The operator (`/v1/drill`, `/v1/lookup`, `/v1/report`, `/v1/unsuppress`) | `DRILL_TOKEN` | Send drill mail to any address (fixed text plus a caller-chosen `site` label), read status fields and per-domain counts, lift suppressions — and, as a side effect, find out whether a given address is on the suppression list. 20 requests/min, 200/day in total. |
13
+ | Resend (`POST /webhooks/resend`) | Svix signature, 5-minute window, event id de-duplicated | Update delivery status, add hard bounces and complaints to the suppression list. |
14
+ | Cloudflare Email Sending events | Arrive on your own queue | Same as above. |
15
+ | Amazon SES via SNS (`POST /webhooks/ses`) | SNS signature (SignatureVersion 2 by default) with a certificate fetched only from `sns.<region>.amazonaws.com`, topic ARN allowlist, 7-day window, SNS message id de-duplicated. Off (404) unless `SES_SNS_TOPIC_ARNS` is set. | Same as above, plus confirm its own SNS subscription. See [ses.md](ses.md). |
16
+ | Everyone else | — | `GET /` returns a plain-text health check. `POST /webhooks/resend` answers 401, 411 or 413. Everything else is 404. |
17
+
18
+ Mailroom does **not** check that a recipient opted in, does not scan message content, and does not sanitise HTML.
19
+ Whoever holds a client key can send anything, to anyone, from that client's allowed sender addresses.
20
+ The rate limits cap the damage; they do not prevent it.
21
+
22
+ ## What is stored, and for how long
23
+
24
+ One D1 database, four tables:
25
+
26
+ | Table | Personal data | Notes |
27
+ |---|---|---|
28
+ | `messages` | recipient address, sender address, **subject line**; also whatever your apps put in the idempotency key and `kind`, and the provider's error code | Message bodies are never stored. Subjects often contain names or order details, and keys often contain a user id or address — treat the ledger as personal data. |
29
+ | `suppressions` | recipient address, bounce detail text from the provider | Kept until you lift the suppression. |
30
+ | `webhook_events` | none (event id, type, time) | |
31
+ | `rate_counters` | none | Rows older than two days are pruned opportunistically, on a small share of HTTP requests. |
32
+
33
+ **Retention is off until you turn it on.** Set `LEDGER_RETENTION_DAYS` (a positive integer, e.g. `180`) and add a cron trigger: each run then deletes `messages` rows and `webhook_events` rows older than that (up to 5,000 of each per run; rows still `sending` are kept). `suppressions` are never deleted automatically — they are a defence, not a log; remove entries with `/v1/unsuppress`. Without the variable or without a cron trigger nothing is deleted. You can also clean by hand, for example:
34
+
35
+ ```bash
36
+ npx wrangler d1 execute mailroom --remote --command \
37
+ "DELETE FROM messages WHERE created_at < strftime('%Y-%m-%dT%H:%M:%fZ','now','-180 days'); DELETE FROM webhook_events WHERE received_at < strftime('%Y-%m-%dT%H:%M:%fZ','now','-30 days')"
38
+ ```
39
+
40
+ Deleting a `messages` row also forgets its idempotency key, so only delete rows older than any retry window your apps use.
41
+ To erase one person on request, delete their rows from `messages` and (if they ask to receive mail again) `suppressions`.
42
+ Keeping a suppression row for someone who complained is usually the right thing to do — it is what stops you emailing them again.
43
+
44
+ Mailroom's own log lines contain site names, message kinds, provider error codes and counts — not recipients,
45
+ subjects, bodies or secrets. Please keep it that way in pull requests. Two things are outside that promise:
46
+ your apps choose `kind` and the idempotency key, so don't put personal data in `kind`; and Cloudflare's request
47
+ logs record request URLs, including the `site` and `key` query parameters of `/v1/lookup`.
48
+
49
+ Your providers (Resend, SMTP2GO, Cloudflare) receive the full message and keep their own logs under their own retention rules.
50
+
51
+ ## If a secret leaks
52
+
53
+ | Secret | Worst case | What to do |
54
+ |---|---|---|
55
+ | `HTTP_KEY_<SITE>` | Someone sends mail as that app — phishing from your real domain — up to `HTTP_RATE_PER_MIN` / `HTTP_DAILY_LIMIT`. A `suppressed` reply also tells them an address bounced or complained, whichever of your apps it happened in. | Replace the secret (`wrangler secret put`), update the app, then check `/v1/report?days=1` for sends you don't recognise. |
56
+ | `DRILL_TOKEN` | Up to 200 drill emails a day to arbitrary addresses, suppressions lifted, per-domain statistics read, and addresses probed for "is this on the suppression list". Recipient lists, subjects and bodies are not exposed. | Replace or delete the secret. With it deleted, the operator paths return 404. |
57
+ | `RESEND_API_KEY`, `SMTP2GO_API_KEY` | Full sending access at the provider, outside mailroom and outside its limits. | Revoke at the provider first, then replace the secret. |
58
+ | `RESEND_WEBHOOK_SECRET` | Forged bounce and complaint events: an attacker can suppress any address, so real mail to it stops. | Rotate the signing secret in Resend, replace the secret, review recent `suppressions` rows. |
59
+
60
+ ## Hardening checklist
61
+
62
+ - [ ] Every secret is a Cloudflare **Secret**, never a plain variable, never in `wrangler.jsonc`. `wrangler.jsonc` and `.dev.vars` stay git-ignored.
63
+ - [ ] Each HTTP client has its own key, and an `HTTP_FROM` entry listing exactly the sender addresses it may use. A client without an entry is refused (403 `from_allowlist_required`), and if `HTTP_FROM` is set but isn't valid JSON `/v1/send` refuses everything with a 500.
64
+ - [ ] `HTTP_RATE_PER_MIN` and `HTTP_DAILY_LIMIT` are set to what your busiest client really needs, not left at the defaults.
65
+ - [ ] Keys are long and random (`openssl rand -hex 32`). There is no lockout on wrong keys; length is the defence.
66
+ - [ ] `DRILL_TOKEN` is set only while you are running a drill or lifting a suppression, or is rotated regularly.
67
+ - [ ] Provider keys are scoped to the sending domain and to "send only" where the provider allows it.
68
+ - [ ] If you don't use webhooks or HTTP clients, `workers_dev` is `false`. If you do, consider a WAF rate-limiting rule in front of `/v1/*`.
69
+ - [ ] SPF, DKIM and DMARC are set up for every sender domain.
70
+ - [ ] You pin the mailroom version you deploy and read the diff before upgrading. Nothing here updates itself.
71
+ - [ ] `LEDGER_RETENTION_DAYS` is set and a cron trigger exists (see above), or you have your own retention job.
72
+ - [ ] After every deploy you run the drill from the README.
73
+
74
+ ## Known limits
75
+
76
+ - A provider timeout can produce one duplicate email: the design prefers a duplicate over a lost message.
77
+ - Any Worker with a service binding can read ledger rows of other sites if it knows their keys. Don't bind Workers you don't trust.
78
+ - The suppression list is shared by all sites on the deployment, and Resend's webhook covers the whole Resend account.
79
+ - Rate limits count requests, not delivered messages, and apply only to the HTTP endpoints.
80
+ - `/v1/report` groups by recipient **domain**. For people who use a personal domain, that is close to identifying them.
81
+
82
+ Found something that isn't on this list? See [SECURITY.md](../SECURITY.md) — report it privately.
package/docs/ses.md ADDED
@@ -0,0 +1,116 @@
1
+ # Amazon SES as the newsletter postman
2
+
3
+ The broadcast engine can hand newsletter mail to Amazon SES (API v2) and read SES delivery events back. Code:
4
+ `src/broadcast/ses.ts` (sending and limits), `src/ses-events.ts` (events), `src/aws-sigv4.ts` (request signing, no AWS SDK,
5
+ no extra dependency). SES is used for newsletters only; transactional mail keeps its own providers and sending domain.
6
+
7
+ Everything below uses example values (`mail.example.com`, `us-east-1`, account `123456789012`).
8
+
9
+ ## What it does
10
+
11
+ - **Send** — `SendEmail` with Simple content, UTF-8 subject and bodies, the two unsubscribe headers
12
+ (`List-Unsubscribe`, `List-Unsubscribe-Post: List-Unsubscribe=One-Click`) produced by `render`, a configuration set,
13
+ and two message tags (`campaign`, `contact`) so events can be matched back to the issue and the person. Display names
14
+ outside ASCII are RFC 2047 encoded. A custom MAIL FROM domain is a property of the SES identity, not of the request:
15
+ set it on the identity and it applies to every message.
16
+ - **Limits** — `GetAccount` once per `limitsRefreshMinutes`: `MaxSendRate` (per second), `Max24HourSend`,
17
+ `SentLast24Hours` and `EnforcementStatus`. The 24-hour quota is rolling, so today's cap is at most "already sent today
18
+ + what SES says is left". If sending is disabled or the status is not `HEALTHY`, the engine stops handing over mail.
19
+ - **Events** — configuration set → SNS topic → HTTPS subscription → `POST /webhooks/ses`.
20
+
21
+ ## Error mapping
22
+
23
+ SES has no idempotency key, so the postman only reports "not sent" when SES gave a definite answer:
24
+
25
+ | SES answer | Postman result | What the engine does |
26
+ |---|---|---|
27
+ | 200 with `MessageId` | ok | ledger row `sent` |
28
+ | 429, `TooManyRequestsException`, `Throttling` (rate) | `throttled` | that mail retries in 30 s, the next minute releases half |
29
+ | `Throttling` "Daily message quota exceeded" | `daily_quota` | no more releases today (`daily_limit`), resumes tomorrow |
30
+ | `AccountSuspendedException`, `SendingPausedException`, `MailFromDomainNotVerifiedException`, `NotFoundException` (configuration set), `RequestExpired` (clock), any 403 (keys, permissions) | `account_paused` | issue paused: every mail would fail the same way |
31
+ | other 4xx (`MessageRejected`, `BadRequestException`, e.g. an unverified recipient in the sandbox) | `permanent` | that recipient `failed` |
32
+ | 5xx, timeout, network error, 200 without `MessageId` | throws | recipient marked `uncertain`, never re-sent automatically |
33
+
34
+ ## Events
35
+
36
+ Every request to `/webhooks/ses` is verified before anything is read from it
37
+ ([AWS: verifying SNS message signatures](https://docs.aws.amazon.com/sns/latest/dg/sns-verify-signature-of-message.html)):
38
+
39
+ 1. `TopicArn` must be in `SES_SNS_TOPIC_ARNS` and in `SES_REGION`.
40
+ 2. `SigningCertURL` must be `https://sns.<SES_REGION>.amazonaws.com/SimpleNotificationService-….pem` — no other host,
41
+ port, user info or query. The certificate is fetched over HTTPS, cached for an hour, and must be within its validity
42
+ period.
43
+ 3. The signature is checked over the documented string to sign. `SignatureVersion 2` (SHA-256) only, unless
44
+ `SES_SNS_ALLOW_SHA1 = "true"`. Set the topic's signature version to 2.
45
+ 4. `Timestamp` older than 7 days or more than 15 minutes in the future is refused. Inside that window a replay is
46
+ ignored because the SNS `MessageId` is recorded in `webhook_events` (shared with the other providers).
47
+
48
+ A subscription confirmation is accepted only after the same checks, and only if `SubscribeURL` is the same SNS host
49
+ with `Action=ConfirmSubscription` and the same topic. Unsubscribe confirmations are logged and ignored.
50
+
51
+ Notifications are normalised to provider events (one per recipient) and handed to `ingestEvent`:
52
+
53
+ | SES `eventType` | Event | Feedback |
54
+ |---|---|---|
55
+ | `Send` | `send` | — |
56
+ | `Delivery` | `delivery` | ends a transient-bounce streak |
57
+ | `Bounce`, `bounceType: Permanent` (any subtype) | `bounce` / `Permanent` | global suppression `hard_bounce` |
58
+ | `Bounce`, `Transient` / `MailboxFull` | `bounce` / `Transient`, cause `mailbox` | counts toward the streak (3 issues → `hard_bounce`) |
59
+ | `Bounce`, `Transient` / `MessageTooLarge`, `ContentRejected`, `AttachmentRejected` | cause `content` | not counted |
60
+ | `Bounce`, `Transient` / `General`, `CustomTimeoutExceeded`; `Undetermined` | no cause | not counted |
61
+ | `Complaint` | `complaint` | global suppression `complaint`, unsubscribed from every list |
62
+ | `Complaint` with feedback type `not-spam` | — | ignored (a correction, not a complaint) |
63
+ | `Reject`, `Rendering Failure` | `reject` | — |
64
+ | `DeliveryDelay` | `delay` | — |
65
+ | `Open`, `Click`, `Subscription` | — | ignored (opens and clicks are tracked by the engine itself) |
66
+
67
+ Only events from `SES_CONFIGURATION_SET` (the `ses:configuration-set` tag) are used. A recipient named in an event only
68
+ counts if it was a recipient of the original message (`mail.destination`); an event that names a different address (for
69
+ example the target of an automatic forward) is recorded nowhere and changes nothing. An event that names no recipient at
70
+ all is attributed to the message's single recipient.
71
+
72
+ Bounces with subtype `OnAccountSuppressionList` (and the tenant / email-validation variants) and complaints with
73
+ `complaintSubType: OnAccountSuppressionList` mean SES did not send the message because the address is already on the
74
+ SES account-level suppression list. They are recorded as `reject` events (so they do not count toward bounce or complaint rates)
75
+ and do not touch mailroom's suppression list or list memberships. If you lift a suppression in mailroom (`/v1/unsuppress`), remove the address from the SES account-level
76
+ list too, or SES will keep dropping its newsletter mail.
77
+
78
+ `Throttling` "Daily message quota exceeded" stops releases for the rest of the local day (`daily_limit`), like the
79
+ engine's own cap; it does not pause the issue. Five permanent rejections in a row with nothing delivered in between
80
+ (`permanentStreak`) pause the issue: that is almost always a configuration problem, not five bad addresses.
81
+
82
+ Only the commercial AWS partition is supported (`amazonaws.com`); certificate URLs on other partitions are refused.
83
+
84
+ ## Setup
85
+
86
+ AWS side (one region):
87
+
88
+ 1. Verify the sending domain as an SES identity (Easy DKIM) and set a custom MAIL FROM subdomain on it.
89
+ 2. IAM user for the Worker with only `ses:SendEmail` on the identity and the configuration set, and `ses:GetAccount`.
90
+ 3. SNS topic (standard), signature version 2. Subscribe `https://<your worker>/webhooks/ses` (HTTPS protocol, raw
91
+ message delivery **off**). The endpoint confirms the subscription itself.
92
+ 4. Configuration set with an SNS event destination for Send, Delivery, Bounce, Complaint, Reject, Rendering Failure
93
+ and Delivery Delay, pointing at that topic.
94
+ 5. Account-level suppression list on for bounces and complaints (optional but recommended).
95
+
96
+ Worker:
97
+
98
+ ```jsonc
99
+ "vars": {
100
+ "MARKETING_DOMAIN": "mail.example.com",
101
+ "NEWSLETTER_POSTMAN": "ses",
102
+ "SES_REGION": "us-east-1",
103
+ "SES_CONFIGURATION_SET": "newsletter-events",
104
+ "SES_SNS_TOPIC_ARNS": "arn:aws:sns:us-east-1:123456789012:newsletter-events"
105
+ }
106
+ // Secrets: SES_ACCESS_KEY_ID, SES_SECRET_ACCESS_KEY
107
+ ```
108
+
109
+ Without `SES_SNS_TOPIC_ARNS`, `SES_REGION` and `SES_CONFIGURATION_SET`, `/webhooks/ses` answers 404. Without all four `SES_*` sending values,
110
+ `NEWSLETTER_POSTMAN = "ses"` disables broadcasting (and logs why) rather than sending without events.
111
+
112
+ ## Testing in the SES sandbox
113
+
114
+ The sandbox only delivers to verified addresses and to the SES mailbox simulator (local parts
115
+ `success`, `bounce`, `complaint`, `ooto`, `suppressionlist` at the simulator domain listed in the SES documentation). Simulator mail does not count toward your
116
+ bounce and complaint rates. A newsletter list used for sandbox tests should contain only those addresses.
@@ -0,0 +1,117 @@
1
+ # Unsubscribe, bounces and complaints
2
+
3
+ Every newsletter carries a one-click unsubscribe. This module issues the unsubscribe token, serves the page and endpoint,
4
+ accepts unsubscribe-by-email, and turns bounce and complaint events into suppressions. It does not send anything and does not
5
+ talk to any mail provider: events arrive already normalised (see "Feeding events in").
6
+
7
+ ## The token
8
+
9
+ One token per recipient per list (optionally tagged with the issue it came from). Format: `1.<list>.<contact>.<issue or ->.<signature>`.
10
+
11
+ - Signed with HMAC-SHA256. It holds no email address and **has no expiry** (people unsubscribe from old emails).
12
+ - Changing the list, the contact or the issue invalidates the signature. Only one spelling of a signature is accepted.
13
+ - `UNSUB_TOKEN_SECRET` (a Secret, at least 16 characters) signs and verifies. To rotate it, put the old value in
14
+ `UNSUB_TOKEN_SECRET_PREVIOUS` (comma-separated if several): old tokens keep verifying, new ones are signed with the new key.
15
+ Remove the old value after a transition period (13 months covers a year of old emails).
16
+
17
+ ## Links and headers for a send
18
+
19
+ ```ts
20
+ import { unsubscribeLinks, unsubSecrets } from '@joelincc/mailroom/unsub';
21
+
22
+ const links = await unsubscribeLinks(
23
+ unsubSecrets(env.UNSUB_TOKEN_SECRET, env.UNSUB_TOKEN_SECRET_PREVIOUS),
24
+ { baseUrl: 'https://u.example.com', mailtoAddress: 'unsubscribe@mail.example.com' },
25
+ { list: 'weekly', contactId: 42, campaign: 'weekly-7' },
26
+ );
27
+ links.url // https://u.example.com/u/<token> → compose's `unsubscribe_url`
28
+ links.mailto // mailto:unsubscribe@mail.example.com?subject=<token> → `unsubscribe_mailto`
29
+ links.headers // { 'List-Unsubscribe': '<url>, <mailto>', 'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click' }
30
+ ```
31
+
32
+ Over the service binding: `env.MAILROOM.unsubscribeLinks({ list, email, campaign? })` (needs `UNSUB_BASE_URL`, optional `UNSUB_MAILTO`).
33
+ `baseUrl` must be `https`. Use a domain you control, not a shared `workers.dev` hostname.
34
+
35
+ ## Endpoints (served by the Worker's `fetch`)
36
+
37
+ | Request | What it does |
38
+ |---|---|
39
+ | `GET /u/{token}` | Confirmation page with an optional reason. **Writes nothing**: corporate mail scanners prefetch links. |
40
+ | `POST /u/{token}` | Unsubscribes. The page button posts `reason=...`; mailbox providers post `List-Unsubscribe=One-Click` (RFC 8058). Repeating it returns the same success page and keeps the first timestamp and source. |
41
+ | `POST /u/{token}/resubscribe` | "Pressed by mistake": restores the subscription with the same token, within 30 days, only for self-service unsubscribes (not complaints, imports or API removals), and not for suppressed addresses. |
42
+
43
+ - The POST body may be urlencoded or multipart (RFC 8058 allows both) and is read as a stream, capped at 8 KB (413 above that).
44
+ - An invalid token returns `404` with a generic page and no detail. A database failure returns `503` (providers retry one-click).
45
+ - Pages send `Cache-Control: no-store`, `Referrer-Policy: no-referrer`, a strict CSP and `noindex`; they run no script and load nothing external.
46
+ - Unsubscribing affects **only that list** (`list_members`); it never touches other lists or the global suppression list.
47
+ - Reasons: `too_many`, `not_relevant`, `never_subscribed`, `other` (stored in `list_members.unsub_reason`). There is no "send me fewer" option.
48
+
49
+ ### Page text
50
+
51
+ The engine ships neutral English. Override any field with `UNSUB_PAGE` (a JSON object; only the fields you set change; `{list}` becomes the list name):
52
+
53
+ ```json
54
+ { "lang": "en", "confirmTitle": "Leave {list}?", "confirmButton": "Yes, unsubscribe", "reasons": { "other": "Another reason" }, "css": "body{max-width:40rem}" }
55
+ ```
56
+
57
+ Fields: `lang`, `confirmTitle`, `confirmBody`, `confirmButton`, `reasonLegend`, `reasons`, `doneTitle`, `doneBody`, `resubscribeLead`, `resubscribeButton`,
58
+ `resubscribedTitle`, `resubscribedBody`, `resubscribeFailedTitle`, `resubscribeFailedBody`, `invalidTitle`, `invalidBody`, `retryTitle`, `retryBody`, `css`.
59
+
60
+ ## Unsubscribe by email
61
+
62
+ Route `unsubscribe@your-mail-domain` (Cloudflare Email Routing) to the Worker. Its `email()` handler looks for a token in the **subject**
63
+ and unsubscribes (`unsub_source = 'mailto'`). It does not reply (no mail loops) and does not read the body. An encoded subject (`=?UTF-8?B?...?=` or `?Q?`) is decoded before the token is looked for.
64
+
65
+ ### When an unsubscribe does not go through
66
+
67
+ A reader who wrote in has clearly asked to stop, so these three cases raise an alert instead of disappearing:
68
+
69
+ | Case | Alert `event` | What else happens |
70
+ |---|---|---|
71
+ | Mail without a token | `unsub_mail_no_token` | accepted; a person handles it |
72
+ | Token fails verification | `unsub_token_invalid` | page returns 404. From the web page only tokens of the right shape (a plausible token with a bad signature) alert; random strings typed into the URL are only logged |
73
+ | Database write failed while handling a mail | `unsub_write_failed` | the mail is **rejected** with `setReject` (permanent SMTP rejection carrying a short "use the link instead" text), so the sender is told it did not work |
74
+
75
+ The alert is a plain webhook, not tied to any service: `POST` JSON `{ event, at, from?, subject?, token?, via?, text, content }` to `UNSUB_ALERT_WEBHOOK`
76
+ (https only; optional `UNSUB_ALERT_TOKEN` is sent as a Bearer token; 5-second timeout; a failing webhook never breaks request handling).
77
+ `token` is the full token and `claims` (`list`, `contactId`, `campaign`) is read from it when its shape is right, so a person can tell who it was. Control characters are stripped from `from`, `subject` and `token`; web-page alerts are capped at 20 per minute and mail alerts at 60 per minute per Worker instance (separate budgets, so noise typed into the web page never hides a real unsubscribe mail; the rest are only logged). **`unsub_write_failed` is exempt from the budget** (a lost one can mean mail to someone who asked to stop). When a window dropped alerts, one summary alert `unsub_alerts_suppressed` (`suppressed`: how many) is sent when the window ends: by the next alert, or by the cron (`flushUnsubAlerts`). The counter lives in one Worker instance's memory, so the summary is best effort (a cron run in another instance may not see it); every alert is still written to the log individually. `text` and `content` hold the same one-line summary so common chat webhooks work through a small relay.
78
+
79
+ **If `UNSUB_ALERT_WEBHOOK` is not set**, nothing is lost silently: the same payload is written to the Worker log (`console.error`, visible only to the account owner; the log carries only the first 8 characters of the token plus `claims`, since a full token can unsubscribe that person),
80
+ and a warning is logged once per isolate (and on each scheduled run).
81
+
82
+ Why `setReject` and not `throw`: the Cloudflare docs only state that `setReject()` is a permanent SMTP error; they do not say what the sender sees when `email()` throws, so the documented call is used.
83
+
84
+ ## Bounces and complaints
85
+
86
+ `applyFeedback(db, event, options?)` (in `src/feedback.ts`, exported as `@joelincc/mailroom/feedback`) is the only place that decides what an event does:
87
+
88
+ | Event | Effect |
89
+ |---|---|
90
+ | `bounce` / `permanent` | `suppressions` `hard_bounce`. Blocks **every** stream, including sign-in notices. List membership is left alone. |
91
+ | `complaint` | `suppressions` `complaint` (blocks every stream) **and** every list the person is on becomes `unsubscribed` with `unsub_source = 'complaint'` (earlier self-unsubscribes keep their own time and source). |
92
+ | `bounce` / `transient` | Not blocked. Only `cause: 'mailbox'` bounces (mailbox full, receiving server temporarily down, recipient-side throttling) are counted: one row per (address, issue) in `bounce_streaks`, the same issue twice counts once. **Three different issues in a row** (no delivery in between) → treated as a hard bounce (`detail = transient_streak:3`). `cause: 'content'` (content or attachment rejected, message too large) says nothing about the mailbox and is **not** counted; a missing `cause` or a missing issue id is not counted either. |
93
+ | `delivery` | Clears the address's transient streak. |
94
+
95
+ Everything is idempotent: the same event twice leaves the same state. Lifting a suppression stays a manual act (`POST /v1/unsuppress`).
96
+
97
+ ### Feeding events in
98
+
99
+ The provider layer (SNS verification, Resend webhooks, a fake provider in tests) must verify authenticity and de-duplicate, then call
100
+ `applyFeedback` once per recipient with an already normalised event:
101
+
102
+ ```ts
103
+ await applyFeedback(db, { type: 'bounce', kind: 'permanent', email, source: 'ses', detail: 'NoEmail' });
104
+ await applyFeedback(db, { type: 'bounce', kind: 'transient', email, campaign: 'weekly-7', cause: 'mailbox', source: 'ses' });
105
+ await applyFeedback(db, { type: 'complaint', email, source: 'ses' });
106
+ await applyFeedback(db, { type: 'delivery', email });
107
+ ```
108
+
109
+ Mapping for SES transient bounces: `General` and `MailboxFull` → `cause: 'mailbox'`; `ContentRejected`, `AttachmentRejected` and `MessageTooLarge` → `cause: 'content'`.
110
+
111
+ The existing Resend webhook (`webhook.ts`) and Cloudflare event consumer (`cf-events.ts`) already go through `applyFeedback` for hard bounces and complaints, so a complaint from any provider also unsubscribes the person from every list. Their transient bounces and delivery events are not wired in yet (they carry no issue id).
112
+
113
+ It returns `hard_bounce`, `complaint`, `transient_counted`, `transient_promoted`, `transient_no_campaign`, `transient_not_counted`, `delivery` or `rejected` (bad address or unknown type).
114
+
115
+ ## Migration
116
+
117
+ `0007_unsubscribe.sql`: `list_members.unsub_reason` and the `bounce_streaks` table. Nothing changes for existing sends.
@@ -0,0 +1,42 @@
1
+ -- Ledger: one row per message. Message bodies are never stored — only who it went to, who sent it, which provider carried it, and the outcome.
2
+ CREATE TABLE messages (
3
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
4
+ -- stream: 'transactional' = notifications (open); 'marketing' = newsletters (not implemented yet, always rejected)
5
+ stream TEXT NOT NULL CHECK (stream IN ('transactional', 'marketing')),
6
+ site TEXT NOT NULL, -- which client app sent it, e.g. billing
7
+ dedupe_key TEXT NOT NULL, -- idempotency key: one send per (site, key); also forwarded to Resend as Idempotency-Key
8
+ kind TEXT, -- the client's own message type, e.g. approval_needed, digest, invite
9
+ to_email TEXT NOT NULL, -- always lower-case
10
+ from_addr TEXT NOT NULL,
11
+ subject TEXT NOT NULL,
12
+ status TEXT NOT NULL CHECK (status IN ('sending', 'sent', 'failed', 'suppressed')),
13
+ route TEXT, -- resend / smtp2go / cloudflare
14
+ provider_id TEXT, -- message id returned by the provider (used to match bounce webhooks back to this row)
15
+ error TEXT,
16
+ attempts INTEGER NOT NULL DEFAULT 1,
17
+ last_event TEXT, -- provider feedback: delivered / bounced / complained / failed
18
+ created_at TEXT NOT NULL,
19
+ updated_at TEXT NOT NULL,
20
+ sent_at TEXT,
21
+ UNIQUE (site, dedupe_key)
22
+ );
23
+ CREATE INDEX messages_to ON messages (to_email, created_at);
24
+ CREATE INDEX messages_provider ON messages (provider_id);
25
+ CREATE INDEX messages_created ON messages (created_at);
26
+
27
+ -- Suppression list, one row per (email, reason). hard_bounce and complaint block every stream; unsubscribe only blocks marketing.
28
+ CREATE TABLE suppressions (
29
+ email TEXT NOT NULL,
30
+ reason TEXT NOT NULL CHECK (reason IN ('hard_bounce', 'complaint', 'unsubscribe')),
31
+ source TEXT NOT NULL, -- resend-webhook / cloudflare-event / manual / import
32
+ detail TEXT,
33
+ created_at TEXT NOT NULL,
34
+ PRIMARY KEY (email, reason)
35
+ );
36
+
37
+ -- Webhook de-duplication: a provider re-delivering the same event (same svix-id) is processed once.
38
+ CREATE TABLE webhook_events (
39
+ id TEXT PRIMARY KEY,
40
+ type TEXT NOT NULL,
41
+ received_at TEXT NOT NULL
42
+ );
@@ -0,0 +1,4 @@
1
+ -- Transactional stream split into two tiers: 'notify' = must-deliver (sign-in, invites, payments); 'remind' = service reminders, sent from a separate domain.
2
+ -- Rows created before this migration are all 'notify'. route gains one more value: cloudflare (Cloudflare Email Sending).
3
+ ALTER TABLE messages ADD COLUMN tier TEXT NOT NULL DEFAULT 'notify' CHECK (tier IN ('notify', 'remind'));
4
+ CREATE INDEX messages_tier ON messages (tier, created_at);
@@ -0,0 +1,9 @@
1
+ -- Rate counters for the public HTTP entry point (clients holding an API key): one row per client per time window.
2
+ -- Incremented and read back in a single statement (atomic), so concurrent requests cannot overshoot the limit.
3
+ -- win examples: m:2026-01-01T10:05 (per minute), d:2026-01-01 (per UTC day).
4
+ CREATE TABLE rate_counters (
5
+ site TEXT NOT NULL,
6
+ win TEXT NOT NULL,
7
+ n INTEGER NOT NULL,
8
+ PRIMARY KEY (site, win)
9
+ );
@@ -0,0 +1,2 @@
1
+ -- Keep the previous failure reason after a retry succeeds: when a failed row is claimed again, its error is copied to last_error before error is cleared.
2
+ ALTER TABLE messages ADD COLUMN last_error TEXT;
@@ -0,0 +1,41 @@
1
+ -- Newsletter lists. One contact row per address (shared by every list); one list_members row per (list, contact).
2
+ -- Per-list unsubscribe lives in list_members. The global suppressions table only holds hard bounces, complaints and "no newsletters at all".
3
+ CREATE TABLE contacts (
4
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
5
+ email TEXT NOT NULL UNIQUE, -- always lower-case, trimmed
6
+ name TEXT,
7
+ attrs TEXT, -- JSON: personalisation fields
8
+ created_at TEXT NOT NULL,
9
+ updated_at TEXT NOT NULL
10
+ );
11
+
12
+ CREATE TABLE lists (
13
+ id TEXT PRIMARY KEY, -- e.g. weekly
14
+ name TEXT NOT NULL,
15
+ from_addr TEXT,
16
+ reply_to TEXT,
17
+ welcome_template TEXT,
18
+ created_at TEXT NOT NULL
19
+ );
20
+
21
+ CREATE TABLE list_members (
22
+ list_id TEXT NOT NULL REFERENCES lists (id),
23
+ contact_id INTEGER NOT NULL REFERENCES contacts (id),
24
+ status TEXT NOT NULL CHECK (status IN ('subscribed', 'unsubscribed')),
25
+ subscribed_at TEXT,
26
+ unsubscribed_at TEXT,
27
+ unsub_source TEXT, -- link / one_click / api / import / import-removed / complaint
28
+ source TEXT, -- which entry point the person came in through (free text, set by the caller)
29
+ consent_version TEXT,
30
+ segment TEXT, -- engagement group, copied in from the analytics side; the engine never recomputes it
31
+ segment_label TEXT,
32
+ segment_at TEXT,
33
+ imported_from TEXT,
34
+ last_open_at TEXT,
35
+ last_click_at TEXT,
36
+ updated_at TEXT NOT NULL,
37
+ PRIMARY KEY (list_id, contact_id)
38
+ );
39
+ CREATE INDEX list_members_contact ON list_members (contact_id);
40
+ CREATE INDEX list_members_status ON list_members (list_id, status, contact_id);
41
+ CREATE INDEX list_members_segment ON list_members (list_id, segment);