@joelincc/mailroom 0.1.0 → 0.3.1
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.
- package/README.md +54 -8
- package/SECURITY.md +1 -1
- package/bin/mailroom.mjs +26 -0
- package/dist/broadcast/config.js +79 -0
- package/dist/broadcast/explain.js +50 -0
- package/dist/cli/args.js +29 -0
- package/dist/cli/errors.js +37 -0
- package/dist/cli/main.js +533 -0
- package/dist/compose/clicks.js +29 -0
- package/dist/compose/compose.js +275 -0
- package/dist/compose/index.js +8 -0
- package/dist/compose/markdown.js +1197 -0
- package/dist/compose/personalize.js +123 -0
- package/dist/compose/preflight.js +251 -0
- package/dist/compose/preview.js +41 -0
- package/dist/compose/render.js +141 -0
- package/dist/compose/template.js +118 -0
- package/docs/broadcast.md +199 -0
- package/docs/composing.md +156 -0
- package/docs/desk-commands.md +52 -0
- package/docs/export.md +52 -0
- package/docs/lists.md +68 -0
- package/docs/security-model.md +6 -4
- package/docs/ses.md +116 -0
- package/docs/tracking.md +102 -0
- package/docs/unsubscribe.md +124 -0
- package/docs/welcome.md +72 -0
- package/migrations/0004_last_error.sql +2 -0
- package/migrations/0005_lists.sql +41 -0
- package/migrations/0006_broadcast.sql +154 -0
- package/migrations/0007_unsubscribe.sql +12 -0
- package/migrations/0008_tracking.sql +5 -0
- package/migrations/0009_welcome.sql +17 -0
- package/package.json +21 -3
- package/src/alert.ts +123 -0
- package/src/aws-sigv4.ts +100 -0
- package/src/broadcast/audience.ts +96 -0
- package/src/broadcast/campaigns.ts +352 -0
- package/src/broadcast/config.ts +136 -0
- package/src/broadcast/dispatch.ts +779 -0
- package/src/broadcast/events.ts +110 -0
- package/src/broadcast/explain.ts +73 -0
- package/src/broadcast/freeze.ts +93 -0
- package/src/broadcast/index.ts +21 -0
- package/src/broadcast/postman.ts +229 -0
- package/src/broadcast/reconcile.ts +120 -0
- package/src/broadcast/routes.ts +181 -0
- package/src/broadcast/ses.ts +181 -0
- package/src/broadcast/stats.ts +59 -0
- package/src/broadcast/status.ts +60 -0
- package/src/broadcast/test-send.ts +88 -0
- package/src/broadcast/warmup.ts +150 -0
- package/src/broadcast/worker.ts +218 -0
- package/src/cf-events.ts +4 -3
- package/src/cli/args.ts +27 -0
- package/src/cli/errors.ts +39 -0
- package/src/cli/main.ts +515 -0
- package/src/compose/clicks.ts +45 -0
- package/src/compose/compose.ts +297 -0
- package/src/compose/index.ts +8 -0
- package/src/compose/markdown.ts +1173 -0
- package/src/compose/personalize.ts +130 -0
- package/src/compose/preflight.ts +250 -0
- package/src/compose/preview.ts +58 -0
- package/src/compose/render.ts +158 -0
- package/src/compose/template.ts +197 -0
- package/src/core.ts +45 -2
- package/src/export.ts +184 -0
- package/src/feedback.ts +128 -0
- package/src/http.ts +17 -0
- package/src/index.ts +146 -32
- package/src/list-routes.ts +55 -0
- package/src/lists.ts +381 -0
- package/src/ses-events.ts +426 -0
- package/src/track.ts +409 -0
- package/src/unsub-wiring.ts +64 -0
- package/src/unsub.ts +499 -0
- package/src/webhook.ts +5 -3
- package/src/welcome.ts +257 -0
- package/wrangler.example.jsonc +16 -2
package/docs/lists.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
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 about transactional mail and "no newsletters at all" (which is also what a complaint about a newsletter records).
|
|
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? }) // { status: 'subscribed', firstTime } | { status: '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
|
+
`firstTime` is `true` when the address was never a member of that list before (`false` after an unsubscribe and re-subscribe). A first-time subscribe can trigger the list's welcome mail, see [welcome.md](welcome.md).
|
|
34
|
+
Each `listMembers` row has `suppressed` (the address is on the global suppression list, same meaning as `listStatus` = `blocked`) and `unsubReason`.
|
|
35
|
+
Bad input returns `{ status: 'rejected', reason }` (`bad_email`, `bad_list`, `unknown_list`, `bad_source`, ...) instead of throwing.
|
|
36
|
+
`listStatus` reports `blocked` for a subscribed member who is on the global suppression list; an unsubscribed member always shows `unsubscribed`.
|
|
37
|
+
`source` for unsubscribe is one of `link`, `one_click`, `mailto`, `api`, `import`, `import-removed`, `complaint` (default `api`).
|
|
38
|
+
|
|
39
|
+
## Admin endpoints (bearer `DRILL_TOKEN`, shared admin rate limit)
|
|
40
|
+
|
|
41
|
+
| Request | Body | Notes |
|
|
42
|
+
|---|---|---|
|
|
43
|
+
| `PUT /v1/lists/{id}` | `{ name, fromAddr?, replyTo?, welcomeTemplate? }` | create or update |
|
|
44
|
+
| `POST /v1/lists/{id}/segments` | `{ items: [{ email, segment, segmentLabel? }] }` | up to 5,000 per call; updates existing members only; idempotent |
|
|
45
|
+
| `PUT` / `GET /v1/lists/{id}/welcome` | `{ subject, from, replyTo?, html, text, webUrl, enabled }` | the welcome mail ([welcome.md](welcome.md)); needs `MARKETING_DOMAIN` |
|
|
46
|
+
| `POST /v1/lists/{id}/import` | `{ importedFrom, rows, dryRun?, expected? }` | up to 2,000 rows per call; see below |
|
|
47
|
+
|
|
48
|
+
## Importing
|
|
49
|
+
|
|
50
|
+
Each row is `{ email, status, name?, subscribedAt?, unsubscribedAt?, source?, consentVersion? }` with `status` one of:
|
|
51
|
+
|
|
52
|
+
| Status | Where it lands |
|
|
53
|
+
|---|---|
|
|
54
|
+
| `subscribed` | `list_members` subscribed. Skipped if the address is suppressed (`blocked`) or already unsubscribed (`kept_unsubscribed`). |
|
|
55
|
+
| `unsubscribed` | `list_members` unsubscribed, `unsub_source = 'import'`. |
|
|
56
|
+
| `removed` | `list_members` unsubscribed, `unsub_source = 'import-removed'`. Not sent to, but **not** added to the global suppression list. |
|
|
57
|
+
| `bounced` | `suppressions` `hard_bounce`, `source = 'import'`. No list membership. |
|
|
58
|
+
| `complained` | `suppressions` `complaint`, `source = 'import'`. No list membership. |
|
|
59
|
+
|
|
60
|
+
- The whole call is validated first. Any invalid row (bad address, unknown status) or an `expected` count that does not match
|
|
61
|
+
the de-duplicated input rejects the call with nothing written. `expected` is `{ subscribed: n, ... }` and is for reconciliation against the source system.
|
|
62
|
+
- The same address twice in one call: the most restrictive status wins (`complained` > `bounced` > `removed` > `unsubscribed` > `subscribed`); counted in `duplicates`.
|
|
63
|
+
- Re-running the same import changes nothing and creates no duplicates.
|
|
64
|
+
- `dryRun: true` returns the same report without writing.
|
|
65
|
+
- Large imports: split into calls of at most 2,000 rows; each call is idempotent, so a failed call can simply be repeated.
|
|
66
|
+
The report's `outcomes` are for that call only; add them up across calls to reconcile.
|
|
67
|
+
|
|
68
|
+
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.
|
package/docs/security-model.md
CHANGED
|
@@ -12,6 +12,8 @@ what each secret can do if it leaks, and what you should harden.
|
|
|
12
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
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
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
|
+
| Anyone holding a tracking link (`/c/…`, `/o/….gif` on the `TRACK_BASE_URL` host) | HMAC-signed token (issue, contact id, link number) | Be redirected to a link stored with that issue, and add a click/open event for that contact id. Forged tokens get the same 404 as unknown ones, without a database read. See [tracking.md](tracking.md). |
|
|
15
17
|
| Everyone else | — | `GET /` returns a plain-text health check. `POST /webhooks/resend` answers 401, 411 or 413. Everything else is 404. |
|
|
16
18
|
|
|
17
19
|
Mailroom does **not** check that a recipient opted in, does not scan message content, and does not sanitise HTML.
|
|
@@ -29,8 +31,7 @@ One D1 database, four tables:
|
|
|
29
31
|
| `webhook_events` | none (event id, type, time) | |
|
|
30
32
|
| `rate_counters` | none | Rows older than two days are pruned opportunistically, on a small share of HTTP requests. |
|
|
31
33
|
|
|
32
|
-
**
|
|
33
|
-
period that fits your privacy obligations and delete older rows yourself, for example monthly:
|
|
34
|
+
**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
|
|
|
35
36
|
```bash
|
|
36
37
|
npx wrangler d1 execute mailroom --remote --command \
|
|
@@ -55,12 +56,13 @@ Your providers (Resend, SMTP2GO, Cloudflare) receive the full message and keep t
|
|
|
55
56
|
| `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
57
|
| `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
58
|
| `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. |
|
|
59
|
+
| `TRACK_TOKEN_SECRET` | Forged click and open events for any issue and contact id (inflated statistics, `last_open_at`/`last_click_at` touched). Redirects still only go to links stored with each issue; no addresses are exposed. | Set the old value as `TRACK_TOKEN_SECRET_PREVIOUS` only if links in already-sent mail must keep working, put a new secret, and treat open/click numbers since the leak as unreliable. |
|
|
58
60
|
| `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
61
|
|
|
60
62
|
## Hardening checklist
|
|
61
63
|
|
|
62
64
|
- [ ] 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. (
|
|
65
|
+
- [ ] 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
66
|
- [ ] `HTTP_RATE_PER_MIN` and `HTTP_DAILY_LIMIT` are set to what your busiest client really needs, not left at the defaults.
|
|
65
67
|
- [ ] Keys are long and random (`openssl rand -hex 32`). There is no lockout on wrong keys; length is the defence.
|
|
66
68
|
- [ ] `DRILL_TOKEN` is set only while you are running a drill or lifting a suppression, or is rotated regularly.
|
|
@@ -68,7 +70,7 @@ Your providers (Resend, SMTP2GO, Cloudflare) receive the full message and keep t
|
|
|
68
70
|
- [ ] 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
71
|
- [ ] SPF, DKIM and DMARC are set up for every sender domain.
|
|
70
72
|
- [ ] You pin the mailroom version you deploy and read the diff before upgrading. Nothing here updates itself.
|
|
71
|
-
- [ ]
|
|
73
|
+
- [ ] `LEDGER_RETENTION_DAYS` is set and a cron trigger exists (see above), or you have your own retention job.
|
|
72
74
|
- [ ] After every deploy you run the drill from the README.
|
|
73
75
|
|
|
74
76
|
## Known limits
|
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` | newsletters stop (suppression `unsubscribe`, detail `complaint`), unsubscribed from every list; transactional mail is not blocked (see unsubscribe.md) |
|
|
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.
|
package/docs/tracking.md
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# Click and open tracking
|
|
2
|
+
|
|
3
|
+
The engine tracks clicks and opens itself; it does not use the email provider's tracking. That keeps the numbers comparable if
|
|
4
|
+
the provider changes, lets you use your own tracking host, and writes everything into the same `events` table that the
|
|
5
|
+
analytics export reads (`docs/export.md`).
|
|
6
|
+
|
|
7
|
+
## Setup
|
|
8
|
+
|
|
9
|
+
| Setting | What it does |
|
|
10
|
+
|---|---|
|
|
11
|
+
| `TRACK_BASE_URL` | the tracking origin, e.g. `https://t.example.com` (https, no path). Route that host to the Worker. Use the same value as `trackBase` when composing. |
|
|
12
|
+
| `TRACK_TOKEN_SECRET` | Secret, at least 16 characters. Signs the per-recipient link and pixel tokens. |
|
|
13
|
+
| `TRACK_TOKEN_SECRET_PREVIOUS` | optional, comma-separated: old secrets still accepted during a rotation (never used to sign; if the current secret is missing or too short, tracking is off rather than falling back to an old one). |
|
|
14
|
+
| `TRACK_CONFIG` | optional JSON, only the fields you want to change (see below). |
|
|
15
|
+
|
|
16
|
+
Without `TRACK_BASE_URL` and a secret, the endpoints do not exist (other routes handle the request as before). Content composed
|
|
17
|
+
with `trackBase` cannot be sent without both, or when its tracking links are not under `TRACK_BASE_URL`: rendering fails and the
|
|
18
|
+
issue pauses (`render_error`) instead of sending links that would not work. Link destinations are stored normalised
|
|
19
|
+
(`new URL(url).href`: non-ASCII paths percent-encoded), because a redirect header can only carry ASCII. Issues composed without `trackBase` are sent untracked as before.
|
|
20
|
+
|
|
21
|
+
The desk command `create` stores the issue's link table (`links`, from `compose()`) with the issue. `saveDraft` refuses content
|
|
22
|
+
that uses `{{c:N}}` without a link table entry for every N (`links_missing`), and the link table is part of the content hash, so
|
|
23
|
+
changing where a link goes requires a new approval.
|
|
24
|
+
|
|
25
|
+
## Endpoints
|
|
26
|
+
|
|
27
|
+
| Request | Response |
|
|
28
|
+
|---|---|
|
|
29
|
+
| `GET` / `HEAD /c/{token}` | `302` to link N of that issue; records a `click` |
|
|
30
|
+
| `GET` / `HEAD /o/{token}.gif` | a 1×1 transparent GIF, always (also for invalid tokens); records an `open` when the token is valid and the request is a `GET` |
|
|
31
|
+
|
|
32
|
+
Responses carry `cache-control: no-store` and `referrer-policy: no-referrer`.
|
|
33
|
+
|
|
34
|
+
### Why it cannot be used as an open redirect, or to look up readers
|
|
35
|
+
|
|
36
|
+
- A token holds only `kind | issue | contact id | link number` and a 128-bit HMAC-SHA-256 signature. **The destination is not in
|
|
37
|
+
the token.** The redirect looks up link N in the issue's stored link table, so it can only lead to a URL that is in that issue.
|
|
38
|
+
- Tokens are verified before the database is touched. A forged or altered token, an unknown issue and an unknown link number all
|
|
39
|
+
get the same `404` with the same body, so the endpoint does not reveal which issues or contact ids exist. The pixel answers
|
|
40
|
+
the same GIF either way.
|
|
41
|
+
- Events carry the issue and contact id, never the address. Anything shaped like an address in `detail` is scrubbed.
|
|
42
|
+
- Contact id `0` is a test mail: it redirects and records nothing.
|
|
43
|
+
- If reading the link table fails, the answer is `503` (try again), never a redirect somewhere else.
|
|
44
|
+
|
|
45
|
+
### Speed and failure
|
|
46
|
+
|
|
47
|
+
The redirect needs one read (the issue's link table, cached per Worker instance for 5 minutes). Writing the event happens after
|
|
48
|
+
the response (`waitUntil`); if the write fails it is logged and the reader is redirected anyway.
|
|
49
|
+
|
|
50
|
+
## Event rules
|
|
51
|
+
|
|
52
|
+
| Event | `provider_event_id` (dedupe) | `detail` |
|
|
53
|
+
|---|---|---|
|
|
54
|
+
| click | `self:c:{issue}:{contact}:{link}:{window}` — one per link per `clickDedupeSeconds` (default 60) | `url`, `linkIndex`, `asn`, `ua` (first 200 chars), `suspect` / `scannerRule` when marked |
|
|
55
|
+
| open | `self:o:{issue}:{contact}:{p|h}:{window}` — one per `openDedupeSeconds` (default 3600), prefetch and non-prefetch counted separately | `prefetch: true` when detected, `asn`, `ua` |
|
|
56
|
+
|
|
57
|
+
The window is a fixed time bucket, so two clicks a second apart can still land in two buckets near a boundary. Non-suspect clicks
|
|
58
|
+
update `list_members.last_click_at`; non-prefetch opens update `last_open_at`.
|
|
59
|
+
|
|
60
|
+
### Scanner clicks (`detail.suspect = "scanner"`)
|
|
61
|
+
|
|
62
|
+
Marked, never deleted; leave them out when counting clicks. A click is marked when:
|
|
63
|
+
|
|
64
|
+
| `scannerRule` | Rule |
|
|
65
|
+
|---|---|
|
|
66
|
+
| `burst` | the message got clicks on 3 or more different links within 60 seconds of being sent (`detectScannerClicks`; `scannerWindowMs`, `scannerMinLinks`). All clicks of that message inside the window are marked. |
|
|
67
|
+
| `head` | the request was a `HEAD` (link checkers; people's browsers use `GET`). |
|
|
68
|
+
| `asn` | the request came from a network listed in `scannerAsns` (default: none). |
|
|
69
|
+
|
|
70
|
+
Basis: mail security products (for example Microsoft Defender for Office 365 Safe Links) rewrite and check links, and scanners
|
|
71
|
+
fetch links before delivery or right after it, often several at once; analysts treat clicks that arrive within seconds of
|
|
72
|
+
delivery or in tight clusters as automated. Known limits: a scanner that clicks only one or two links, or clicks later, is not
|
|
73
|
+
caught; a person who opens the mail immediately and clicks three links within a minute is marked. `scannerAsns` is empty by
|
|
74
|
+
default because people behind corporate proxies or on cloud desktops can come from the same networks as scanners — add networks
|
|
75
|
+
only after checking your own data.
|
|
76
|
+
|
|
77
|
+
### Prefetched opens (`detail.prefetch = true`)
|
|
78
|
+
|
|
79
|
+
Apple Mail Privacy Protection loads remote images through Apple's proxy servers when the message is delivered, whether or not it
|
|
80
|
+
is read, so every such load looks like an open. The engine writes `prefetch: true` explicitly (the contract in `docs/export.md`)
|
|
81
|
+
when the request comes from a network in `prefetchAsns` (default `[714]`, the autonomous system Apple operates, read from
|
|
82
|
+
Cloudflare's `request.cf.asn`) or its user agent contains a string in `prefetchUserAgents` (default none).
|
|
83
|
+
|
|
84
|
+
Known limits: this flags any image load from Apple's network, so a real open in Apple Mail with protection turned on is also
|
|
85
|
+
flagged (it cannot be told apart — that is the point of the feature). Other clients that cache images on delivery are not
|
|
86
|
+
detected by default. Gmail's image proxy normally fetches when the message is opened and is counted as an open. Treat open
|
|
87
|
+
rates as indicative and compare them only within the same tracking method; check a real message end to end before relying on
|
|
88
|
+
the flag.
|
|
89
|
+
|
|
90
|
+
## `TRACK_CONFIG`
|
|
91
|
+
|
|
92
|
+
```json
|
|
93
|
+
{ "scannerWindowMs": 60000, "scannerMinLinks": 3, "scannerAsns": [], "prefetchAsns": [714],
|
|
94
|
+
"prefetchUserAgents": [], "clickDedupeSeconds": 60, "openDedupeSeconds": 3600 }
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Unreadable values fall back to the defaults. The ledger site used to match a click to its message is the broadcast `site`.
|
|
98
|
+
|
|
99
|
+
## Not tracked
|
|
100
|
+
|
|
101
|
+
Only links in the article body are rewritten (`docs/composing.md`): the unsubscribe link, `mailto:`/`tel:` links and the
|
|
102
|
+
web-version link are never tracked. Test mail redirects but records nothing.
|
|
@@ -0,0 +1,124 @@
|
|
|
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` (`scope: 'all'`, the default: a complaint about transactional mail) | `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
|
+
| `complaint` with `scope: 'marketing'` (a complaint about a newsletter or welcome mail) | `suppressions` `unsubscribe` with `detail` starting `complaint` — the existing "no newsletters at all" reason: **newsletters stop, sign-in and notification mail keep going** — and every list becomes `unsubscribed` as above. |
|
|
93
|
+
| `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. |
|
|
94
|
+
| `delivery` | Clears the address's transient streak. |
|
|
95
|
+
|
|
96
|
+
Everything is idempotent: the same event twice leaves the same state. Lifting a suppression stays a manual act (`POST /v1/unsuppress`).
|
|
97
|
+
|
|
98
|
+
Why two kinds of complaint: someone who marks a newsletter as spam is refusing the regular mailing, not their own sign-in links. Blocking
|
|
99
|
+
transactional mail as well would leave them unable to receive anything. After a newsletter complaint the address is refused by every
|
|
100
|
+
newsletter path — the person's own subscribe answers `blocked`, imports skip it, frozen lists and welcome mail skip it, the "pressed by
|
|
101
|
+
mistake" resubscribe is refused — until someone lifts it on purpose with `POST /v1/unsuppress` and `reasons: ["unsubscribe", "complaint"]` (`"unsubscribe"` alone does not lift a complaint). Complaints recorded before this
|
|
102
|
+
change stay `complaint` rows and keep blocking every stream.
|
|
103
|
+
|
|
104
|
+
### Feeding events in
|
|
105
|
+
|
|
106
|
+
The provider layer (SNS verification, Resend webhooks, a fake provider in tests) must verify authenticity and de-duplicate, then call
|
|
107
|
+
`applyFeedback` once per recipient with an already normalised event:
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
await applyFeedback(db, { type: 'bounce', kind: 'permanent', email, source: 'ses', detail: 'NoEmail' });
|
|
111
|
+
await applyFeedback(db, { type: 'bounce', kind: 'transient', email, campaign: 'weekly-7', cause: 'mailbox', source: 'ses' });
|
|
112
|
+
await applyFeedback(db, { type: 'complaint', email, source: 'ses', scope: 'marketing' }); // about a newsletter
|
|
113
|
+
await applyFeedback(db, { type: 'delivery', email });
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Mapping for SES transient bounces: `General` and `MailboxFull` → `cause: 'mailbox'`; `ContentRejected`, `AttachmentRejected` and `MessageTooLarge` → `cause: 'content'`.
|
|
117
|
+
|
|
118
|
+
The existing Resend webhook (`webhook.ts`) and Cloudflare event consumer (`cf-events.ts`) carry transactional mail only and go through `applyFeedback` with the default scope (a complaint there stops every stream), so a complaint from any provider also unsubscribes the person from every list. Events from the newsletter postman (`ingestEvent`: SES, the fake postman) use `scope: 'marketing'`, unless the ledger row they match is a transactional one. Their transient bounces and delivery events are not wired in yet (they carry no issue id).
|
|
119
|
+
|
|
120
|
+
It returns `hard_bounce`, `complaint`, `complaint_marketing`, `transient_counted`, `transient_promoted`, `transient_no_campaign`, `transient_not_counted`, `delivery` or `rejected` (bad address or unknown type).
|
|
121
|
+
|
|
122
|
+
## Migration
|
|
123
|
+
|
|
124
|
+
`0007_unsubscribe.sql`: `list_members.unsub_reason` and the `bounce_streaks` table. Nothing changes for existing sends.
|
package/docs/welcome.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# Welcome mail
|
|
2
|
+
|
|
3
|
+
When someone joins a list for the first time, the mailroom can send them one welcome mail. It goes the newsletter way: the
|
|
4
|
+
newsletter postman, the newsletter sender domain, the two unsubscribe headers, a ledger row, today's daily cap.
|
|
5
|
+
|
|
6
|
+
## When exactly it is sent
|
|
7
|
+
|
|
8
|
+
All of these must hold:
|
|
9
|
+
|
|
10
|
+
1. **Newsletters are enabled** on the deployment: `MARKETING_DOMAIN`, `NEWSLETTER_POSTMAN` and the `BROADCAST` queue are set
|
|
11
|
+
and the postman can be built. While newsletters are switched off, nothing is queued and nothing is sent.
|
|
12
|
+
2. **The list has a welcome mail and it is switched on** (`enabled`). A new list has none; storing one requires saying
|
|
13
|
+
`enabled: true` or `false` every time.
|
|
14
|
+
3. **The person subscribed through `listSubscribe`** (the service binding) and was **never a member of that list before**
|
|
15
|
+
(`firstTime: true` in the answer). Someone who unsubscribed and comes back gets `firstTime: false` and no second welcome.
|
|
16
|
+
Imports (`POST /v1/lists/{id}/import`) and segment writes never send one; an imported person (subscribed, unsubscribed or
|
|
17
|
+
removed) is not first-time when they subscribe later.
|
|
18
|
+
4. At sending time they are still subscribed, not on the suppression list, the sender domain is not on hold, the provider is
|
|
19
|
+
healthy and today's cap has room. A domain hold, an unhealthy provider or a full cap waits: the message is re-queued as a new
|
|
20
|
+
message every 15 minutes (so it does not use up the queue's retry count) for up to 48 hours from the subscribe, then gives up
|
|
21
|
+
(an old welcome is not sent late, also when a dead-letter queue is replayed).
|
|
22
|
+
Welcome mail is not part of the warm-up ladder; it only counts toward today's cap. Keep that in mind while a new sender
|
|
23
|
+
domain is warming up (or leave the welcome mail off until warm-up is done).
|
|
24
|
+
5. The ledger key `welcome:{list}:{contact}` has not been sent. Two subscribe calls at the same time, or a queue message
|
|
25
|
+
delivered twice, still send one mail.
|
|
26
|
+
|
|
27
|
+
`listSubscribe` answers as before, with one extra field: `{ status: 'subscribed', firstTime: boolean }`. Queueing happens after
|
|
28
|
+
the member is written; if it fails it is logged and the subscribe still succeeds.
|
|
29
|
+
|
|
30
|
+
Only call `listSubscribe` for addresses whose owner confirmed the subscription (for example after a confirmation mail): the
|
|
31
|
+
welcome mail goes out automatically. Because the name is supplied by whoever subscribes, only names made of letters, combining marks,
|
|
32
|
+
spaces, apostrophes and hyphens (a dot only after a single letter, as in initials; at most 40 characters, after Unicode NFKC
|
|
33
|
+
normalisation) are used; any other name is dropped from the welcome mail (the greeting section is left out).
|
|
34
|
+
|
|
35
|
+
A welcome mail is not tracked (no click redirect, no open pixel). Events for it carry `campaign = "_welcome-{list}"`, which can
|
|
36
|
+
never collide with an issue id. Bounces and complaints are handled like any other newsletter mail.
|
|
37
|
+
|
|
38
|
+
## Content
|
|
39
|
+
|
|
40
|
+
The content is configuration, composed outside the Worker like an issue. With the desk command:
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
mailroom welcome --list weekly --source welcome.md --web-url https://example.com/newsletter --disable --yes # store it off
|
|
44
|
+
mailroom welcome --list weekly # look at it
|
|
45
|
+
mailroom welcome --list weekly --source welcome.md --web-url https://example.com/newsletter --enable --yes # switch it on
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The command composes the markdown with your template (without `trackBase`), runs the pre-send check, and stores the result with
|
|
49
|
+
`PUT /v1/lists/{id}/welcome` (admin token). `GET /v1/lists/{id}/welcome` returns what is stored. The engine refuses content
|
|
50
|
+
without `{{unsubscribe_url}}` in both HTML and text, with tracking placeholders, with unknown placeholders, or with a sender
|
|
51
|
+
outside the newsletter domain. Placeholders: `{{name}}` (`{{#name}}…{{/name}}`), `{{email}}`, `{{unsubscribe_url}}`,
|
|
52
|
+
`{{web_url}}` (the URL you pass, e.g. the archive page). The engine adds `List-Unsubscribe` (with the unsubscribe mailto when
|
|
53
|
+
`UNSUB_MAILTO` is set) and `List-Unsubscribe-Post` itself.
|
|
54
|
+
|
|
55
|
+
An example source (keep your real one in your own configuration):
|
|
56
|
+
|
|
57
|
+
```markdown
|
|
58
|
+
---
|
|
59
|
+
title: Welcome to Example Weekly
|
|
60
|
+
description: One email a week. Here is what to expect.
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
Thanks for subscribing. Every Monday you will get one email with the week's notes.
|
|
64
|
+
|
|
65
|
+
- Past issues are on the [archive page](https://example.com/newsletter).
|
|
66
|
+
- Reply to any issue to reach us.
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Storage
|
|
70
|
+
|
|
71
|
+
Migration `0009_welcome.sql` adds `welcome_mails` (one row per list: subject, sender, HTML, text, web URL, content hash,
|
|
72
|
+
`enabled`). The older `lists.welcome_template` column is left as it was and is not used by the engine.
|
|
@@ -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);
|