@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/dist/compose/render.js
CHANGED
|
@@ -52,7 +52,8 @@ function blockHtml(b, c, last = false) {
|
|
|
52
52
|
case 'list': {
|
|
53
53
|
const tag = b.ordered ? 'ol' : 'ul';
|
|
54
54
|
const items = b.items.map((it) => `<li class="mr-text" style="margin:0 0 8px;font-size:16px;line-height:1.8;${T(c)}">${listItemHtml(it, c)}</li>`).join('');
|
|
55
|
-
|
|
55
|
+
const start = b.ordered && b.start !== undefined ? ` start="${b.start}"` : '';
|
|
56
|
+
return `<${tag}${start} style="margin:0 0 ${mb};padding-left:24px">${items}</${tag}>`;
|
|
56
57
|
}
|
|
57
58
|
case 'code':
|
|
58
59
|
return `<pre class="mr-code mr-text" style="margin:0 0 ${mb};padding:12px 14px;background:${c.theme.codeBg};font-family:Menlo,Consolas,monospace;font-size:13px;line-height:1.6;white-space:pre-wrap;overflow-wrap:anywhere;color:${c.theme.text}">${escapeHtml(b.v)}</pre>`;
|
|
@@ -94,7 +95,11 @@ function inlineText(n, labels) {
|
|
|
94
95
|
const url = n.tu ?? n.href;
|
|
95
96
|
if (url === '')
|
|
96
97
|
return text;
|
|
97
|
-
|
|
98
|
+
// 讀者在網站上看得到的連結文字不能在純文字版消失:只有它就是印出來的網址、或是一串網址且整串出現在印出來的網址裡
|
|
99
|
+
// (沒追蹤的裸網址,後面只多了 utm)才省略。裸網址也一樣——網站上它的文字就是那串網址(緊貼在後面、沒空格的字也算在內),
|
|
100
|
+
// 追蹤轉址看不出來,所以照「文字 (網址)」印。
|
|
101
|
+
const shown = text.trim();
|
|
102
|
+
if (shown === '' || shown === url || (/^https?:\/\//i.test(shown) && url.includes(shown)))
|
|
98
103
|
return url;
|
|
99
104
|
return `${text} (${url})`;
|
|
100
105
|
}
|
|
@@ -115,7 +120,7 @@ function blockText(b, l, indent = '') {
|
|
|
115
120
|
case 'list':
|
|
116
121
|
return b.items
|
|
117
122
|
.map((it, i) => {
|
|
118
|
-
const mark = b.ordered ? `${
|
|
123
|
+
const mark = b.ordered ? `${(b.start ?? 1) + i}. ` : '- ';
|
|
119
124
|
const body = it.map((x) => blockText(x, l)).join('\n\n');
|
|
120
125
|
const [first, ...rest] = body.split('\n');
|
|
121
126
|
return pad([mark + first, ...rest.map((x) => (x === '' ? x : ' '.repeat(mark.length) + x))].join('\n'));
|
package/docs/composing.md
CHANGED
|
@@ -36,17 +36,38 @@ The HTML is stored once per issue — it is never rendered per recipient until s
|
|
|
36
36
|
|
|
37
37
|
### Markdown that works
|
|
38
38
|
|
|
39
|
-
Headings, paragraphs (a single newline becomes a line break), bold, italic, inline code, links, bare URLs (
|
|
40
|
-
punctuation is not part of the URL), images, lists (nested, ordered), block quotes, tables (with alignment), fenced code, rules.
|
|
39
|
+
Headings, paragraphs (a single newline becomes a line break), bold, italic, inline code, links, bare URLs, images, lists (nested, ordered, with their start number), block quotes, tables (with alignment), fenced and indented code, rules.
|
|
41
40
|
Also understood: `<https://…>` autolinks, `<a href="…">text</a>` (only the `href` and the text are kept — every other
|
|
42
41
|
attribute is dropped and the link goes through the normal checks and tracking), and paired `<b>` / `<strong>` / `<i>` / `<em>`.
|
|
43
42
|
HTML character references (` `, `&`, `'` …) are decoded once and escaped once.
|
|
44
43
|
|
|
45
|
-
|
|
44
|
+
A bare `http://` / `https://` URL is cut where the site cuts it: it runs to the next whitespace (a full-width space
|
|
45
|
+
or a no-break space counts) or `<`, and ASCII punctuation at the very end (`.` `,` `:` `;` `!` `?` `'` `*` `_` `~` `]`, an
|
|
46
|
+
unbalanced `)`) is not part of it. (One known difference: the rare ASCII characters `"` `{` `}` `|` `^` `\` end the link in
|
|
47
|
+
the email but not on the site; the text after them stays visible.) Everything else belongs to the link, including non-ASCII characters: a Japanese or Chinese path
|
|
48
|
+
(`https://ja.wikipedia.org/wiki/写真`), full-width punctuation, and words glued to the URL without a space
|
|
49
|
+
(`詳見https://example.com/a這篇文章`, `https://example.com/p/1看完再說`) — on the site all of that is link text, so it is link
|
|
50
|
+
text in the email too, and the destination carries the non-ASCII characters as `%XX`, as on the site. Such a link usually
|
|
51
|
+
points to a page that does not exist; the pre-send link check reports it (`link_broken`), and a URL whose last character is
|
|
52
|
+
full-width punctuation (`(https://example.com/a)`, `https://example.com/a。`) gets a `url_glued_text` warning. The fix in
|
|
53
|
+
the article is a space after the URL. The link text of `[text](url)` is never autolinked again (the site does not put a
|
|
54
|
+
link inside a link).
|
|
55
|
+
|
|
56
|
+
In the plain-text version a link is printed as `text (url)`, where `url` is the tracking URL (or the final URL without
|
|
57
|
+
tracking). The text is left out only when it adds nothing: when it is empty, when it is the printed URL itself, or when it
|
|
58
|
+
is a URL contained in the printed URL (an untracked link, which only gains `utm_*`). So a bare URL prints as
|
|
59
|
+
`https://example.com/a (https://t.example.com/c/…)`: the reader sees what the site shows, glued words included, and the
|
|
60
|
+
mail never silently drops text.
|
|
61
|
+
|
|
62
|
+
Block structure follows CommonMark (with GFM tables) for everything the email supports: the parser first decides which lines form which block — fenced or indented code, HTML comment block, paragraph, list item, quote, table, heading (ATX or setext) — and only then parses the inline content of each block. HTML comments are handled **in that same single pass**; there is no separate comment-stripping step that could disagree with the parser about where code is. A line that starts with `<!--` (indented at most three spaces) is a comment block that ends on the line containing `-->` (blank lines in between included); it can interrupt a paragraph, a list item or a quote, exactly as on a CommonMark site, and any text after `-->` on its last line is kept. Inside a paragraph, heading or table cell, inline code and comments are recognised in one left-to-right scan, so whichever starts first wins: `` `<!--` `` is code, `<!-- a ` b -->` is a comment. Inline code never crosses a block boundary, so a multi-line code span that meets a line starting with `<!--` ends there and that line is a comment (CommonMark behaviour). Code fences (``` and ~~~, longer fences, fences in lists and quotes) and indented code keep their `<!--` and `-->` text verbatim. Lazy continuation lines join a quote or list item only when its last block is an open paragraph.
|
|
63
|
+
|
|
64
|
+
Two safety nets run after that. First, a reconciliation: every `<!--` in the source must be accounted for as either a hidden comment or text inside code; if one is left over (a backslash-escaped `\<!--`, a `<!--` in image alt text or a URL), the issue gets a `comment_leaked` error. Second, the final email HTML and plain text are rendered again with code contents masked; if anything outside code still contains `<!--` (for example from `<!--`), that is also a `comment_leaked` error. A bare URL followed directly by a backtick, and an unfinished `<tag` after a comment on the same line, are errors too. Comments containing `--!>` (browsers end a comment there early) are an error (`comment_ambiguous`). Constructs that a website would pass through as raw HTML or hide in other ways are blocked with an error rather than imitated: a line holding a single tag such as `<em>`, `<br>` or `<a href="…">` on its own (an HTML block — inline tags inside a paragraph are fine), `<?…>`, `<!X…>` and `<![CDATA[…]]>` (`unsupported_html`), and link reference definitions `[name]: url` (`unsupported_syntax`), and footnote definitions the site would not show: a definition is kept only when it is a one-line paragraph line starting at column 0 (consecutive definition lines are fine), its label has no spaces and is defined once (labels are case-insensitive), its content is plain text (not a list, quote, heading, code, HTML or another definition), no indented continuation follows it, and a real footnote reference `[^x]` appears in the text (references inside code, comments, URLs, escapes, entities or the definitions themselves do not count, nor does one written right after a bare URL or email address, which the site absorbs into the link); anything else is an error, and so is a footnote reference inside link text. A link inside the text of another link is an error too (the site shows the outer brackets and URL literally; the mail would lose them). A footnote reference that the site absorbs into a preceding bare URL — also when brackets or emphasis wrap the URL, as in `(www.example.com**[^1]***)` or `**https://example.com**[^1]` — is itself an error (`unsupported_syntax`, fix: put a space before the reference), even if the same footnote is referenced properly elsewhere. Every URL in the run of non-space characters before the reference is checked, not only the first; a URL counts as closed only when it is the destination of something that really is a link on the site (`[text](url)`, ``, `<url>`, `<a href>`) — when link text contains another link, the site does not treat the outer brackets as a link, and its `](url)` is a bare URL. A tab in the structure at the start of a line (indentation, after `>`, after a list marker) is an error (`unsupported_syntax`): how a site lays it out depends on every enclosing container, so it cannot be predicted reliably; use spaces. Tabs inside fenced code (Go, Makefiles), also in lists and quotes, are fine and kept as they are; in indented code only the four columns of indentation must be spaces. Like the site's renderer, an ordered list that does not start at 1, or an empty list item, is not recognised right after an indented code block or as the first block of a list item or quote that interrupts a paragraph; that line becomes a paragraph. A table needs a delimiter row containing `|` that is indented less than four spaces; a list item, heading or quote line never becomes a table header. These rules are checked by `tests/compose-fuzz.test.ts`, which generates random combinations of comments, code and blocks and compares the output with a CommonMark reference renderer (a dev dependency): nothing hidden on the site may appear in the email, nothing visible may disappear, and `<!--` / `-->` inside code stay verbatim — unless the issue is blocked with an error. CI runs a small sample; run `MAILROOM_FUZZ_N=24000 npm test` for a long run. A bare URL that has `[`, `*` or a backtick glued to it in the same word (or an HTML entity right before it), `![^x]`, and a footnote reference after nested brackets are errors as well: the site absorbs such runs into one link. Baseline at the time of writing (keep it current when the parser changes): the built-in generator gives zero violations on 4 × 24,000 samples (about 40 % of them blocked with an error). Several additional adversarial generators written during review (nested containers with tabs, footnotes, inline-symbol soup) were run for about 350,000 more samples; all were clean except an inline-symbol generator that glues bare URLs, emphasis, links, footnote references and code without spaces. On 40,000 such samples it used to leave 213 cases (200 where words glued to a bare URL vanished from the plain-text email, 8 where code was split differently from the site, 5 where a footnote hidden on the site was printed in the email, inside runs like `(www.example.com**[^1]***)`); with the bare-URL and footnote rules above it leaves none: the 200 are now handled correctly (178) or blocked (22), and the other 13 are blocked (about 65 % of these samples are blocked in all). The other review generators were re-run for 320,000 samples with the same results as before. One known layout difference: after an HTML block inside a list item, a following under-indented line may be split into code differently from the site (content stays visible).
|
|
65
|
+
|
|
66
|
+
A line that holds only `<div>`, `<div lang="…">` or `</div>` (a language wrapper) is dropped and its content converted normally; a `div` with any other attribute (`hidden`, `style`, `class` …) is an error, so text meant to be hidden can never reach readers. Angle-bracket words that only look like tags (`<Research.example>`, `</p/100110>`) are reported with a hint to rewrite them or put them in backticks.
|
|
46
67
|
|
|
47
68
|
Everything else is **not** passed through: an unknown tag or an unknown block syntax (for example `:::note`) is recorded
|
|
48
69
|
as an `error` problem and the pre-send check fails, so nothing half-converted can be sent. So are an unclosed `<!--` comment
|
|
49
|
-
(`unclosed_comment`, wherever it starts) and an unclosed code fence (`unclosed_fence
|
|
70
|
+
(`unclosed_comment`, wherever it starts — on a website it hides everything after it) and an unclosed code fence (`unclosed_fence`, which turns the rest of the container into code); the text after them is kept in the output.
|
|
50
71
|
The exception is content that cannot work in an email — `<iframe>`, `<video>`, `<audio>`, `<embed>`, `<object>`, `<canvas>`
|
|
51
72
|
and a ```` ```mermaid ```` fence: it becomes a "view on the website" link card and an `info` problem.
|
|
52
73
|
|
package/docs/export.md
CHANGED
|
@@ -38,7 +38,8 @@ and have their own rate bucket (`_export`: 60 per minute, 1000 per day), separat
|
|
|
38
38
|
`detail` is the stored JSON (or `null`). Anything shaped like an email address is replaced with `[email]` when the event is recorded and again on export (`@channel`-style handles are not addresses and stay). Contract the analytics side relies on:
|
|
39
39
|
|
|
40
40
|
- `detail.suspect = "scanner"` marks a click that a security scanner made (see `docs/composing.md`). Keep these rows, do not count them.
|
|
41
|
-
- **`detail.prefetch = true` must be written explicitly by the tracking service** for opens that mail-privacy prefetching made. The user-agent string (`detail.ua`) is only a fallback hint and is not reliable
|
|
41
|
+
- **`detail.prefetch = true` must be written explicitly by the tracking service** for opens that mail-privacy prefetching made. The built-in tracker (`docs/tracking.md`) does this; the user-agent string (`detail.ua`) is only a fallback hint and is not reliable. Check a real message end to end before relying on it.
|
|
42
|
+
- Built-in tracker events have `provider = "self"`; `detail.scannerRule` says why a click was marked (`burst`, `head`, `asn`).
|
|
42
43
|
- `detail.linkIndex` / `detail.url` identify the link of a click.
|
|
43
44
|
- Unsubscribes are recorded by the engine itself when someone goes from subscribed to unsubscribed through the unsubscribe page, the one-click endpoint or an unsubscribe mail: `type = "unsubscribe"`, `detail = { via: "link" | "one_click" | "mailto", list, reason? }`. Repeating the request records nothing more. Unsubscribes made through the list API or a member-centre sync record no event, so a per-issue unsubscribe count only counts people who left from a mail of that issue.
|
|
44
45
|
|
package/docs/lists.md
CHANGED
|
@@ -8,7 +8,7 @@ Lists are the source of truth for "who gets the newsletter". They live in the sa
|
|
|
8
8
|
- `contacts`: one row per address, shared by every list. Addresses are trimmed and lower-cased.
|
|
9
9
|
- `lists`: one row per newsletter (`weekly`, `promo`, ...). Create one with `PUT /v1/lists/{id}`.
|
|
10
10
|
- `list_members`: a person's state on one list: `subscribed` or `unsubscribed`, where they came from, an optional engagement group.
|
|
11
|
-
- `suppressions` (existing): global refusals. It only holds hard bounces, complaints and "no newsletters at all".
|
|
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
12
|
**Unsubscribing from one list is recorded in `list_members` only**, so someone on two lists can leave one and keep the other.
|
|
13
13
|
|
|
14
14
|
## Rules
|
|
@@ -24,12 +24,13 @@ Lists are the source of truth for "who gets the newsletter". They live in the sa
|
|
|
24
24
|
## Internal interface (service binding)
|
|
25
25
|
|
|
26
26
|
```ts
|
|
27
|
-
env.MAILROOM.listSubscribe({ list, email, source, consentVersion, name? }) // 'subscribed' | 'already' | 'blocked'
|
|
27
|
+
env.MAILROOM.listSubscribe({ list, email, source, consentVersion, name? }) // { status: 'subscribed', firstTime } | { status: 'already' | 'blocked' }
|
|
28
28
|
env.MAILROOM.listUnsubscribe({ list, email, source }) // 'unsubscribed' | 'not_member'
|
|
29
29
|
env.MAILROOM.listStatus({ list, email }) // 'subscribed' | 'unsubscribed' | 'not_found' | 'blocked'
|
|
30
30
|
env.MAILROOM.listMembers({ list, status?, cursor?, limit? }) // { members, next }, 1,000 per page
|
|
31
31
|
```
|
|
32
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).
|
|
33
34
|
Each `listMembers` row has `suppressed` (the address is on the global suppression list, same meaning as `listStatus` = `blocked`) and `unsubReason`.
|
|
34
35
|
Bad input returns `{ status: 'rejected', reason }` (`bad_email`, `bad_list`, `unknown_list`, `bad_source`, ...) instead of throwing.
|
|
35
36
|
`listStatus` reports `blocked` for a subscribed member who is on the global suppression list; an unsubscribed member always shows `unsubscribed`.
|
|
@@ -41,6 +42,7 @@ Bad input returns `{ status: 'rejected', reason }` (`bad_email`, `bad_list`, `un
|
|
|
41
42
|
|---|---|---|
|
|
42
43
|
| `PUT /v1/lists/{id}` | `{ name, fromAddr?, replyTo?, welcomeTemplate? }` | create or update |
|
|
43
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` |
|
|
44
46
|
| `POST /v1/lists/{id}/import` | `{ importedFrom, rows, dryRun?, expected? }` | up to 2,000 rows per call; see below |
|
|
45
47
|
|
|
46
48
|
## Importing
|
package/docs/security-model.md
CHANGED
|
@@ -13,6 +13,7 @@ what each secret can do if it leaks, and what you should harden.
|
|
|
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
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). |
|
|
16
17
|
| Everyone else | — | `GET /` returns a plain-text health check. `POST /webhooks/resend` answers 401, 411 or 413. Everything else is 404. |
|
|
17
18
|
|
|
18
19
|
Mailroom does **not** check that a recipient opted in, does not scan message content, and does not sanitise HTML.
|
|
@@ -55,6 +56,7 @@ 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
|
package/docs/ses.md
CHANGED
|
@@ -58,7 +58,7 @@ Notifications are normalised to provider events (one per recipient) and handed t
|
|
|
58
58
|
| `Bounce`, `Transient` / `MailboxFull` | `bounce` / `Transient`, cause `mailbox` | counts toward the streak (3 issues → `hard_bounce`) |
|
|
59
59
|
| `Bounce`, `Transient` / `MessageTooLarge`, `ContentRejected`, `AttachmentRejected` | cause `content` | not counted |
|
|
60
60
|
| `Bounce`, `Transient` / `General`, `CustomTimeoutExceeded`; `Undetermined` | no cause | not counted |
|
|
61
|
-
| `Complaint` | `complaint` |
|
|
61
|
+
| `Complaint` | `complaint` | newsletters stop (suppression `unsubscribe`, detail `complaint`), unsubscribed from every list; transactional mail is not blocked (see unsubscribe.md) |
|
|
62
62
|
| `Complaint` with feedback type `not-spam` | — | ignored (a correction, not a complaint) |
|
|
63
63
|
| `Reject`, `Rendering Failure` | `reject` | — |
|
|
64
64
|
| `DeliveryDelay` | `delay` | — |
|
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.
|
package/docs/unsubscribe.md
CHANGED
|
@@ -88,12 +88,19 @@ Why `setReject` and not `throw`: the Cloudflare docs only state that `setReject(
|
|
|
88
88
|
| Event | Effect |
|
|
89
89
|
|---|---|
|
|
90
90
|
| `bounce` / `permanent` | `suppressions` `hard_bounce`. Blocks **every** stream, including sign-in notices. List membership is left alone. |
|
|
91
|
-
| `complaint` | `suppressions` `complaint` (blocks every stream) **and** every list the person is on becomes `unsubscribed` with `unsub_source = 'complaint'` (earlier self-unsubscribes keep their own time and source). |
|
|
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. |
|
|
92
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. |
|
|
93
94
|
| `delivery` | Clears the address's transient streak. |
|
|
94
95
|
|
|
95
96
|
Everything is idempotent: the same event twice leaves the same state. Lifting a suppression stays a manual act (`POST /v1/unsuppress`).
|
|
96
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
|
+
|
|
97
104
|
### Feeding events in
|
|
98
105
|
|
|
99
106
|
The provider layer (SNS verification, Resend webhooks, a fake provider in tests) must verify authenticity and de-duplicate, then call
|
|
@@ -102,15 +109,15 @@ The provider layer (SNS verification, Resend webhooks, a fake provider in tests)
|
|
|
102
109
|
```ts
|
|
103
110
|
await applyFeedback(db, { type: 'bounce', kind: 'permanent', email, source: 'ses', detail: 'NoEmail' });
|
|
104
111
|
await applyFeedback(db, { type: 'bounce', kind: 'transient', email, campaign: 'weekly-7', cause: 'mailbox', source: 'ses' });
|
|
105
|
-
await applyFeedback(db, { type: 'complaint', email, source: 'ses' });
|
|
112
|
+
await applyFeedback(db, { type: 'complaint', email, source: 'ses', scope: 'marketing' }); // about a newsletter
|
|
106
113
|
await applyFeedback(db, { type: 'delivery', email });
|
|
107
114
|
```
|
|
108
115
|
|
|
109
116
|
Mapping for SES transient bounces: `General` and `MailboxFull` → `cause: 'mailbox'`; `ContentRejected`, `AttachmentRejected` and `MessageTooLarge` → `cause: 'content'`.
|
|
110
117
|
|
|
111
|
-
The existing Resend webhook (`webhook.ts`) and Cloudflare event consumer (`cf-events.ts`)
|
|
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).
|
|
112
119
|
|
|
113
|
-
It returns `hard_bounce`, `complaint`, `transient_counted`, `transient_promoted`, `transient_no_campaign`, `transient_not_counted`, `delivery` or `rejected` (bad address or unknown type).
|
|
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).
|
|
114
121
|
|
|
115
122
|
## Migration
|
|
116
123
|
|
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,5 @@
|
|
|
1
|
+
-- Click / open tracking. Additive only: existing rows and code paths are unchanged.
|
|
2
|
+
|
|
3
|
+
-- Each issue's link table: JSON [{ "index": 1, "url": "https://…" }, …] (compose()'s links, final URLs).
|
|
4
|
+
-- The click redirect only goes to a URL in this table. NULL = the issue has no tracked links (older issues).
|
|
5
|
+
ALTER TABLE campaigns ADD COLUMN links TEXT;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
-- Welcome mail for new subscribers. Additive only.
|
|
2
|
+
|
|
3
|
+
-- One welcome mail per list. Composed outside the Worker (like an issue) and stored once. The engine adds the
|
|
4
|
+
-- List-Unsubscribe headers itself when sending.
|
|
5
|
+
-- enabled = 0 until someone switches it on explicitly; a list without a row (or with enabled = 0) sends no welcome mail.
|
|
6
|
+
CREATE TABLE welcome_mails (
|
|
7
|
+
list_id TEXT PRIMARY KEY REFERENCES lists (id),
|
|
8
|
+
subject TEXT NOT NULL,
|
|
9
|
+
from_addr TEXT NOT NULL,
|
|
10
|
+
reply_to TEXT,
|
|
11
|
+
html TEXT NOT NULL,
|
|
12
|
+
text TEXT NOT NULL,
|
|
13
|
+
web_url TEXT NOT NULL, -- the {{web_url}} placeholder (e.g. the newsletter's archive page)
|
|
14
|
+
content_hash TEXT NOT NULL,
|
|
15
|
+
enabled INTEGER NOT NULL DEFAULT 0,
|
|
16
|
+
updated_at TEXT NOT NULL
|
|
17
|
+
);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@joelincc/mailroom",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.1",
|
|
4
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
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
"./unsub": "./src/unsub.ts",
|
|
18
18
|
"./feedback": "./src/feedback.ts",
|
|
19
19
|
"./broadcast": "./src/broadcast/index.ts",
|
|
20
|
+
"./track": "./src/track.ts",
|
|
20
21
|
"./cli": {
|
|
21
22
|
"types": "./src/cli/main.ts",
|
|
22
23
|
"default": "./dist/cli/main.js"
|
|
@@ -57,6 +58,7 @@
|
|
|
57
58
|
},
|
|
58
59
|
"devDependencies": {
|
|
59
60
|
"@cloudflare/workers-types": "^5.20261019.1",
|
|
61
|
+
"satteri": "0.10.5",
|
|
60
62
|
"typescript": "^5.6.3",
|
|
61
63
|
"wrangler": "4.162.0"
|
|
62
64
|
},
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
// 內容(讀者看得到的一切)算一個雜湊:核准與寄前檢查都綁在那個雜湊上,內容一改就退回 draft、要重新核准。
|
|
9
9
|
|
|
10
10
|
import { parseAddress, type Db } from '../core.ts';
|
|
11
|
+
import { checkLinks, type StoredLink } from '../track.ts';
|
|
11
12
|
|
|
12
13
|
export type CampaignStatus = 'draft' | 'approved' | 'scheduled' | 'sending' | 'paused' | 'done' | 'cancelled';
|
|
13
14
|
export const CAMPAIGN_STATUSES: readonly CampaignStatus[] = ['draft', 'approved', 'scheduled', 'sending', 'paused', 'done', 'cancelled'];
|
|
@@ -43,6 +44,8 @@ export interface CampaignInput {
|
|
|
43
44
|
webUrl?: string;
|
|
44
45
|
sourceRef?: string;
|
|
45
46
|
audience: Audience;
|
|
47
|
+
/** compose() 的連結表(序號+最終網址)。內容用到追蹤佔位 {{c:N}} 時必填;點擊轉址只會轉到這裡列的網址。 */
|
|
48
|
+
links?: StoredLink[];
|
|
46
49
|
}
|
|
47
50
|
|
|
48
51
|
export interface CampaignRow {
|
|
@@ -52,6 +55,7 @@ export interface CampaignRow {
|
|
|
52
55
|
approved_at: string | null; approved_note: string | null; preflight: string | null; scheduled_at: string | null;
|
|
53
56
|
started_at: string | null; frozen_at: string | null; last_release_at: string | null; waiting_since: string | null; last_progress_at: string | null;
|
|
54
57
|
finished_at: string | null; pause_reason: string | null; counts: string | null; created_at: string; updated_at: string;
|
|
58
|
+
links?: string | null;
|
|
55
59
|
}
|
|
56
60
|
|
|
57
61
|
export type Fail = { ok: false; reason: string; status?: CampaignStatus; twin?: string; twinStatus?: CampaignStatus; twinBy?: 'web_url' | 'content' | 'source_ref' };
|
|
@@ -67,8 +71,11 @@ const nowIso = (now?: () => Date) => (now ?? (() => new Date()))().toISOString()
|
|
|
67
71
|
const ctl = (s: string) => /[\u0000-\u001f\u007f]/.test(s);
|
|
68
72
|
|
|
69
73
|
/** 讀者看得到的一切(含名單與寄件人)算一個雜湊。 */
|
|
70
|
-
export async function contentHash(c: { list: string; subject: string; preheader?: string | null; from: string; replyTo?: string | null; html: string; text: string; headers?: Record<string, string> | null; webUrl?: string | null }): Promise<string> {
|
|
71
|
-
const
|
|
74
|
+
export async function contentHash(c: { list: string; subject: string; preheader?: string | null; from: string; replyTo?: string | null; html: string; text: string; headers?: Record<string, string> | null; webUrl?: string | null; links?: StoredLink[] | null }): Promise<string> {
|
|
75
|
+
const parts: unknown[] = [c.list, c.subject, c.preheader ?? '', c.from, c.replyTo ?? '', c.html, c.text, Object.entries(c.headers ?? {}).sort(), c.webUrl ?? ''];
|
|
76
|
+
// 連結表也算讀者看得到的內容(點了會去哪裡)。沒有連結表時雜湊跟舊版一樣,已存的期不會因升版而失效。
|
|
77
|
+
if (c.links && c.links.length) parts.push(c.links.map((l) => [l.index, l.url]));
|
|
78
|
+
const raw = JSON.stringify(parts);
|
|
72
79
|
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw));
|
|
73
80
|
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
74
81
|
}
|
|
@@ -153,6 +160,10 @@ function checkInput(input: CampaignInput, marketingDomain: string): string | nul
|
|
|
153
160
|
if (input.webUrl !== undefined && (typeof input.webUrl !== 'string' || input.webUrl.length > 2000 || !/^https:\/\/[^\s<>"]+$/i.test(input.webUrl))) return 'bad_web_url';
|
|
154
161
|
if (input.sourceRef !== undefined && (typeof input.sourceRef !== 'string' || input.sourceRef.length > LIMITS.sourceRef || ctl(input.sourceRef))) return 'bad_source_ref';
|
|
155
162
|
if (!checkAudience(input.audience)) return 'bad_audience';
|
|
163
|
+
if (input.links !== undefined && !checkLinks(input.links)) return 'bad_links';
|
|
164
|
+
// 內容用到的每個 {{c:N}} 都要在連結表裡,不然寄出去的連結點了會 404。
|
|
165
|
+
const n = input.links?.length ?? 0;
|
|
166
|
+
for (const s of [input.html, input.text]) for (const m of s.matchAll(/\{\{\s*c:(\d+)\s*\}\}/g)) if (Number(m[1]) < 1 || Number(m[1]) > n) return 'links_missing';
|
|
156
167
|
return null;
|
|
157
168
|
}
|
|
158
169
|
|
|
@@ -169,9 +180,11 @@ export async function saveDraft(db: Db, input: CampaignInput, opts: { marketingD
|
|
|
169
180
|
const bad = checkInput(input, opts.marketingDomain);
|
|
170
181
|
if (bad) return { ok: false, reason: bad };
|
|
171
182
|
if (!(await db.prepare('SELECT id FROM lists WHERE id = ?').bind(input.list).first())) return { ok: false, reason: 'unknown_list' };
|
|
172
|
-
const hash = await contentHash(input);
|
|
183
|
+
const hash = await contentHash({ ...input, links: input.links && input.links.length ? checkLinks(input.links) : undefined });
|
|
173
184
|
const audience = JSON.stringify(checkAudience(input.audience));
|
|
174
185
|
const headers = input.headers ? JSON.stringify(input.headers) : null;
|
|
186
|
+
const normalized = input.links && input.links.length ? checkLinks(input.links) : null;
|
|
187
|
+
const links = normalized && normalized.length ? JSON.stringify(normalized) : null;
|
|
175
188
|
const t = nowIso(opts.now);
|
|
176
189
|
const existing = await getCampaign(db, input.id);
|
|
177
190
|
// 同一份內容不能用不同期號建兩次(會寄兩封):網頁版網址(正規化後)、同名單同內文、原稿位置任一相同,且對方沒被取消,就擋。
|
|
@@ -181,10 +194,10 @@ export async function saveDraft(db: Db, input: CampaignInput, opts: { marketingD
|
|
|
181
194
|
if (!existing) {
|
|
182
195
|
const r = await db
|
|
183
196
|
.prepare(
|
|
184
|
-
`INSERT INTO campaigns (id, list_id, subject, preheader, from_addr, reply_to, html, text, headers, web_url, source_ref, status, audience, content_hash, created_at, updated_at)
|
|
185
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'draft', ?, ?, ?, ?) ON CONFLICT (id) DO NOTHING`,
|
|
197
|
+
`INSERT INTO campaigns (id, list_id, subject, preheader, from_addr, reply_to, html, text, headers, web_url, source_ref, status, audience, content_hash, links, created_at, updated_at)
|
|
198
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'draft', ?, ?, ?, ?, ?) ON CONFLICT (id) DO NOTHING`,
|
|
186
199
|
)
|
|
187
|
-
.bind(input.id, input.list, input.subject, input.preheader ?? null, input.from, input.replyTo ?? null, input.html, input.text, headers, input.webUrl ?? null, input.sourceRef ?? null, audience, hash, t, t)
|
|
200
|
+
.bind(input.id, input.list, input.subject, input.preheader ?? null, input.from, input.replyTo ?? null, input.html, input.text, headers, input.webUrl ?? null, input.sourceRef ?? null, audience, hash, links, t, t)
|
|
188
201
|
.run();
|
|
189
202
|
if ((r.meta.changes ?? 0) === 1) return { ok: true, status: 'draft', changed: true };
|
|
190
203
|
return { ok: false, reason: 'conflict' };
|
|
@@ -196,10 +209,10 @@ export async function saveDraft(db: Db, input: CampaignInput, opts: { marketingD
|
|
|
196
209
|
const r = await db
|
|
197
210
|
.prepare(
|
|
198
211
|
`UPDATE campaigns SET list_id = ?, subject = ?, preheader = ?, from_addr = ?, reply_to = ?, html = ?, text = ?, headers = ?, web_url = ?, source_ref = ?, audience = ?,
|
|
199
|
-
content_hash = ?, status = 'draft', approved_hash = NULL, approved_at = NULL, approved_note = NULL, preflight = NULL, scheduled_at = NULL, updated_at = ?
|
|
212
|
+
content_hash = ?, links = ?, status = 'draft', approved_hash = NULL, approved_at = NULL, approved_note = NULL, preflight = NULL, scheduled_at = NULL, updated_at = ?
|
|
200
213
|
WHERE id = ? AND status IN ('draft', 'approved', 'scheduled')`,
|
|
201
214
|
)
|
|
202
|
-
.bind(input.list, input.subject, input.preheader ?? null, input.from, input.replyTo ?? null, input.html, input.text, headers, input.webUrl ?? null, input.sourceRef ?? null, audience, hash, t, input.id)
|
|
215
|
+
.bind(input.list, input.subject, input.preheader ?? null, input.from, input.replyTo ?? null, input.html, input.text, headers, input.webUrl ?? null, input.sourceRef ?? null, audience, hash, links, t, input.id)
|
|
203
216
|
.run();
|
|
204
217
|
if ((r.meta.changes ?? 0) !== 1) return { ok: false, reason: 'locked' };
|
|
205
218
|
return { ok: true, status: 'draft', changed: true };
|
|
@@ -17,6 +17,7 @@ import type { Postman, PostmanMail, ProviderEvent } from './postman.ts';
|
|
|
17
17
|
import { reconcileCampaign } from './reconcile.ts';
|
|
18
18
|
import { campaignRates, domainRates } from './stats.ts';
|
|
19
19
|
import { currentStep, planBlocked } from './warmup.ts';
|
|
20
|
+
import { consumeWelcome, type WelcomeMessage } from '../welcome.ts';
|
|
20
21
|
|
|
21
22
|
export interface RecipientRow {
|
|
22
23
|
campaign_id: string; contact_id: number; email: string; segment: string | null; wave: number | null; rank: number;
|
|
@@ -28,7 +29,7 @@ export interface RenderResult { html: string; text: string; headers?: Record<str
|
|
|
28
29
|
/** 產生這一位收件人的信(個人化、退訂連結、追蹤簽章)。丟例外=這期暫停(不能寄出沒有退訂連結的信)。 */
|
|
29
30
|
export type Render = (campaign: CampaignRow, recipient: RecipientRow & { name: string | null }) => RenderResult | Promise<RenderResult>;
|
|
30
31
|
|
|
31
|
-
export type BroadcastMessage = { kind: 'send'; campaign: string; contact: number } | { kind: 'event'; event: ProviderEvent };
|
|
32
|
+
export type BroadcastMessage = { kind: 'send'; campaign: string; contact: number } | { kind: 'event'; event: ProviderEvent } | WelcomeMessage;
|
|
32
33
|
export interface BroadcastQueue { sendBatch(messages: { body: BroadcastMessage; delaySeconds?: number }[]): Promise<unknown> }
|
|
33
34
|
|
|
34
35
|
export interface Alert { level: 'red' | 'yellow' | 'info'; code: string; campaign?: string; message: string }
|
|
@@ -44,6 +45,8 @@ export interface BroadcastDeps {
|
|
|
44
45
|
/** 煞車、暫停、寄完等通知交給誰(告警出口由部署端決定,引擎不自己發)。 */
|
|
45
46
|
alert?: (a: Alert) => void | Promise<void>;
|
|
46
47
|
feedback?: IngestOptions['feedback'];
|
|
48
|
+
/** 歡迎信的退訂連結設定(與退訂模組同一組鑰匙)。沒給=歡迎信一律不寄(沒有退訂連結的信不出去)。 */
|
|
49
|
+
unsub?: { secrets: readonly string[]; baseUrl?: string; mailto?: string };
|
|
47
50
|
now?: () => Date;
|
|
48
51
|
sleep?: (ms: number) => Promise<void>;
|
|
49
52
|
}
|
|
@@ -596,6 +599,15 @@ export async function consume(deps: BroadcastDeps, body: unknown): Promise<Consu
|
|
|
596
599
|
const outcome = await ingestEvent(db, msg.event, { feedback: deps.feedback, now: deps.now });
|
|
597
600
|
return ack(`event:${outcome}`);
|
|
598
601
|
}
|
|
602
|
+
if (msg && typeof msg === 'object' && msg.kind === 'welcome') {
|
|
603
|
+
const w = await consumeWelcome({ db, postman: deps.postman, domain: deps.domain.toLowerCase(), site: cfg.site, utcOffsetHours: cfg.utcOffsetHours, unsub: deps.unsub ?? { secrets: [] }, now: deps.now }, msg);
|
|
604
|
+
// 等候(網域停寄、額度用完…)改成重新排一則新訊息,不吃 Queue 的重試次數:不然幾次之後就掉進死信佇列,撐不到 48 小時的期限。
|
|
605
|
+
if (w.action === 'retry' && deps.queue) {
|
|
606
|
+
await deps.queue.sendBatch([{ body: msg, delaySeconds: w.delaySeconds }]);
|
|
607
|
+
return ack(`${w.outcome}:requeued`);
|
|
608
|
+
}
|
|
609
|
+
return w;
|
|
610
|
+
}
|
|
599
611
|
if (!msg || typeof msg !== 'object' || msg.kind !== 'send' || typeof msg.campaign !== 'string' || !Number.isInteger(msg.contact)) return ack('bad_message');
|
|
600
612
|
|
|
601
613
|
const r = await db.prepare('SELECT * FROM campaign_recipients WHERE campaign_id = ? AND contact_id = ?').bind(msg.campaign, msg.contact).first<RecipientRow>();
|
|
@@ -745,7 +757,8 @@ export async function consumeBatch(deps: BroadcastDeps, messages: readonly Queue
|
|
|
745
757
|
const results: ConsumeResult[] = [];
|
|
746
758
|
let lastSend = 0;
|
|
747
759
|
for (const m of messages) {
|
|
748
|
-
const
|
|
760
|
+
const kind = (m.body as BroadcastMessage | null)?.kind;
|
|
761
|
+
const isSend = kind === 'send' || kind === 'welcome';
|
|
749
762
|
if (isSend && lastSend) {
|
|
750
763
|
const wait = gap - (Date.now() - lastSend);
|
|
751
764
|
if (wait > 0) await sleep(wait);
|
|
@@ -753,7 +766,7 @@ export async function consumeBatch(deps: BroadcastDeps, messages: readonly Queue
|
|
|
753
766
|
try {
|
|
754
767
|
const r = await consume(deps, m.body);
|
|
755
768
|
results.push(r);
|
|
756
|
-
if (isSend && /^(sent|duplicate|uncertain|failed_|throttled|temporary)/.test(r.outcome)) lastSend = Date.now();
|
|
769
|
+
if (isSend && /^(sent|duplicate|uncertain|failed_|throttled|temporary|welcome_(sent|uncertain|failed|temporary|throttled))/.test(r.outcome)) lastSend = Date.now();
|
|
757
770
|
if (r.action === 'ack') m.ack();
|
|
758
771
|
else m.retry({ delaySeconds: r.delaySeconds });
|
|
759
772
|
} catch (e) {
|