@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.
- package/LICENSE +21 -0
- package/README.md +207 -2
- package/SECURITY.md +11 -0
- 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 +31 -0
- package/dist/cli/main.js +475 -0
- package/dist/compose/clicks.js +29 -0
- package/dist/compose/compose.js +224 -0
- package/dist/compose/index.js +8 -0
- package/dist/compose/markdown.js +637 -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 +136 -0
- package/dist/compose/template.js +118 -0
- package/docs/broadcast.md +199 -0
- package/docs/composing.md +135 -0
- package/docs/desk-commands.md +52 -0
- package/docs/export.md +51 -0
- package/docs/lists.md +66 -0
- package/docs/security-model.md +82 -0
- package/docs/ses.md +116 -0
- package/docs/unsubscribe.md +117 -0
- package/migrations/0001_init.sql +42 -0
- package/migrations/0002_tier.sql +4 -0
- package/migrations/0003_rate.sql +9 -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/package.json +64 -4
- 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 +339 -0
- package/src/broadcast/config.ts +136 -0
- package/src/broadcast/dispatch.ts +766 -0
- package/src/broadcast/events.ts +107 -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 +177 -0
- package/src/cf-events.ts +84 -0
- package/src/cli/args.ts +27 -0
- package/src/cli/errors.ts +33 -0
- package/src/cli/main.ts +466 -0
- package/src/compose/clicks.ts +45 -0
- package/src/compose/compose.ts +257 -0
- package/src/compose/index.ts +8 -0
- package/src/compose/markdown.ts +624 -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 +153 -0
- package/src/compose/template.ts +197 -0
- package/src/core.ts +328 -0
- package/src/export.ts +184 -0
- package/src/feedback.ts +111 -0
- package/src/http.ts +17 -0
- package/src/index.ts +378 -0
- package/src/list-routes.ts +42 -0
- package/src/lists.ts +370 -0
- package/src/ses-events.ts +426 -0
- package/src/transport.ts +193 -0
- package/src/unsub-wiring.ts +64 -0
- package/src/unsub.ts +499 -0
- package/src/webhook.ts +101 -0
- package/wrangler.example.jsonc +56 -0
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,208 @@
|
|
|
1
|
-
#
|
|
1
|
+
# mailroom
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
## Composing (preview)
|
|
21
|
+
|
|
22
|
+
The `@joelincc/mailroom/compose` entry point turns a markdown source into an email (HTML + plain text), personalises it, and
|
|
23
|
+
runs a pre-send check that refuses to schedule a broken issue. It does not send anything. See [docs/composing.md](docs/composing.md).
|
|
24
|
+
|
|
25
|
+
## Broadcasting (preview)
|
|
26
|
+
|
|
27
|
+
The `@joelincc/mailroom/broadcast` entry point sends one newsletter issue to a frozen list: approval and pre-send check
|
|
28
|
+
before scheduling, waves, pacing under the provider's limits and your own daily cap, a warm-up ladder, automatic brakes
|
|
29
|
+
on bounces and complaints, and a reconciliation that must add up before an issue counts as done. Newsletter
|
|
30
|
+
postmans: Amazon SES with signed SNS events ([docs/ses.md](docs/ses.md)) and a fake one for development. See
|
|
31
|
+
[docs/broadcast.md](docs/broadcast.md).
|
|
32
|
+
|
|
33
|
+
## How it works
|
|
34
|
+
|
|
35
|
+
```
|
|
36
|
+
your app ──(service binding or HTTPS + key)──▶ mailroom Worker
|
|
37
|
+
1. suppression list? → suppressed
|
|
38
|
+
2. (site, key) seen? → duplicate / in_flight
|
|
39
|
+
3. provider #1 → recheck → provider #2 …
|
|
40
|
+
4. write ledger row → sent / failed
|
|
41
|
+
Resend / Cloudflare events ──▶ webhook / queue ──▶ ledger + suppression list
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
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:
|
|
45
|
+
|
|
46
|
+
| | `notify` (default) | `remind` (optional) |
|
|
47
|
+
|---|---|---|
|
|
48
|
+
| 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) |
|
|
49
|
+
| Sender domain | `FROM_DOMAIN` | `REMIND_DOMAIN` |
|
|
50
|
+
| 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) |
|
|
51
|
+
|
|
52
|
+
The `from` address must belong to the tier's domain.
|
|
53
|
+
|
|
54
|
+
## Supported providers
|
|
55
|
+
|
|
56
|
+
For transactional mail, mailroom supports exactly **three** providers: **Resend**, **SMTP2GO** and **Cloudflare Email Sending** (newsletters can use Amazon SES, see [docs/ses.md](docs/ses.md)). `ROUTES` only accepts those three names (`resend`, `smtp2go`, `cloudflare`); anything else is ignored. If you want another provider (SES, Postmark, Mailgun, a plain SMTP relay…), you have to write an adapter yourself in `src/transport.ts` and add its name to `MAIL_ROUTES` — there is no plugin interface, and no support for doing so.
|
|
57
|
+
|
|
58
|
+
## Verify your sender domain first
|
|
59
|
+
|
|
60
|
+
Providers refuse to send, or the mail lands in spam, until the domain in your `from` address is verified. Do this for every sender domain (`FROM_DOMAIN`, and `REMIND_DOMAIN` if you use tier 2), **at each provider you enable**. Using a dedicated subdomain such as `notify.example.com` keeps this mail's reputation apart from your main domain.
|
|
61
|
+
|
|
62
|
+
1. In the provider's dashboard (Resend → Domains, SMTP2GO → Sending → Verified Senders → Sender Domains, Cloudflare → Email Sending), add the domain. The provider then shows you the exact DNS records to create — copy them from there, because the values are specific to your account.
|
|
63
|
+
2. Add those records at your DNS host. They normally come in three kinds:
|
|
64
|
+
|
|
65
|
+
| Record | What it does | Typical shape (example values — use the ones your provider shows) |
|
|
66
|
+
|---|---|---|
|
|
67
|
+
| **SPF** (TXT) | Lists who may send for the domain. Providers usually put theirs on a provider-specific sub-label (for example `send.notify.example.com`) so it doesn't collide with your own. If you add one on the sending domain itself, there must be **only one** SPF record per name: merge them (`v=spf1 include:provider-a.example include:provider-b.example ~all`), never publish two. | `TXT notify.example.com "v=spf1 include:spf.provider.example ~all"` |
|
|
68
|
+
| **DKIM** (TXT or CNAME) | A public key the provider signs each message with, so receivers can check it wasn't altered and really came from you. Each provider gives its own selector, so several providers can coexist. | `CNAME s1._domainkey.notify.example.com → s1.dkim.provider.example` (or a TXT with `v=DKIM1; k=rsa; p=…`) |
|
|
69
|
+
| **DMARC** (TXT, once per domain) | Tells receivers what to do when SPF/DKIM fail, and where to send reports. Start with monitoring only. | `TXT _dmarc.notify.example.com "v=DMARC1; p=none; rua=mailto:dmarc@example.com"` |
|
|
70
|
+
|
|
71
|
+
3. Wait for the provider to show the domain as **Verified** (DNS can take minutes to hours). DMARC passes when SPF or DKIM passes *and aligns* with the `from` domain, so check that your provider's records authenticate the same domain you put in `FROM_DOMAIN`.
|
|
72
|
+
4. Send a drill (below) to a mailbox you control, open "show original" and confirm `SPF: PASS`, `DKIM: PASS`, `DMARC: PASS`. Once that is stable you can tighten DMARC to `p=quarantine` or `p=reject`.
|
|
73
|
+
|
|
74
|
+
If a provider key can be scoped to one domain (Resend can), create it after the domain is verified.
|
|
75
|
+
|
|
76
|
+
## Quick deploy
|
|
77
|
+
|
|
78
|
+
You need a Cloudflare account, Node.js ≥ 22, and at least one provider account (Resend and/or SMTP2GO) with your sender domain verified.
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
git clone <this repo> mailroom && cd mailroom
|
|
82
|
+
npm ci
|
|
83
|
+
cp wrangler.example.jsonc wrangler.jsonc # git-ignored: your ids stay local
|
|
84
|
+
npx wrangler d1 create mailroom # paste the database_id into wrangler.jsonc
|
|
85
|
+
# edit FROM_DOMAIN in wrangler.jsonc (uncomment REMIND_DOMAIN only if you use tier 2)
|
|
86
|
+
npx wrangler secret put RESEND_API_KEY
|
|
87
|
+
npx wrangler secret put SMTP2GO_API_KEY
|
|
88
|
+
# npx wrangler secret put RESEND_API_KEY_REMIND # only if you enable tier 2 (REMIND_DOMAIN)
|
|
89
|
+
npx wrangler secret put RESEND_WEBHOOK_SECRET # from the Resend webhook you point at /webhooks/resend
|
|
90
|
+
npx wrangler secret put DRILL_TOKEN # any long random string, e.g. `openssl rand -hex 32`
|
|
91
|
+
npm run deploy # tests + typecheck + D1 migrations + wrangler deploy
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Then run the drill below to prove failover works before you point real traffic at it.
|
|
95
|
+
|
|
96
|
+
## Sending mail
|
|
97
|
+
|
|
98
|
+
**From a Worker on the same Cloudflare account (recommended)** — add a service binding to the sending app's `wrangler.jsonc`:
|
|
99
|
+
|
|
100
|
+
```jsonc
|
|
101
|
+
"services": [{ "binding": "MAILROOM", "service": "mailroom", "entrypoint": "Mailroom" }]
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
const r = await env.MAILROOM.send({
|
|
106
|
+
site: 'billing', // your app's name: [a-z0-9-], max 40
|
|
107
|
+
key: `invoice-paid:${invoice.id}`, // idempotency key, unique per message
|
|
108
|
+
kind: 'invoice_paid', // optional label for your own reporting
|
|
109
|
+
from: 'Billing <billing@notify.example.com>',
|
|
110
|
+
to: customer.email,
|
|
111
|
+
subject: 'Your invoice has been paid',
|
|
112
|
+
html, text,
|
|
113
|
+
// tier: 'remind', replyTo: 'help@example.com'
|
|
114
|
+
});
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
**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`, setting the secret `HTTP_KEY_<NAME_UPPERCASE>` (dashes become underscores) and listing its allowed sender addresses in `HTTP_FROM`.
|
|
118
|
+
|
|
119
|
+
### Responses
|
|
120
|
+
|
|
121
|
+
| `status` | Meaning | What your app should do |
|
|
122
|
+
|---|---|---|
|
|
123
|
+
| `sent` | Delivered to a provider on this call | done |
|
|
124
|
+
| `duplicate` | This `(site, key)` was already sent | done — do not send again |
|
|
125
|
+
| `in_flight` | The same key is being sent right now | ask again shortly |
|
|
126
|
+
| `suppressed` | Recipient hard-bounced or complained | don't retry; show the user a "check your address" message |
|
|
127
|
+
| `failed` | Every provider failed | if `retryable: true`, queue it and retry later **with the same key** |
|
|
128
|
+
| `rejected` | The request itself is invalid (`reason` says why) | fix the request; don't retry |
|
|
129
|
+
|
|
130
|
+
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.
|
|
131
|
+
|
|
132
|
+
## Public endpoints
|
|
133
|
+
|
|
134
|
+
| Path | Purpose | Protection |
|
|
135
|
+
|---|---|---|
|
|
136
|
+
| `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 |
|
|
137
|
+
| `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); sender allowlist `HTTP_FROM` (required per client) |
|
|
138
|
+
| `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 |
|
|
139
|
+
| `GET`/`POST /u/{token}`, `POST /u/{token}/resubscribe` | Unsubscribe page and one-click unsubscribe ([docs/unsubscribe.md](docs/unsubscribe.md)) | the unsubscribe token itself |
|
|
140
|
+
| `PUT /v1/lists/{id}`, `POST /v1/lists/{id}/import`, `POST /v1/lists/{id}/segments` | Newsletter list management ([docs/lists.md](docs/lists.md)) | `DRILL_TOKEN`, same quota; bodies capped at 1.5 MB |
|
|
141
|
+
| `/v1/campaigns/*`, `/v1/throttle`, `/v1/warmup/*`, `/v1/broadcast/release-hold` | Newsletter broadcasting ([docs/broadcast.md](docs/broadcast.md)); 404 unless `MARKETING_DOMAIN` is set; test mail only if `TEST_RECIPIENTS` is set | `DRILL_TOKEN`, same quota; bodies capped at 3 MB |
|
|
142
|
+
|
|
143
|
+
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.
|
|
144
|
+
|
|
145
|
+
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.
|
|
146
|
+
|
|
147
|
+
**Required for every HTTP client:** set `HTTP_FROM` (`{ "shop": ["orders@notify.example.com"] }`) with the exact sender addresses that client may use. A client listed in `HTTP_CLIENTS` that has no entry is **refused** (`403`, `reason: "from_allowlist_required"`) — a leaked key must never be usable with every address on your domain. (Before 0.2.0 this only logged a warning.)
|
|
148
|
+
|
|
149
|
+
## Operating it
|
|
150
|
+
|
|
151
|
+
**Drill** — proves failover, de-duplication and lookup in one go:
|
|
152
|
+
|
|
153
|
+
```bash
|
|
154
|
+
URL=https://mailroom.<your-subdomain>.workers.dev
|
|
155
|
+
curl -X POST $URL/v1/drill -H "Authorization: Bearer $DRILL_TOKEN" \
|
|
156
|
+
-d '{"to":"you@example.com","mode":"fallback","key":"d1"}' # expect route: smtp2go (Resend key is deliberately wrong)
|
|
157
|
+
# same command again → expect status: duplicate
|
|
158
|
+
curl "$URL/v1/lookup?site=drill&key=drill:d1" -H "Authorization: Bearer $DRILL_TOKEN" # → the ledger row
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
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).
|
|
162
|
+
|
|
163
|
+
**Report** — `GET /v1/report?days=7` groups the ledger by site, tier, provider, outcome and recipient *domain* (never full addresses).
|
|
164
|
+
|
|
165
|
+
**Lift a suppression** — when someone fixed their mailbox or a bounce was a false positive:
|
|
166
|
+
|
|
167
|
+
```bash
|
|
168
|
+
curl -X POST $URL/v1/unsuppress -H "Authorization: Bearer $DRILL_TOKEN" \
|
|
169
|
+
-d '{"email":"someone@example.com","reasons":["hard_bounce"]}'
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
`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.
|
|
173
|
+
|
|
174
|
+
**Roll back** — Cloudflare dashboard → Workers → mailroom → Deployments → Rollback, or `npx wrangler rollback`.
|
|
175
|
+
|
|
176
|
+
### Configuration reference
|
|
177
|
+
|
|
178
|
+
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`, `LEDGER_RETENTION_DAYS` (positive integer; with a cron trigger, each run deletes `messages` and `webhook_events` rows older than that many days — missing, blank or invalid means nothing is deleted automatically; see below), `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).
|
|
179
|
+
|
|
180
|
+
**Ledger retention** — set `LEDGER_RETENTION_DAYS` (for example `180`) and add a cron trigger (`"triggers": { "crons": ["17 3 * * *"] }` in `wrangler.jsonc`). Each run deletes up to 5,000 `messages` rows and 5,000 `webhook_events` rows older than the limit (rows still `sending` are kept; the suppression list is never touched) and continues on the next run. Without a cron trigger nothing runs, so nothing is deleted. Deleting a `messages` row also forgets its idempotency key, so choose a period longer than any retry window your apps use.
|
|
181
|
+
|
|
182
|
+
**Previous failure reason** — when a failed key is retried, the earlier error is copied to `last_error` before `error` is cleared, so `GET /v1/lookup` still shows why the first attempt failed even if the retry succeeded.
|
|
183
|
+
|
|
184
|
+
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).
|
|
185
|
+
|
|
186
|
+
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.
|
|
187
|
+
|
|
188
|
+
## Development
|
|
189
|
+
|
|
190
|
+
```bash
|
|
191
|
+
npm test # node --test; runs the real migrations/*.sql against Node's built-in SQLite
|
|
192
|
+
npm run typecheck
|
|
193
|
+
npm run clean-scan # blocks keys, account ids and real email addresses from ever being committed
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
`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.
|
|
197
|
+
|
|
198
|
+
## Contributing, support and security
|
|
199
|
+
|
|
200
|
+
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.
|
|
201
|
+
|
|
202
|
+
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).
|
|
203
|
+
|
|
204
|
+
Before you deploy, read [docs/security-model.md](docs/security-model.md): who mailroom trusts, what personal data the ledger holds (and how to set an 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.
|
|
205
|
+
|
|
206
|
+
## License
|
|
207
|
+
|
|
208
|
+
[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.3.0 -->
|
package/bin/mailroom.mjs
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// 電子報櫃台指令入口。預設值(名單、寄件人、樣板…)放在一個設定模組,用 --config <路徑> 或環境變數 MAILROOM_CONFIG 指定;
|
|
3
|
+
// 模組的 default export 是 CliDefaults。沒給就只能用命令列旗標。
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { resolve } from 'node:path';
|
|
6
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
7
|
+
import { dirname } from 'node:path';
|
|
8
|
+
// 原始碼資料夾裡(有 src)優先用 src,免得打包留下的舊 dist 蓋過最新的程式;裝成套件時沒有 src,用建置好的 JS(Node 不替 node_modules 裡的 .ts 去除型別)。
|
|
9
|
+
import { existsSync } from 'node:fs';
|
|
10
|
+
const srcMain = new URL('../src/cli/main.ts', import.meta.url);
|
|
11
|
+
const main = existsSync(srcMain) && !import.meta.url.includes('/node_modules/') ? await import(srcMain.href) : await import('../dist/cli/main.js');
|
|
12
|
+
const { runCli } = main;
|
|
13
|
+
|
|
14
|
+
const argv = process.argv.slice(2);
|
|
15
|
+
let cfgPath = process.env.MAILROOM_CONFIG;
|
|
16
|
+
const i = argv.indexOf('--config');
|
|
17
|
+
if (i !== -1) {
|
|
18
|
+
cfgPath = argv[i + 1];
|
|
19
|
+
argv.splice(i, 2);
|
|
20
|
+
}
|
|
21
|
+
const defaults = cfgPath ? (await import(pathToFileURL(resolve(cfgPath)).href)).default : {};
|
|
22
|
+
process.exitCode = await runCli(argv, {
|
|
23
|
+
defaults,
|
|
24
|
+
env: process.env,
|
|
25
|
+
io: { readFile: (p) => readFile(p, 'utf8'), writeFile: async (p, b) => { await mkdir(dirname(p), { recursive: true }); await writeFile(p, b); } },
|
|
26
|
+
});
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// 群發的設定值(門檻、配速、暖機過關條件)。引擎給保守預設值;部署端用 JSON 只覆寫想改的欄位。
|
|
2
|
+
export const DEFAULT_BROADCAST_CONFIG = Object.freeze({
|
|
3
|
+
site: 'newsletter',
|
|
4
|
+
maxPerDay: 3000,
|
|
5
|
+
rateFactor: 0.8,
|
|
6
|
+
paceMinutes: 150,
|
|
7
|
+
waveGapMinutes: 60,
|
|
8
|
+
waveGateWaitMinutes: 30,
|
|
9
|
+
waveGateBounceRate: 0.02,
|
|
10
|
+
brakeMinSent: 200,
|
|
11
|
+
brakeHardBounceRate: 0.04,
|
|
12
|
+
brakeComplaintCount: 3,
|
|
13
|
+
brakeComplaintRate: 0.001,
|
|
14
|
+
domainBounceRate: 0.04,
|
|
15
|
+
domainComplaintRate: 0.0008,
|
|
16
|
+
domainWindowDays: 30,
|
|
17
|
+
domainMinSent: 200,
|
|
18
|
+
domainMinComplaints: 1,
|
|
19
|
+
waveGateMinSent: 1,
|
|
20
|
+
startGraceMinutes: 360,
|
|
21
|
+
stuckMinutes: 10,
|
|
22
|
+
stallMinutes: 30,
|
|
23
|
+
maxAttempts: 3,
|
|
24
|
+
permanentStreak: 5,
|
|
25
|
+
throttleRetrySeconds: 30,
|
|
26
|
+
utcOffsetHours: 8,
|
|
27
|
+
limitsRefreshMinutes: 60,
|
|
28
|
+
gateWaitHours: 72,
|
|
29
|
+
gateBounceRate: 0.02,
|
|
30
|
+
gateComplaintRate: 0.001,
|
|
31
|
+
gateOpenDrop: 0.05,
|
|
32
|
+
gateMaxFails: 2,
|
|
33
|
+
});
|
|
34
|
+
const SITE = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
|
35
|
+
/** 「下限」類設定的上限:設太大等於把那道煞車關掉,超過就當寫錯、用預設值(並在 log 留一行)。 */
|
|
36
|
+
const MAX_VALUE = { domainMinComplaints: 10, waveGateMinSent: 100, startGraceMinutes: 2880 };
|
|
37
|
+
/**
|
|
38
|
+
* 合併設定:只收「型別對、數值合理」的欄位,其他一律用預設值(寫錯不能變成「不設防」)。
|
|
39
|
+
* 比率要在 0~1 之間;次數、分鐘要是正數。
|
|
40
|
+
*/
|
|
41
|
+
export function resolveConfig(over) {
|
|
42
|
+
let o = {};
|
|
43
|
+
if (typeof over === 'string') {
|
|
44
|
+
try {
|
|
45
|
+
const parsed = JSON.parse(over);
|
|
46
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
|
|
47
|
+
o = parsed;
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
console.error('bad broadcast config json');
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
else if (over && typeof over === 'object')
|
|
54
|
+
o = over;
|
|
55
|
+
const out = { ...DEFAULT_BROADCAST_CONFIG };
|
|
56
|
+
for (const key of Object.keys(DEFAULT_BROADCAST_CONFIG)) {
|
|
57
|
+
const v = o[key];
|
|
58
|
+
if (v === undefined || v === null)
|
|
59
|
+
continue;
|
|
60
|
+
if (key === 'site') {
|
|
61
|
+
if (typeof v === 'string' && SITE.test(v))
|
|
62
|
+
out.site = v;
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
const n = typeof v === 'string' && v.trim() !== '' ? Number(v) : v;
|
|
66
|
+
if (typeof n !== 'number' || !Number.isFinite(n))
|
|
67
|
+
continue;
|
|
68
|
+
const isRate = key.endsWith('Rate') || key === 'rateFactor' || key === 'gateOpenDrop';
|
|
69
|
+
if (isRate ? n < 0 || n > 1 : key === 'utcOffsetHours' ? n < -14 || n > 14 : n <= 0)
|
|
70
|
+
continue;
|
|
71
|
+
const cap = MAX_VALUE[key];
|
|
72
|
+
if (cap !== undefined && n > cap) {
|
|
73
|
+
console.error(`broadcast config ${key} above ${cap}: using the default`);
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
out[key] = n;
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// 把「暫停原因」翻成人看得懂的說明:哪一道門檻、當時的分子分母、建議下一步。唯讀,不改任何狀態。
|
|
2
|
+
// 原因字串的格式由 dispatch.ts 的 brake() 寫入(brake:hard_bounce_rate:3/200、brake:wave_gate:wave1:2/30…)。
|
|
3
|
+
const ratio = (a, b) => (b > 0 ? a / b : 0);
|
|
4
|
+
export function explainPause(reason, cfg) {
|
|
5
|
+
if (!reason)
|
|
6
|
+
return null;
|
|
7
|
+
const nd = /(\d+)\/(\d+)\s*$/.exec(reason);
|
|
8
|
+
const n = nd ? Number(nd[1]) : undefined;
|
|
9
|
+
const d = nd ? Number(nd[2]) : undefined;
|
|
10
|
+
const rate = n !== undefined && d !== undefined ? ratio(n, d) : undefined;
|
|
11
|
+
const base = { numerator: n, denominator: d, rate };
|
|
12
|
+
const m = /^brake:([a-z_]+)/.exec(reason);
|
|
13
|
+
const code = m ? m[1] : (reason.split(':')[0] ?? reason).trim();
|
|
14
|
+
switch (code) {
|
|
15
|
+
case 'hard_bounce_rate':
|
|
16
|
+
return { code, ...base, summary: `Hard bounces reached the issue brake: ${n} of ${d} sent.`, threshold: { hardBounceRate: cfg.brakeHardBounceRate, minSent: cfg.brakeMinSent }, suggestion: 'Check the bounce reasons and the list source; resume only if the bounces are explained (counting restarts from the resume).', needsDomainRelease: false, resumable: true };
|
|
17
|
+
case 'complaint_rate':
|
|
18
|
+
return { code, ...base, summary: `Complaints reached the issue brake: ${n} of ${d} sent.`, threshold: { complaintCount: cfg.brakeComplaintCount, complaintRate: cfg.brakeComplaintRate }, suggestion: 'Look at who complained (their segment and source) before resuming; complaints are the strongest signal to providers.', needsDomainRelease: false, resumable: true };
|
|
19
|
+
case 'wave_gate':
|
|
20
|
+
return { code, ...base, summary: `The previous wave had too many hard bounces to open the next wave: ${n} of ${d} sent.`, threshold: { waveGateBounceRate: cfg.waveGateBounceRate, waveGateMinSent: cfg.waveGateMinSent }, suggestion: 'Small waves make this brake touchy: check whether the bounces are real (same domain? typos?) and consider raising waveGateMinSent.', needsDomainRelease: false, resumable: true };
|
|
21
|
+
case 'domain_hold': {
|
|
22
|
+
const dr = /(?:bounce_rate|complaint_rate):(\d+)\/(\d+)/.exec(reason);
|
|
23
|
+
const dn = dr ? Number(dr[1]) : undefined;
|
|
24
|
+
const dd = dr ? Number(dr[2]) : undefined;
|
|
25
|
+
const isComplaint = reason.includes('complaint_rate');
|
|
26
|
+
return { code, numerator: dn, denominator: dd, rate: dn !== undefined && dd !== undefined ? ratio(dn, dd) : undefined, summary: `The sender domain is on hold: ${isComplaint ? 'complaints' : 'hard bounces'} ${dn} of ${dd} sent in the rolling window.`, threshold: isComplaint ? { complaintRate: cfg.domainComplaintRate, minSent: cfg.domainMinSent, minComplaints: cfg.domainMinComplaints } : { hardBounceRate: cfg.domainBounceRate, minSent: cfg.domainMinSent }, suggestion: 'All newsletters on the domain stopped. Check the numbers (a single complaint can trip it on a small sample), then release the domain hold and resume.', needsDomainRelease: true, resumable: true };
|
|
27
|
+
}
|
|
28
|
+
case 'queue_stalled':
|
|
29
|
+
return { code, summary: `Work was handed to the queue but nothing came back for ${cfg.stallMinutes} minutes.`, threshold: { stallMinutes: cfg.stallMinutes }, suggestion: 'Check the queue and consumer logs (and the dead-letter queue) first; resume once results flow again.', needsDomainRelease: false, resumable: true };
|
|
30
|
+
case 'provider_enforcement':
|
|
31
|
+
case 'provider_account_paused':
|
|
32
|
+
return { code, summary: `The provider reports the account is not healthy (${reason.split(':').slice(2).join(':') || code}).`, suggestion: 'Look at the provider console. Do not resume until the provider says the account is healthy again.', needsDomainRelease: false, resumable: true };
|
|
33
|
+
case 'start_stale':
|
|
34
|
+
return { code, summary: `The issue started but not one mail was handed to the provider within ${cfg.startGraceMinutes} minutes.`, threshold: { startGraceMinutes: cfg.startGraceMinutes }, suggestion: 'Usually the provider limits could not be read when it started (key or API problem) or the queue is not moving. Fix that first; resuming restarts the timer.', needsDomainRelease: false, resumable: true };
|
|
35
|
+
case 'permanent_streak':
|
|
36
|
+
return { code, summary: `Sending stopped after ${reason.split(':')[2] ?? cfg.permanentStreak} permanent failures in a row.`, suggestion: 'A run of permanent failures usually means a configuration problem (sender, domain verification, key), not bad addresses. Fix the cause before resuming.', needsDomainRelease: false, resumable: false };
|
|
37
|
+
case 'freeze_blocked':
|
|
38
|
+
return { code, summary: `The list could not be frozen: ${reason.split(':').slice(2).join(':')}.`, suggestion: 'Fix the audience or warm-up plan, then cancel and rebuild this issue.', needsDomainRelease: false, resumable: false };
|
|
39
|
+
case 'reconcile_mismatch':
|
|
40
|
+
return { code, summary: `Reconciliation does not add up: ${reason.slice(reason.indexOf(':') + 1)}.`, suggestion: 'Run the reconcile command and read the differences; do not resume until a person has explained them.', needsDomainRelease: false, resumable: false };
|
|
41
|
+
case 'render_error':
|
|
42
|
+
case 'rejected':
|
|
43
|
+
return { code, summary: `Sending stopped on an error: ${reason.slice(reason.indexOf(':') + 1)}.`, suggestion: 'This is a configuration or content problem, not a rate. Fix the cause before resuming.', needsDomainRelease: false, resumable: false };
|
|
44
|
+
case 'manual':
|
|
45
|
+
case 'cancelled':
|
|
46
|
+
return { code, summary: `Paused by a person: ${reason.slice(reason.indexOf(':') + 1).trim()}`, suggestion: 'Resume with a note when the reason no longer applies.', needsDomainRelease: false, resumable: code === 'manual' };
|
|
47
|
+
default:
|
|
48
|
+
return { code, summary: `Paused: ${reason}`, suggestion: 'Unknown reason: read the issue status before resuming.', needsDomainRelease: false, resumable: true };
|
|
49
|
+
}
|
|
50
|
+
}
|
package/dist/cli/args.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// 指令列參數:--key value、--key=value、--flag。不收未知旗標(打錯字不能被默默吞掉)。
|
|
2
|
+
export function parseArgs(argv, spec) {
|
|
3
|
+
const values = new Set(spec.values);
|
|
4
|
+
const booleans = new Set(spec.booleans);
|
|
5
|
+
const out = { positional: [], flags: {} };
|
|
6
|
+
for (let i = 0; i < argv.length; i++) {
|
|
7
|
+
const a = argv[i];
|
|
8
|
+
if (!a.startsWith('--')) {
|
|
9
|
+
out.positional.push(a);
|
|
10
|
+
continue;
|
|
11
|
+
}
|
|
12
|
+
const eq = a.indexOf('=');
|
|
13
|
+
const key = a.slice(2, eq === -1 ? undefined : eq);
|
|
14
|
+
if (booleans.has(key)) {
|
|
15
|
+
if (eq !== -1)
|
|
16
|
+
return { error: `--${key} does not take a value` };
|
|
17
|
+
out.flags[key] = true;
|
|
18
|
+
}
|
|
19
|
+
else if (values.has(key)) {
|
|
20
|
+
const v = eq !== -1 ? a.slice(eq + 1) : argv[++i];
|
|
21
|
+
if (v === undefined || (eq === -1 && v.startsWith('--')))
|
|
22
|
+
return { error: `--${key} needs a value` };
|
|
23
|
+
out.flags[key] = v;
|
|
24
|
+
}
|
|
25
|
+
else
|
|
26
|
+
return { error: `unknown option --${key}` };
|
|
27
|
+
}
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// 引擎回的失敗原因 → 人看得懂的一句話+下一步。找不到對照的,照實印原因代碼。
|
|
2
|
+
const TABLE = {
|
|
3
|
+
not_found: ['No such issue.', 'Check the issue id with `campaign status <id>`; create it with `campaign create` first.'],
|
|
4
|
+
illegal_transition: ['The issue is not in a state where this is allowed.', 'Run `campaign status <id>` to see the current state and what comes next.'],
|
|
5
|
+
illegal_state: ['The issue is not in a state where this is allowed (retry-failed works only while it is sending or paused; a finished (done) issue is closed for good: recipients that failed are recorded with their reason).', 'Run `campaign status <id>` to see the current state.'],
|
|
6
|
+
locked: ['The content is locked: sending has started.', 'Pause the issue first if it must change; a sent issue cannot be edited.'],
|
|
7
|
+
changed_meanwhile: ['The issue changed while the command ran.', 'Run `campaign status <id>` and try again.'],
|
|
8
|
+
conflict: ['An issue with this id already exists.', 'Use a different id or look at the existing one.'],
|
|
9
|
+
domain_held: ['The sender domain is on hold: every newsletter is stopped.', 'Read `campaign status <id>`, then release it with `hold release --note "..." --yes` (or, when this issue paused because of the hold: `campaign release <id> --release-domain`).'],
|
|
10
|
+
preview_required: ['This content has not been previewed yet (or it changed after the preview).', 'Run `campaign preview <id> --yes`, let the owner look at it, then approve.'],
|
|
11
|
+
duplicate_content: ['The same content already exists under another id.', 'Use the existing issue (or see the line above for what to change).'],
|
|
12
|
+
note_required: ['A note is required: who said yes, when, where.', 'Add --note "..."'],
|
|
13
|
+
reason_required: ['A reason is required.', 'Add --reason "..."'],
|
|
14
|
+
not_approved: ['The approval does not match the current content.', 'Preview and approve the current content again.'],
|
|
15
|
+
preflight_not_passed: ['The pre-send check has not passed for the current content.', 'Run `campaign create` again (or fix the source) until the check passes.'],
|
|
16
|
+
web_url_required: ['The issue has no web version URL.', 'Recreate it with --web-url.'],
|
|
17
|
+
bad_time: ['The time could not be understood.', 'Use "YYYY-MM-DD HH:MM" (local time) or a full ISO time.'],
|
|
18
|
+
unknown_plan: ['The warm-up plan does not exist.', 'Define it with the warm-up API before scheduling.'],
|
|
19
|
+
unknown_list: ['The list does not exist.', 'Check the list id.'],
|
|
20
|
+
recipient_not_allowed: ['That address is not on the test recipient list.', 'Test mail only goes to the addresses configured as TEST_RECIPIENTS.'],
|
|
21
|
+
test_recipients_not_configured: ['Test mail is not enabled on this deployment.', 'Set TEST_RECIPIENTS on the Worker.'],
|
|
22
|
+
bad_recipients: ['Give 1 to 10 test addresses.', 'Use --to a@example.com,b@example.com'],
|
|
23
|
+
bad_prefix: ['The subject prefix is not valid.', 'At most 20 characters, no line breaks.'],
|
|
24
|
+
not_uncertain: ['That recipient is not in the "uncertain" state.', 'Run `campaign status <id>` to see who is.'],
|
|
25
|
+
bad_json: ['The request body was not valid JSON.', 'This is a bug in the command: report it.'],
|
|
26
|
+
};
|
|
27
|
+
export function friendly(reason, extra) {
|
|
28
|
+
const t = TABLE[reason];
|
|
29
|
+
const head = t ? `${t[0]} (${reason})` : `Refused: ${reason}`;
|
|
30
|
+
return [head, extra, t ? `Next: ${t[1]}` : 'Next: read the reason above; `campaign status <id>` shows the current state.'].filter(Boolean).join('\n');
|
|
31
|
+
}
|