@joelincc/mailroom 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 joelin.cc
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,166 @@
1
- # Temporary Holding Version
1
+ # mailroom
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Must-deliver notification email for Cloudflare Workers.**
4
+ Sign-in links, invites, receipts, payment and security notices — the mail that has to arrive.
5
+
6
+ > Status: **v0.x preview.** It runs in production for a handful of small apps, but the interface may still change before 1.0.
7
+
8
+ ## What it is (and isn't)
9
+
10
+ Your apps hand a message to one Worker; the Worker does everything it can to get it delivered, never sends the same key twice once it has succeeded, and keeps a ledger.
11
+
12
+ - **Multi-provider failover** — Resend first, SMTP2GO as backup (Cloudflare Email Sending optional). A timeout or 5xx from Resend is re-checked once with the same idempotency key before falling back. The design prefers a rare duplicate over a lost message: if a provider times out after actually sending, the fallback provider may deliver a second copy.
13
+ - **Idempotent sends** — every message carries a `(site, key)` pair. Once a key is recorded as `sent`, sending it again returns `duplicate` instead of a second email; a `failed` key can be retried. (A retry after a timeout can produce a duplicate — see above. Resend honours the idempotency key for 24 hours; SMTP2GO has no idempotency key.)
14
+ - **Suppression list** — hard bounces and spam complaints are recorded and future sends to that address are blocked (`suppressed`), across all your apps.
15
+ - **Bounce / complaint feedback** — Resend webhooks (Svix-signed) and Cloudflare Email Sending events update the ledger and the suppression list.
16
+ - **A D1 ledger** — one row per message: recipient, sender, subject, provider, provider id, outcome, later events. Message bodies are never stored.
17
+
18
+ It is **not** a newsletter or marketing-email system: there are no lists, campaigns, open/click tracking or unsubscribe pages. Requests with `stream: "marketing"` are rejected. It is not for cold email, and never will be — only send to people who asked to hear from you.
19
+
20
+ ## How it works
21
+
22
+ ```
23
+ your app ──(service binding or HTTPS + key)──▶ mailroom Worker
24
+ 1. suppression list? → suppressed
25
+ 2. (site, key) seen? → duplicate / in_flight
26
+ 3. provider #1 → recheck → provider #2 …
27
+ 4. write ledger row → sent / failed
28
+ Resend / Cloudflare events ──▶ webhook / queue ──▶ ledger + suppression list
29
+ ```
30
+
31
+ Two tiers share the same ledger and suppression list but use separate sender domains, so reputation problems in one don't leak into the other:
32
+
33
+ | | `notify` (default) | `remind` (optional) |
34
+ |---|---|---|
35
+ | For | sign-in, email change, invites, payments, receipts, security alerts | in-app notices, due-date reminders, digests (always triggered by a user event, never promotional) |
36
+ | Sender domain | `FROM_DOMAIN` | `REMIND_DOMAIN` |
37
+ | Provider order | `ROUTES`, default Resend → SMTP2GO | `ROUTES`, default Resend → SMTP2GO — Resend only if `RESEND_API_KEY_REMIND` is set (otherwise tier 2 silently uses SMTP2GO only) |
38
+
39
+ The `from` address must belong to the tier's domain.
40
+
41
+ ## Quick deploy
42
+
43
+ You need a Cloudflare account, Node.js ≥ 22, and at least one provider account (Resend and/or SMTP2GO) with your sender domain verified.
44
+
45
+ ```bash
46
+ git clone <this repo> mailroom && cd mailroom
47
+ npm ci
48
+ cp wrangler.example.jsonc wrangler.jsonc # git-ignored: your ids stay local
49
+ npx wrangler d1 create mailroom # paste the database_id into wrangler.jsonc
50
+ # edit FROM_DOMAIN in wrangler.jsonc (uncomment REMIND_DOMAIN only if you use tier 2)
51
+ npx wrangler secret put RESEND_API_KEY
52
+ npx wrangler secret put SMTP2GO_API_KEY
53
+ # npx wrangler secret put RESEND_API_KEY_REMIND # only if you enable tier 2 (REMIND_DOMAIN)
54
+ npx wrangler secret put RESEND_WEBHOOK_SECRET # from the Resend webhook you point at /webhooks/resend
55
+ npx wrangler secret put DRILL_TOKEN # any long random string, e.g. `openssl rand -hex 32`
56
+ npm run deploy # tests + typecheck + D1 migrations + wrangler deploy
57
+ ```
58
+
59
+ Then run the drill below to prove failover works before you point real traffic at it.
60
+
61
+ ## Sending mail
62
+
63
+ **From a Worker on the same Cloudflare account (recommended)** — add a service binding to the sending app's `wrangler.jsonc`:
64
+
65
+ ```jsonc
66
+ "services": [{ "binding": "MAILROOM", "service": "mailroom", "entrypoint": "Mailroom" }]
67
+ ```
68
+
69
+ ```ts
70
+ const r = await env.MAILROOM.send({
71
+ site: 'billing', // your app's name: [a-z0-9-], max 40
72
+ key: `invoice-paid:${invoice.id}`, // idempotency key, unique per message
73
+ kind: 'invoice_paid', // optional label for your own reporting
74
+ from: 'Billing <billing@notify.example.com>',
75
+ to: customer.email,
76
+ subject: 'Your invoice has been paid',
77
+ html, text,
78
+ // tier: 'remind', replyTo: 'help@example.com'
79
+ });
80
+ ```
81
+
82
+ **From anywhere else** — `POST /v1/send` with `Authorization: Bearer <HTTP_KEY_SITE>` and the same JSON body. The key decides which `site` the message belongs to; a `site` in the body is ignored. Enable a client by adding its name to `HTTP_CLIENTS` and setting the secret `HTTP_KEY_<NAME_UPPERCASE>` (dashes become underscores).
83
+
84
+ ### Responses
85
+
86
+ | `status` | Meaning | What your app should do |
87
+ |---|---|---|
88
+ | `sent` | Delivered to a provider on this call | done |
89
+ | `duplicate` | This `(site, key)` was already sent | done — do not send again |
90
+ | `in_flight` | The same key is being sent right now | ask again shortly |
91
+ | `suppressed` | Recipient hard-bounced or complained | don't retry; show the user a "check your address" message |
92
+ | `failed` | Every provider failed | if `retryable: true`, queue it and retry later **with the same key** |
93
+ | `rejected` | The request itself is invalid (`reason` says why) | fix the request; don't retry |
94
+
95
+ If your app can't reach the mailroom at all, queue the message locally and retry with the same key — a key already recorded as `sent` won't be sent again.
96
+
97
+ ## Public endpoints
98
+
99
+ | Path | Purpose | Protection |
100
+ |---|---|---|
101
+ | `POST /webhooks/resend` | Resend events (delivered, bounced, complained, failed, delayed); permanent bounces and complaints go into the suppression list | Svix signature (`RESEND_WEBHOOK_SECRET`), 5-minute timestamp window |
102
+ | `POST /v1/send` | Sending from apps outside your Cloudflare account | per-client `HTTP_KEY_*`; rate limits `HTTP_RATE_PER_MIN` (default 60) and `HTTP_DAILY_LIMIT` (default 2000 per UTC day); optional sender allowlist `HTTP_FROM` |
103
+ | `POST /v1/drill`, `GET /v1/lookup`, `GET /v1/report`, `POST /v1/unsuppress` | Operator tools (see below) | `DRILL_TOKEN`; **if it isn't set these paths return 404**; 20 requests/min and 200/day in total |
104
+
105
+ Apart from `GET /` (a plain-text health check), anything else returns 404. Unknown keys get a 404, not a 401, so the endpoint doesn't confirm that it exists. The operator endpoints only return status fields — never recipients, senders or subjects — so a leaked `DRILL_TOKEN` can't be used to read your mail log. It **can** still be used to send drill emails from your domain to any address (capped by the limit above) and to lift suppressions, so treat it like a password: set it only when you need it, and rotate it after use (`wrangler secret put DRILL_TOKEN`, or `wrangler secret delete DRILL_TOKEN` to switch the endpoints off). Request bodies must carry a `Content-Length` header (411 otherwise) and are capped at 3 MB (`/v1/send`) and 256 KB (webhook). Someone holding a leaked token can also use up the operator quota for the day, locking you out until you rotate the token.
106
+
107
+ The webhook needs a public URL, which is why `workers_dev` is on in the template. If you don't use Resend webhooks or HTTP clients, set `"workers_dev": false` and the Worker is reachable only through service bindings.
108
+
109
+ **Strongly recommended for every HTTP client:** set `HTTP_FROM` (`{ "shop": ["orders@notify.example.com"] }`). Without it a client may use any address on the tier's domain (a warning is logged).
110
+
111
+ ## Operating it
112
+
113
+ **Drill** — proves failover, de-duplication and lookup in one go:
114
+
115
+ ```bash
116
+ URL=https://mailroom.<your-subdomain>.workers.dev
117
+ curl -X POST $URL/v1/drill -H "Authorization: Bearer $DRILL_TOKEN" \
118
+ -d '{"to":"you@example.com","mode":"fallback","key":"d1"}' # expect route: smtp2go (Resend key is deliberately wrong)
119
+ # same command again → expect status: duplicate
120
+ curl "$URL/v1/lookup?site=drill&key=drill:d1" -H "Authorization: Bearer $DRILL_TOKEN" # → the ledger row
121
+ ```
122
+
123
+ Drill keys are always prefixed with `drill:` so a drill can never claim a real message's key. Options: `"mode": "normal"`, `"tier": "remind"`, `"only": "smtp2go"` (test a single provider).
124
+
125
+ **Report** — `GET /v1/report?days=7` groups the ledger by site, tier, provider, outcome and recipient *domain* (never full addresses).
126
+
127
+ **Lift a suppression** — when someone fixed their mailbox or a bounce was a false positive:
128
+
129
+ ```bash
130
+ curl -X POST $URL/v1/unsuppress -H "Authorization: Bearer $DRILL_TOKEN" \
131
+ -d '{"email":"someone@example.com","reasons":["hard_bounce"]}'
132
+ ```
133
+
134
+ `reasons` is required (`hard_bounce`, `complaint`, `unsubscribe`) so you can't accidentally clear a complaint. Providers keep their own suppression lists (e.g. Resend → Suppressions); clear those there.
135
+
136
+ **Roll back** — Cloudflare dashboard → Workers → mailroom → Deployments → Rollback, or `npx wrangler rollback`.
137
+
138
+ ### Configuration reference
139
+
140
+ Variables (`wrangler.jsonc` → `vars`): `FROM_DOMAIN`, `REMIND_DOMAIN`, `ROUTES`, `HTTP_CLIENTS`, `HTTP_RATE_PER_MIN`, `HTTP_DAILY_LIMIT` (non-negative integers only; missing, blank or invalid → default; an explicit `0` means unlimited), `HTTP_FROM`, `DAILY_DRILL` (optional scheduled drill: `{ "until": "YYYY-MM-DD", "to": ["you@example.com"], "tier": "remind", "utcOffsetHours": 0 }` — `until` is inclusive and compared in UTC unless you set `utcOffsetHours`; sends at most one round per day — extra cron runs that day return `duplicate` — so add a daily cron trigger).
141
+
142
+ Secrets (always add as **Secret**, never as a plain variable): `RESEND_API_KEY`, `SMTP2GO_API_KEY`, `RESEND_WEBHOOK_SECRET`, `DRILL_TOKEN`, `HTTP_KEY_*`, `RESEND_API_KEY_REMIND` (Resend keys can be scoped to one domain, so tier 2 can have its own).
143
+
144
+ Provider order (`ROUTES`): keys are `site:tier` or `*:tier`, values are lists of `resend`, `smtp2go`, `cloudflare`. Example: `{ "*:remind": ["cloudflare", "resend"] }`. Cloudflare Email Sending also needs the `send_email` binding and, for bounce events, the queue consumer — both are in the template, commented out.
145
+
146
+ ## Development
147
+
148
+ ```bash
149
+ npm test # node --test; runs the real migrations/*.sql against Node's built-in SQLite
150
+ npm run typecheck
151
+ npm run clean-scan # blocks keys, account ids and real email addresses from ever being committed
152
+ ```
153
+
154
+ `src/core.ts` (ledger), `src/transport.ts` (providers) and `src/webhook.ts` (events) don't import `cloudflare:*`, so they run under plain Node in tests. `src/index.ts` is the Worker shell. Code comments are currently in Traditional Chinese.
155
+
156
+ ## Contributing, support and security
157
+
158
+ Forks are welcome — that's what the MIT license is for. Issues and pull requests are welcome too, but this is maintained on a best-effort basis: **no support, no guaranteed response, no roadmap commitments.** Please don't email the author about it, and please don't send unsolicited (cold) email pitches.
159
+
160
+ Pull requests run tests and a clean-scan; changes to `src/`, `migrations/`, workflows or dependencies wait for an owner review. Details, including the rules for AI-assisted contributions, are in [CONTRIBUTING.md](CONTRIBUTING.md) and [AGENTS.md](AGENTS.md).
161
+
162
+ Before you deploy, read [docs/security-model.md](docs/security-model.md): who mailroom trusts, what personal data the ledger holds (and that **it has no automatic retention limit**), what each secret can do if it leaks, and a hardening checklist. Security issues: see [SECURITY.md](SECURITY.md) — please report privately, not in a public issue.
163
+
164
+ ## License
165
+
166
+ [MIT](LICENSE)
package/SECURITY.md ADDED
@@ -0,0 +1,11 @@
1
+ # Security policy/資安回報
2
+
3
+ - **Please do not open a public issue for security problems.** Use GitHub's private vulnerability reporting
4
+ (Security tab → "Report a vulnerability").
5
+ 資安問題請不要開公開 issue,請用 GitHub 的私下回報(Security 分頁 →「Report a vulnerability」)。
6
+ - This project is provided as-is, without support or response-time guarantees; fixes are best-effort.
7
+ 本專案照現狀提供,不提供支援、不保證回覆時間。
8
+ - Releases are published to npm only through GitHub Actions with provenance (Trusted Publishing);
9
+ no npm token exists for this package. 發布只經 GitHub Actions(附 provenance),本套件沒有 npm 鑰匙。
10
+
11
+ <!-- public-gate v0.2.0 -->
@@ -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
+ | Everyone else | — | `GET /` returns a plain-text health check. `POST /webhooks/resend` answers 401, 411 or 413. Everything else is 404. |
16
+
17
+ Mailroom does **not** check that a recipient opted in, does not scan message content, and does not sanitise HTML.
18
+ Whoever holds a client key can send anything, to anyone, from that client's allowed sender addresses.
19
+ The rate limits cap the damage; they do not prevent it.
20
+
21
+ ## What is stored, and for how long
22
+
23
+ One D1 database, four tables:
24
+
25
+ | Table | Personal data | Notes |
26
+ |---|---|---|
27
+ | `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. |
28
+ | `suppressions` | recipient address, bounce detail text from the provider | Kept until you lift the suppression. |
29
+ | `webhook_events` | none (event id, type, time) | |
30
+ | `rate_counters` | none | Rows older than two days are pruned opportunistically, on a small share of HTTP requests. |
31
+
32
+ **There is no automatic retention limit on `messages`, `suppressions` or `webhook_events`.** Decide a retention
33
+ period that fits your privacy obligations and delete older rows yourself, for example monthly:
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. (If `HTTP_FROM` is set but isn't valid JSON, `/v1/send` refuses everything with a 500 rather than running without the allowlist.)
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
+ - [ ] You have a retention job for the ledger (see above).
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.
@@ -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
+ );
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@joelincc/mailroom",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Must-deliver transactional email for Cloudflare Workers: multi-provider failover (Resend, SMTP2GO, Cloudflare Email Sending), idempotent sends, a suppression list and bounce/complaint feedback, with a D1 ledger.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/joepspsps2/mailroom.git"
10
+ },
11
+ "exports": {
12
+ ".": "./src/index.ts"
13
+ },
14
+ "files": [
15
+ "src",
16
+ "migrations",
17
+ "wrangler.example.jsonc",
18
+ "README.md",
19
+ "LICENSE",
20
+ "SECURITY.md",
21
+ "docs"
22
+ ],
23
+ "keywords": [
24
+ "cloudflare-workers",
25
+ "email",
26
+ "transactional-email",
27
+ "failover",
28
+ "resend",
29
+ "smtp2go",
30
+ "d1",
31
+ "idempotency",
32
+ "suppression-list"
33
+ ],
34
+ "scripts": {
35
+ "test": "node --test --experimental-strip-types tests/*.test.ts",
36
+ "typecheck": "tsc --noEmit",
37
+ "db:migrate": "wrangler d1 migrations apply mailroom --remote",
38
+ "deploy": "npm test && npm run typecheck && npm run db:migrate && wrangler deploy",
39
+ "dev": "wrangler dev",
40
+ "clean-scan": "node .public-gate/clean-scan.mjs"
41
+ },
42
+ "devDependencies": {
43
+ "@cloudflare/workers-types": "^5.20261019.1",
44
+ "typescript": "^5.6.3",
45
+ "wrangler": "4.162.0"
46
+ },
47
+ "engines": {
48
+ "node": ">=22.23.4"
49
+ }
50
+ }
@@ -0,0 +1,83 @@
1
+ // Cloudflare 寄信的事後回報:Cloudflare 把寄件網域的送達/退信/檢舉事件放進 Queue
2
+ // (官方 event-subscriptions,來源 Email Sending,每個寄件網域一份訂閱),郵務室當消費者讀進來。
3
+ // 跟 Resend 的 webhook 進同一份拒收名單、同一張帳本(messages.provider_id=Cloudflare 回的 messageId)。
4
+ // 文件:https://developers.cloudflare.com/email-service/reference/event-subscriptions/(2026-11-04 查)
5
+
6
+ import { addSuppression, type Db } from './core.ts';
7
+
8
+ interface CfEmailEvent {
9
+ type?: string;
10
+ source?: { type?: string; domain?: string };
11
+ payload?: {
12
+ eventId?: string;
13
+ messageId?: string;
14
+ recipient?: string;
15
+ terminal?: boolean;
16
+ delivery?: { status?: string; smtpStatusCode?: string; smtpResponse?: string };
17
+ bounce?: { type?: string; classification?: string; reason?: string };
18
+ failure?: { reason?: string };
19
+ rejection?: { reason?: string; party?: string; detail?: string };
20
+ complaint?: { type?: string };
21
+ };
22
+ metadata?: { eventTimestamp?: string };
23
+ }
24
+
25
+ const PREFIX = 'cf.email.sending.message.';
26
+ /** 事件 → 帳本 last_event(跟 Resend 那邊同一套字)。 */
27
+ const LAST_EVENT: Record<string, string> = {
28
+ delivered: 'delivered',
29
+ deferred: 'delayed',
30
+ bounced: 'bounced',
31
+ failed: 'failed',
32
+ rejected: 'rejected',
33
+ complained: 'complained',
34
+ };
35
+
36
+ /** 處理一則 Cloudflare 寄信事件;回傳做了什麼(給 log/測試看)。同一則事件(eventId)只處理一次。 */
37
+ export async function handleCfEvent(db: Db, raw: unknown, now = new Date()): Promise<string> {
38
+ const ev = (typeof raw === 'string' ? safeParse(raw) : raw) as CfEmailEvent | null;
39
+ if (!ev || typeof ev !== 'object') return 'bad_event';
40
+ const type = String(ev.type ?? '');
41
+ if (ev.source?.type !== 'email.sending' || !type.startsWith(PREFIX)) return 'ignored';
42
+ const name = type.slice(PREFIX.length);
43
+ const p = ev.payload ?? {};
44
+ const eventKey = `cf:${p.eventId || `${p.messageId ?? '-'}:${name}:${ev.metadata?.eventTimestamp ?? ''}`}`;
45
+ // 先查有沒有處理過;處理完才記「已處理」(中途出錯時郵差重送還會再處理一次)。下面每一步都可重複執行不出錯。
46
+ const seen = await db.prepare('SELECT 1 AS x FROM webhook_events WHERE id = ?').bind(eventKey).first();
47
+ if (seen) return 'repeat';
48
+ const outcome = await applyEvent(db, ev, name, now);
49
+ await db.prepare('INSERT INTO webhook_events (id, type, received_at) VALUES (?, ?, ?) ON CONFLICT (id) DO NOTHING').bind(eventKey, type, now.toISOString()).run();
50
+ return outcome;
51
+ }
52
+
53
+ async function applyEvent(db: Db, ev: CfEmailEvent, name: string, now: Date): Promise<string> {
54
+ const p = ev.payload ?? {};
55
+
56
+ const last = LAST_EVENT[name];
57
+ if (last && p.messageId) {
58
+ await db.prepare("UPDATE messages SET last_event = ?, updated_at = ? WHERE provider_id = ? AND route = 'cloudflare'").bind(last, now.toISOString(), p.messageId).run();
59
+ }
60
+ const email = String(p.recipient ?? '').trim().toLowerCase();
61
+
62
+ if (name === 'bounced') {
63
+ // 只有硬退信(信箱不存在、網域收不到)才進拒收名單;暫時性重試用完的 soft 不擋。
64
+ if (p.bounce?.type !== 'hard' || !email) return `bounce_${String(p.bounce?.type ?? 'unknown').toLowerCase()}`;
65
+ const detail = [p.bounce.classification, p.bounce.reason, p.delivery?.smtpStatusCode].filter(Boolean).join(': ');
66
+ await addSuppression(db, email, 'hard_bounce', 'cloudflare-event', detail || null, now);
67
+ return 'hard_bounce:1';
68
+ }
69
+ if (name === 'complained') {
70
+ if (!email) return 'complaint:0';
71
+ await addSuppression(db, email, 'complaint', 'cloudflare-event', p.complaint?.type ?? null, now);
72
+ return 'complaint:1';
73
+ }
74
+ return last ? `event:${last}` : 'ignored';
75
+ }
76
+
77
+ function safeParse(s: string): unknown {
78
+ try {
79
+ return JSON.parse(s);
80
+ } catch {
81
+ return null;
82
+ }
83
+ }