@joelincc/mailroom 0.3.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 +8 -4
- package/dist/cli/errors.js +6 -0
- package/dist/cli/main.js +60 -2
- package/dist/compose/compose.js +51 -0
- package/dist/compose/markdown.js +837 -277
- package/dist/compose/render.js +8 -3
- package/docs/composing.md +25 -4
- package/docs/export.md +2 -1
- package/docs/lists.md +4 -2
- package/docs/security-model.md +2 -0
- package/docs/ses.md +1 -1
- package/docs/tracking.md +102 -0
- package/docs/unsubscribe.md +11 -4
- package/docs/welcome.md +72 -0
- package/migrations/0008_tracking.sql +5 -0
- package/migrations/0009_welcome.sql +17 -0
- package/package.json +3 -1
- package/src/broadcast/campaigns.ts +21 -8
- package/src/broadcast/dispatch.ts +16 -3
- package/src/broadcast/events.ts +6 -3
- package/src/broadcast/worker.ts +44 -3
- package/src/cli/errors.ts +6 -0
- package/src/cli/main.ts +51 -2
- package/src/compose/compose.ts +40 -0
- package/src/compose/markdown.ts +796 -247
- package/src/compose/render.ts +8 -3
- package/src/core.ts +3 -1
- package/src/feedback.ts +21 -4
- package/src/index.ts +31 -6
- package/src/list-routes.ts +18 -5
- package/src/lists.ts +13 -2
- package/src/track.ts +409 -0
- package/src/welcome.ts +257 -0
package/README.md
CHANGED
|
@@ -11,11 +11,11 @@ Your apps hand a message to one Worker; the Worker does everything it can to get
|
|
|
11
11
|
|
|
12
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
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.
|
|
14
|
+
- **Suppression list** — hard bounces and spam complaints are recorded and future sends to that address are blocked (`suppressed`), across all your apps. A complaint about a newsletter only stops newsletters (sign-in and notification mail keep going).
|
|
15
15
|
- **Bounce / complaint feedback** — Resend webhooks (Svix-signed) and Cloudflare Email Sending events update the ledger and the suppression list.
|
|
16
16
|
- **A D1 ledger** — one row per message: recipient, sender, subject, provider, provider id, outcome, later events. Message bodies are never stored.
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
Transactional sends (`send()`, `POST /v1/send`) reject `stream: "marketing"`. Newsletters go through the separate, opt-in newsletter desk below (lists, unsubscribe, broadcasting, tracking), which only sends to people on a list they subscribed to. It is not for cold email, and never will be — only send to people who asked to hear from you.
|
|
19
19
|
|
|
20
20
|
## Composing (preview)
|
|
21
21
|
|
|
@@ -30,6 +30,9 @@ on bounces and complaints, and a reconciliation that must add up before an issue
|
|
|
30
30
|
postmans: Amazon SES with signed SNS events ([docs/ses.md](docs/ses.md)) and a fake one for development. See
|
|
31
31
|
[docs/broadcast.md](docs/broadcast.md).
|
|
32
32
|
|
|
33
|
+
Click and open tracking runs on your own tracking host: signed per-recipient tokens, redirects only to links stored with the
|
|
34
|
+
issue, scanner clicks and prefetched opens marked rather than deleted. See [docs/tracking.md](docs/tracking.md).
|
|
35
|
+
|
|
33
36
|
## How it works
|
|
34
37
|
|
|
35
38
|
```
|
|
@@ -137,7 +140,8 @@ If your app can't reach the mailroom at all, queue the message locally and retry
|
|
|
137
140
|
| `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
141
|
| `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
142
|
| `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 |
|
|
143
|
+
| `PUT /v1/lists/{id}`, `POST /v1/lists/{id}/import`, `POST /v1/lists/{id}/segments`, `PUT`/`GET /v1/lists/{id}/welcome` | Newsletter list management ([docs/lists.md](docs/lists.md)) and the welcome mail ([docs/welcome.md](docs/welcome.md)) | `DRILL_TOKEN`, same quota; bodies capped at 1.5 MB |
|
|
144
|
+
| `GET /c/{token}`, `GET /o/{token}.gif` on the `TRACK_BASE_URL` host | Click redirect and open pixel ([docs/tracking.md](docs/tracking.md)) | the signed token itself |
|
|
141
145
|
| `/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
146
|
|
|
143
147
|
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.
|
|
@@ -169,7 +173,7 @@ curl -X POST $URL/v1/unsuppress -H "Authorization: Bearer $DRILL_TOKEN" \
|
|
|
169
173
|
-d '{"email":"someone@example.com","reasons":["hard_bounce"]}'
|
|
170
174
|
```
|
|
171
175
|
|
|
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.
|
|
176
|
+
`reasons` is required (`hard_bounce`, `complaint`, `unsubscribe`) so you can't accidentally clear a complaint. A complaint about a newsletter is stored as `unsubscribe` with detail `complaint…`; lifting it needs both `"unsubscribe"` and `"complaint"` in `reasons` (with `"unsubscribe"` alone it stays and is not listed in `removed`). Providers keep their own suppression lists (e.g. Resend → Suppressions); clear those there.
|
|
173
177
|
|
|
174
178
|
**Roll back** — Cloudflare dashboard → Workers → mailroom → Deployments → Rollback, or `npx wrangler rollback`.
|
|
175
179
|
|
package/dist/cli/errors.js
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
// 引擎回的失敗原因 → 人看得懂的一句話+下一步。找不到對照的,照實印原因代碼。
|
|
2
2
|
const TABLE = {
|
|
3
|
+
links_missing: ['The content uses a tracked link that is not in the link table.', 'Run `campaign create` again with the current engine (it stores the link table), or compose without trackBase.'],
|
|
4
|
+
bad_links: ['The link table is malformed (numbers must be 1..N, http(s) URLs only).', 'Compose the issue again with `campaign create`.'],
|
|
5
|
+
marketing_domain_not_set: ['Newsletters are not configured on this deployment (no sender domain), so the welcome mail cannot be checked or stored.', 'Set MARKETING_DOMAIN first; the welcome mail can be stored switched off (--disable).'],
|
|
6
|
+
enabled_required: ['Say explicitly whether the welcome mail is on.', 'Add --enable or --disable.'],
|
|
7
|
+
unsubscribe_link_missing: ['The welcome mail has no {{unsubscribe_url}} link in the HTML or the text.', 'Use a template whose footer contains the unsubscribe link.'],
|
|
8
|
+
tracking_not_supported: ['The welcome mail contains tracking placeholders.', 'Compose it without trackBase (the `welcome` command does this).'],
|
|
3
9
|
not_found: ['No such issue.', 'Check the issue id with `campaign status <id>`; create it with `campaign create` first.'],
|
|
4
10
|
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
11
|
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.'],
|
package/dist/cli/main.js
CHANGED
|
@@ -8,7 +8,7 @@ import { explainPause } from "../broadcast/explain.js";
|
|
|
8
8
|
import { resolveConfig } from "../broadcast/config.js";
|
|
9
9
|
import { friendly } from "./errors.js";
|
|
10
10
|
const VALUES = ['issue', 'source', 'post', 'web-url', 'list', 'from', 'subject', 'audience', 'source-ref', 'to', 'note', 'reason', 'at', 'out', 'contact', 'as', 'tz', 'base-url'];
|
|
11
|
-
const BOOLEANS = ['yes', 'json', 'offline', 'force', 'release-domain', 'to-defaults', 'help'];
|
|
11
|
+
const BOOLEANS = ['yes', 'json', 'offline', 'force', 'release-domain', 'to-defaults', 'help', 'enable', 'disable'];
|
|
12
12
|
class CliError extends Error {
|
|
13
13
|
code;
|
|
14
14
|
constructor(message, code = 1) {
|
|
@@ -35,6 +35,9 @@ Changes state (dry-run unless --yes is given):
|
|
|
35
35
|
cancel <id> --reason "..." --yes
|
|
36
36
|
retry-failed <id> --yes resolve <id> --contact N --as sent|failed --note "..." --yes
|
|
37
37
|
hold release --note "..." --yes release the sender-domain hold
|
|
38
|
+
welcome [--list L] show the list's welcome mail (subject, on/off)
|
|
39
|
+
welcome --source <file.md> --web-url U (--enable | --disable) [--list L] [--subject S] --yes
|
|
40
|
+
compose, check and store the welcome mail for new subscribers
|
|
38
41
|
Options: --json (machine-readable output), --base-url, --tz +08:00
|
|
39
42
|
Environment: MAILROOM_URL, MAILROOM_ADMIN_TOKEN`;
|
|
40
43
|
const ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
|
@@ -197,6 +200,7 @@ export async function runCli(argv, opts = {}) {
|
|
|
197
200
|
return r.ok ? 0 : 1;
|
|
198
201
|
}
|
|
199
202
|
case 'create': return await create();
|
|
203
|
+
case 'welcome': return await welcome();
|
|
200
204
|
case 'preview': {
|
|
201
205
|
const id = idArg();
|
|
202
206
|
if (!yes) {
|
|
@@ -402,11 +406,65 @@ export async function runCli(argv, opts = {}) {
|
|
|
402
406
|
if (!yes)
|
|
403
407
|
return dry(lines, data);
|
|
404
408
|
const sourceRef = (typeof flags['source-ref'] === 'string' ? flags['source-ref'] : undefined) ?? post?.ref ?? sourcePath;
|
|
405
|
-
const saved = await call('PUT', `/v1/campaigns/${issue}`, { list, subject: composed.subject, preheader: composed.preheader || undefined, from, ...(d.replyTo ? { replyTo: d.replyTo } : {}), html: composed.html, text: composed.text, headers: composed.headers, webUrl, sourceRef, audience });
|
|
409
|
+
const saved = await call('PUT', `/v1/campaigns/${issue}`, { list, subject: composed.subject, preheader: composed.preheader || undefined, from, ...(d.replyTo ? { replyTo: d.replyTo } : {}), html: composed.html, text: composed.text, headers: composed.headers, webUrl, sourceRef, audience, ...(composed.links.length ? { links: composed.links.map((l) => ({ index: l.index, url: l.url })) } : {}) });
|
|
406
410
|
const rec = await call('POST', `/v1/campaigns/${issue}/preflight`, { ok: check.ok, issues: check.issues.map((i) => ({ severity: i.severity, code: i.code, message: i.message })) });
|
|
407
411
|
emit([...lines, '', `saved as draft (${saved.changed ? 'new or changed' : 'unchanged'}); check recorded: ${rec.preflightOk ? 'passed' : 'failed'}`, rec.preflightOk ? `Next: campaign preview ${issue} --yes` : 'Next: fix the errors above in the source, then run create again (same id updates the draft).'], { ...data, saved, preflightOk: rec.preflightOk });
|
|
408
412
|
return rec.preflightOk ? 0 : 1;
|
|
409
413
|
}
|
|
414
|
+
async function welcome() {
|
|
415
|
+
const list = (typeof flags.list === 'string' ? flags.list : d.list) ?? '';
|
|
416
|
+
if (!ID.test(list))
|
|
417
|
+
throw new CliError('welcome needs a list: pass --list or set it in the defaults.', 2);
|
|
418
|
+
if (typeof flags.source !== 'string') {
|
|
419
|
+
const r = await api('GET', `/v1/lists/${list}/welcome`);
|
|
420
|
+
if (r.status === 404 && r.body.reason === 'not_found') {
|
|
421
|
+
emit([`${list}: no welcome mail stored (new subscribers get none).`, 'Next: welcome --source <file.md> --web-url https://... --disable --yes (store it switched off first, look at it, then --enable).'], { list, exists: false });
|
|
422
|
+
return 0;
|
|
423
|
+
}
|
|
424
|
+
if (r.status >= 400 || r.body.ok === false)
|
|
425
|
+
throw new CliError(friendly(String(r.body.reason ?? `http_${r.status}`)));
|
|
426
|
+
emit([`${list}: "${r.body.subject}" from ${r.body.from}`, `welcome mail is ${r.body.enabled ? 'ON (sent to first-time subscribers while newsletters are enabled)' : 'OFF'}; updated ${r.body.updatedAt}`], { list, exists: true, subject: r.body.subject, enabled: r.body.enabled, updatedAt: r.body.updatedAt });
|
|
427
|
+
return 0;
|
|
428
|
+
}
|
|
429
|
+
if (flags.enable === true && flags.disable === true)
|
|
430
|
+
throw new CliError('Pick one: --enable or --disable.', 2);
|
|
431
|
+
if (!d.template)
|
|
432
|
+
throw new CliError('No email template is configured.\nNext: pass `template` in the defaults (see docs/composing.md).');
|
|
433
|
+
const from = (typeof flags.from === 'string' ? flags.from : d.from) ?? '';
|
|
434
|
+
if (!from)
|
|
435
|
+
throw new CliError('The sender is required: pass --from or set it in the defaults.', 2);
|
|
436
|
+
let source;
|
|
437
|
+
try {
|
|
438
|
+
source = await io.readFile(flags.source);
|
|
439
|
+
}
|
|
440
|
+
catch {
|
|
441
|
+
throw new CliError(`Could not read the source file "${flags.source}".\nNext: check the path.`);
|
|
442
|
+
}
|
|
443
|
+
const webUrl = typeof flags['web-url'] === 'string' ? flags['web-url'] : '';
|
|
444
|
+
if (!webUrl)
|
|
445
|
+
throw new CliError('Pass --web-url https://... (the {{web_url}} link, for example the newsletter archive).', 2);
|
|
446
|
+
const template = createTemplate(d.template);
|
|
447
|
+
// 歡迎信不追蹤:不給 trackBase(歡迎信沒有期別的連結表)。
|
|
448
|
+
const { trackBase: _ignored, ...composeOpts } = d.composeDefaults ?? {};
|
|
449
|
+
const composed = compose({ ...composeOpts, source, template, issue: 'welcome', ...(typeof flags.subject === 'string' ? { subject: flags.subject } : {}) });
|
|
450
|
+
const check = await preflight(composed, { template, webUrl, checkLinks: flags.offline !== true, fetch: io.fetch });
|
|
451
|
+
const errors = check.issues.filter((i) => i.severity === 'error');
|
|
452
|
+
const lines = [
|
|
453
|
+
`welcome mail for ${list}: "${composed.subject}"`, `from ${from} {{web_url}} ${webUrl}`, `HTML ${composed.htmlBytes} bytes, ${composed.links.length} links (not tracked)`,
|
|
454
|
+
`pre-send check: ${check.ok ? 'PASSED' : `FAILED (${errors.length} error${errors.length === 1 ? '' : 's'})`}`,
|
|
455
|
+
...check.issues.map((i) => ` [${i.severity}] ${i.code}: ${i.message}${i.where ? ` (${i.where})` : ''}`),
|
|
456
|
+
];
|
|
457
|
+
const data = { list, subject: composed.subject, checkOk: check.ok, issues: check.issues };
|
|
458
|
+
if (!yes)
|
|
459
|
+
return dry(lines, data);
|
|
460
|
+
if (!check.ok)
|
|
461
|
+
throw new CliError(`${lines.join('\n')}\n\nNot stored: fix the errors above first.`, 1);
|
|
462
|
+
if (flags.enable !== true && flags.disable !== true)
|
|
463
|
+
throw new CliError('Say whether new subscribers should get it now: --enable or --disable.', 2);
|
|
464
|
+
const saved = await call('PUT', `/v1/lists/${list}/welcome`, { subject: composed.subject, from, ...(d.replyTo ? { replyTo: d.replyTo } : {}), html: composed.html, text: composed.text, webUrl, enabled: flags.enable === true });
|
|
465
|
+
emit([...lines, '', `stored (${saved.changed ? 'new or changed' : 'unchanged'}); welcome mail is ${saved.enabled ? 'ON' : 'OFF'}.`, saved.enabled ? 'It is sent only while newsletters are enabled on this deployment, and only to first-time subscribers.' : 'Next: look at it, then run again with --enable --yes.'], { ...data, saved });
|
|
466
|
+
return 0;
|
|
467
|
+
}
|
|
410
468
|
function previewLines(id, p, marked) {
|
|
411
469
|
const pf = p.preflight;
|
|
412
470
|
return [
|
package/dist/compose/compose.js
CHANGED
|
@@ -183,6 +183,7 @@ export function compose(opts) {
|
|
|
183
183
|
const parts = { subject, preheader, bodyHtml, bodyText, pixelUrl };
|
|
184
184
|
const html = t.renderHtml(parts);
|
|
185
185
|
const text = t.renderText(parts);
|
|
186
|
+
checkOutputForComments(parsed.blocks, parts, t, problems);
|
|
186
187
|
return {
|
|
187
188
|
subject,
|
|
188
189
|
preheader,
|
|
@@ -222,3 +223,53 @@ function flatBlocks(blocks) {
|
|
|
222
223
|
}
|
|
223
224
|
return out;
|
|
224
225
|
}
|
|
226
|
+
/** 數 <!--(含跳脫成 <!-- 的)出現幾次。 */
|
|
227
|
+
const commentMarks = (s) => s.split('<!--').length - 1 + (s.split('<!--').length - 1);
|
|
228
|
+
/**
|
|
229
|
+
* 最後一道保險:看「最終」HTML 與純文字版(不是解析樹)。把程式碼的內容遮掉重排一次,跟「只有樣板、沒有正文」的版本比:
|
|
230
|
+
* 程式碼以外多出任何一個 <!--,就代表有註解字樣會寄到讀者眼前(解析或排版哪裡出了錯),記 error 擋下。
|
|
231
|
+
* 樣板自己的 Outlook 條件註解(<!--[if mso]>)在兩邊一樣多,所以不會誤報。
|
|
232
|
+
*/
|
|
233
|
+
function checkOutputForComments(blocks, parts, t, problems) {
|
|
234
|
+
if (problems.some((p) => p.code === 'comment_leaked' || p.code === 'unclosed_comment'))
|
|
235
|
+
return; // 已經擋下,不重複報
|
|
236
|
+
const masked = structuredClone(blocks);
|
|
237
|
+
const mask = (bs) => {
|
|
238
|
+
const inl = (ns) => {
|
|
239
|
+
for (const n of ns) {
|
|
240
|
+
if (n.t === 'code')
|
|
241
|
+
n.v = '';
|
|
242
|
+
else if (n.t === 'strong' || n.t === 'em' || n.t === 'link')
|
|
243
|
+
inl(n.c);
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
for (const b of bs) {
|
|
247
|
+
if (b.t === 'code')
|
|
248
|
+
b.v = '';
|
|
249
|
+
else if (b.t === 'p' || b.t === 'h')
|
|
250
|
+
inl(b.c);
|
|
251
|
+
else if (b.t === 'quote')
|
|
252
|
+
mask(b.c);
|
|
253
|
+
else if (b.t === 'list')
|
|
254
|
+
for (const it of b.items)
|
|
255
|
+
mask(it);
|
|
256
|
+
else if (b.t === 'table') {
|
|
257
|
+
for (const c of b.head)
|
|
258
|
+
inl(c);
|
|
259
|
+
for (const r of b.rows)
|
|
260
|
+
for (const c of r)
|
|
261
|
+
inl(c);
|
|
262
|
+
}
|
|
263
|
+
else if (b.t === 'image' && b.link)
|
|
264
|
+
inl(b.link.c);
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
mask(masked);
|
|
268
|
+
const withBody = { ...parts, bodyHtml: renderBodyHtml(masked, t.theme, t.labels), bodyText: renderBodyText(masked, t.labels) };
|
|
269
|
+
const empty = { ...parts, bodyHtml: '', bodyText: '' };
|
|
270
|
+
const extraHtml = commentMarks(t.renderHtml(withBody)) - commentMarks(t.renderHtml(empty));
|
|
271
|
+
const extraText = commentMarks(t.renderText(withBody)) - commentMarks(t.renderText(empty));
|
|
272
|
+
if (extraHtml > 0 || extraText > 0) {
|
|
273
|
+
problems.push({ code: 'comment_leaked', severity: 'error', message: `信件${extraHtml > 0 ? ' HTML' : ''}${extraText > 0 ? ' 純文字版' : ''}在程式碼以外含有 <!-- 字樣,會原樣寄到讀者眼前;請檢查原稿裡的註解寫法` });
|
|
274
|
+
}
|
|
275
|
+
}
|