@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.
Files changed (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +207 -2
  3. package/SECURITY.md +11 -0
  4. package/bin/mailroom.mjs +26 -0
  5. package/dist/broadcast/config.js +79 -0
  6. package/dist/broadcast/explain.js +50 -0
  7. package/dist/cli/args.js +29 -0
  8. package/dist/cli/errors.js +31 -0
  9. package/dist/cli/main.js +475 -0
  10. package/dist/compose/clicks.js +29 -0
  11. package/dist/compose/compose.js +224 -0
  12. package/dist/compose/index.js +8 -0
  13. package/dist/compose/markdown.js +637 -0
  14. package/dist/compose/personalize.js +123 -0
  15. package/dist/compose/preflight.js +251 -0
  16. package/dist/compose/preview.js +41 -0
  17. package/dist/compose/render.js +136 -0
  18. package/dist/compose/template.js +118 -0
  19. package/docs/broadcast.md +199 -0
  20. package/docs/composing.md +135 -0
  21. package/docs/desk-commands.md +52 -0
  22. package/docs/export.md +51 -0
  23. package/docs/lists.md +66 -0
  24. package/docs/security-model.md +82 -0
  25. package/docs/ses.md +116 -0
  26. package/docs/unsubscribe.md +117 -0
  27. package/migrations/0001_init.sql +42 -0
  28. package/migrations/0002_tier.sql +4 -0
  29. package/migrations/0003_rate.sql +9 -0
  30. package/migrations/0004_last_error.sql +2 -0
  31. package/migrations/0005_lists.sql +41 -0
  32. package/migrations/0006_broadcast.sql +154 -0
  33. package/migrations/0007_unsubscribe.sql +12 -0
  34. package/package.json +64 -4
  35. package/src/alert.ts +123 -0
  36. package/src/aws-sigv4.ts +100 -0
  37. package/src/broadcast/audience.ts +96 -0
  38. package/src/broadcast/campaigns.ts +339 -0
  39. package/src/broadcast/config.ts +136 -0
  40. package/src/broadcast/dispatch.ts +766 -0
  41. package/src/broadcast/events.ts +107 -0
  42. package/src/broadcast/explain.ts +73 -0
  43. package/src/broadcast/freeze.ts +93 -0
  44. package/src/broadcast/index.ts +21 -0
  45. package/src/broadcast/postman.ts +229 -0
  46. package/src/broadcast/reconcile.ts +120 -0
  47. package/src/broadcast/routes.ts +181 -0
  48. package/src/broadcast/ses.ts +181 -0
  49. package/src/broadcast/stats.ts +59 -0
  50. package/src/broadcast/status.ts +60 -0
  51. package/src/broadcast/test-send.ts +88 -0
  52. package/src/broadcast/warmup.ts +150 -0
  53. package/src/broadcast/worker.ts +177 -0
  54. package/src/cf-events.ts +84 -0
  55. package/src/cli/args.ts +27 -0
  56. package/src/cli/errors.ts +33 -0
  57. package/src/cli/main.ts +466 -0
  58. package/src/compose/clicks.ts +45 -0
  59. package/src/compose/compose.ts +257 -0
  60. package/src/compose/index.ts +8 -0
  61. package/src/compose/markdown.ts +624 -0
  62. package/src/compose/personalize.ts +130 -0
  63. package/src/compose/preflight.ts +250 -0
  64. package/src/compose/preview.ts +58 -0
  65. package/src/compose/render.ts +153 -0
  66. package/src/compose/template.ts +197 -0
  67. package/src/core.ts +328 -0
  68. package/src/export.ts +184 -0
  69. package/src/feedback.ts +111 -0
  70. package/src/http.ts +17 -0
  71. package/src/index.ts +378 -0
  72. package/src/list-routes.ts +42 -0
  73. package/src/lists.ts +370 -0
  74. package/src/ses-events.ts +426 -0
  75. package/src/transport.ts +193 -0
  76. package/src/unsub-wiring.ts +64 -0
  77. package/src/unsub.ts +499 -0
  78. package/src/webhook.ts +101 -0
  79. package/wrangler.example.jsonc +56 -0
package/src/export.ts ADDED
@@ -0,0 +1,184 @@
1
+ // 分析匯出:把事件、期別、凍結名單、名單成員用 NDJSON 一頁一頁交給外面的分析管線(帶管理口令)。見 docs/export.md。
2
+ //
3
+ // GET /v1/export/events?cursor=&limit= 事件(依 id 遞增;cursor=上一頁回的 x-export-next-cursor)
4
+ // POST /v1/export/events/ack { through } 分析端「已經安全存好」到哪個事件 id:標 exported_at(可重複執行)
5
+ // GET /v1/export/campaigns?cursor=&limit= 每期一列(寄送時間、狀態)
6
+ // GET /v1/export/recipients?campaign=&cursor=&limit= 某一期的凍結名單(寄的當下每人的分群;不含信箱)
7
+ // GET /v1/export/members?list=&cursor=&limit= 某份名單目前所有成員(含信箱,每週快照用)
8
+ //
9
+ // 設計重點:
10
+ // - 讀取本身不改任何東西:同一個 cursor 重拉一定拿到同一批(除了新進來的)。中途失敗的人只要從上次存好的 cursor 再來,不會漏也不會重。
11
+ // - 「分析端存好了」才呼叫 ack;ack 只是標記(exported_at),不影響下一次從哪裡拉,拉到哪由分析端自己記 cursor。
12
+ // - 事件只帶 contact_id,不帶信箱(記事件時與匯出時都會把 detail 裡信箱形狀的字串遮掉);要對到信箱用 members 快照。
13
+ // - D1 的寫入是一筆一筆依序提交,AUTOINCREMENT 的 id 看得到 N+1 就代表 N 已提交,依 id 往後拉不會跳過。
14
+ // - 自己一組速度上限(_export),不跟其他管理入口搶額度。
15
+
16
+ import { takeRate, type Db } from './core.ts';
17
+ import { bearer, json, notFound, sameToken } from './http.ts';
18
+
19
+ export const EXPORT_LIMITS = { perMinute: 60, perDay: 1000 };
20
+ export const EXPORT_DEFAULT_PAGE = 2000;
21
+ export const EXPORT_MAX_PAGE = 5000;
22
+
23
+ const PATH = /^\/v1\/export\/(events|campaigns|recipients|members)$/;
24
+ const ACK_PATH = '/v1/export/events/ack';
25
+ const LIST_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
26
+ const CAMPAIGN_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
27
+
28
+ const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+/g;
29
+ /** 事件的 detail 不該帶信箱:遞迴走訪,只在每個字串值上把信箱形狀的字串遮成 [email](@頻道 這類不是信箱,原樣保留)。
30
+ * 不碰 JSON 原文,所以字串裡的跳脫字元(\t、\n、控制字元)後面接信箱也安全;任何情況都不丟例外——
31
+ * 萬一出事,整個 detail 換成固定標記,事件照樣寫入/匯出。已知限制:像 pkg@1.2.3 的版本號會被誤遮、%40 編碼的信箱不會被遮。 */
32
+ export function scrubEmails(value: unknown, depth = 0): unknown {
33
+ try {
34
+ if (typeof value === 'string') return value.includes('@') ? value.replace(EMAIL, '[email]') : value;
35
+ if (value === null || typeof value !== 'object') return value;
36
+ if (depth > 20) return '[scrub-depth-limit]';
37
+ if (Array.isArray(value)) return value.map((v) => scrubEmails(v, depth + 1));
38
+ const out: Record<string, unknown> = {};
39
+ for (const [k, v] of Object.entries(value)) out[k.includes('@') ? k.replace(EMAIL, '[email]') : k] = scrubEmails(v, depth + 1);
40
+ return out;
41
+ } catch {
42
+ return { scrub_failed: true };
43
+ }
44
+ }
45
+
46
+ const ndjson = (rows: unknown[], next: string | null): Response =>
47
+ new Response(rows.map((r) => JSON.stringify(r)).join('\n') + (rows.length ? '\n' : ''), {
48
+ headers: {
49
+ 'content-type': 'application/x-ndjson; charset=utf-8',
50
+ 'cache-control': 'no-store',
51
+ 'x-export-count': String(rows.length),
52
+ 'x-export-has-more': next === null ? '0' : '1',
53
+ 'x-export-next-cursor': next ?? '',
54
+ },
55
+ });
56
+
57
+ function parseJson(text: string | null | undefined): unknown {
58
+ if (!text) return null;
59
+ try {
60
+ return JSON.parse(text);
61
+ } catch {
62
+ return { _unparsed: String(text).slice(0, 500) };
63
+ }
64
+ }
65
+
66
+ function pageLimit(raw: string | null): number {
67
+ const n = Math.trunc(Number(raw));
68
+ return Math.min(Math.max(Number.isFinite(n) && n > 0 ? n : EXPORT_DEFAULT_PAGE, 1), EXPORT_MAX_PAGE);
69
+ }
70
+
71
+ /** cursor 只收十進位整數;沒給=從頭(0)。 */
72
+ function parseCursor(raw: string | null): number | null {
73
+ if (raw === null || raw === '') return 0;
74
+ return /^\d{1,15}$/.test(raw) ? Number(raw) : null;
75
+ }
76
+
77
+ export async function exportEvents(db: Db, cursor: number, limit: number): Promise<{ rows: unknown[]; next: string | null }> {
78
+ const r = await db
79
+ .prepare(
80
+ `SELECT id, provider, provider_event_id, message_id, provider_message_id, campaign_id, contact_id, type, subtype, at, detail, exported_at
81
+ FROM events WHERE id > ? ORDER BY id LIMIT ?`,
82
+ )
83
+ .bind(cursor, limit + 1)
84
+ .all<Record<string, unknown> & { id: number; detail: string | null }>();
85
+ const more = r.results.length > limit;
86
+ const page = r.results.slice(0, limit);
87
+ return { rows: page.map((e) => ({ ...e, detail: scrubEmails(parseJson(e.detail)) })), next: more ? String(page[page.length - 1].id) : null };
88
+ }
89
+
90
+ /** 標記 id ≤ through 的事件已匯出。through 不能超過目前最大 id(防呼叫端算錯把還沒拉的也標掉)。 */
91
+ export async function ackEvents(db: Db, through: unknown, now: Date): Promise<{ ok: true; marked: number } | { ok: false; reason: 'bad_through' | 'beyond_max' }> {
92
+ if (typeof through !== 'number' || !Number.isInteger(through) || through < 0) return { ok: false, reason: 'bad_through' };
93
+ const max = await db.prepare('SELECT COALESCE(MAX(id), 0) AS m FROM events').first<{ m: number }>();
94
+ if (through > Number(max?.m ?? 0)) return { ok: false, reason: 'beyond_max' };
95
+ const r = await db.prepare('UPDATE events SET exported_at = ? WHERE id <= ? AND exported_at IS NULL').bind(now.toISOString(), through).run();
96
+ return { ok: true, marked: Number(r.meta.changes ?? 0) };
97
+ }
98
+
99
+ export async function exportCampaigns(db: Db, cursor: number, limit: number): Promise<{ rows: unknown[]; next: string | null }> {
100
+ const r = await db
101
+ .prepare(
102
+ `SELECT rowid AS seq, id, list_id, subject, from_addr, status, scheduled_at, started_at, finished_at, frozen_at, pause_reason, created_at, updated_at
103
+ FROM campaigns WHERE rowid > ? ORDER BY rowid LIMIT ?`,
104
+ )
105
+ .bind(cursor, limit + 1)
106
+ .all<Record<string, unknown> & { seq: number }>();
107
+ const more = r.results.length > limit;
108
+ const page = r.results.slice(0, limit);
109
+ return { rows: page, next: more ? String(page[page.length - 1].seq) : null };
110
+ }
111
+
112
+ export async function exportRecipients(db: Db, campaign: string, cursor: number, limit: number): Promise<{ rows: unknown[]; next: string | null }> {
113
+ const r = await db
114
+ .prepare(
115
+ `SELECT campaign_id, contact_id, segment, wave, state, skip_reason, enqueued_at, done_at
116
+ FROM campaign_recipients WHERE campaign_id = ? AND contact_id > ? ORDER BY contact_id LIMIT ?`,
117
+ )
118
+ .bind(campaign, cursor, limit + 1)
119
+ .all<Record<string, unknown> & { contact_id: number }>();
120
+ const more = r.results.length > limit;
121
+ const page = r.results.slice(0, limit);
122
+ return { rows: page, next: more ? String(page[page.length - 1].contact_id) : null };
123
+ }
124
+
125
+ export async function exportMembers(db: Db, list: string, cursor: number, limit: number): Promise<{ rows: unknown[]; next: string | null }> {
126
+ const r = await db
127
+ .prepare(
128
+ `SELECT m.list_id, m.contact_id, c.email AS email, m.status, m.subscribed_at, m.unsubscribed_at, m.unsub_source, m.source,
129
+ m.segment, m.segment_label, m.segment_at, m.imported_from, m.last_open_at, m.last_click_at, m.updated_at
130
+ FROM list_members m JOIN contacts c ON c.id = m.contact_id
131
+ WHERE m.list_id = ? AND m.contact_id > ? ORDER BY m.contact_id LIMIT ?`,
132
+ )
133
+ .bind(list, cursor, limit + 1)
134
+ .all<Record<string, unknown> & { contact_id: number }>();
135
+ const more = r.results.length > limit;
136
+ const page = r.results.slice(0, limit);
137
+ return { rows: page, next: more ? String(page[page.length - 1].contact_id) : null };
138
+ }
139
+
140
+ /** 路徑不是匯出入口=回 null(交給後面的路由);口令不對一律 404(不透露入口存在)。 */
141
+ export async function routeExport(request: Request, db: Db, adminToken: string | undefined, now: () => Date = () => new Date()): Promise<Response | null> {
142
+ const url = new URL(request.url);
143
+ const m = PATH.exec(url.pathname);
144
+ const isAck = url.pathname === ACK_PATH;
145
+ if (!m && !isAck) return null;
146
+ const wanted = isAck ? 'POST' : 'GET';
147
+ if (request.method !== wanted) return notFound();
148
+ if (!sameToken(bearer(request), adminToken ?? '')) return notFound();
149
+ const over = await takeRate(db, '_export', EXPORT_LIMITS, now());
150
+ if (over) return new Response('rate limited', { status: 429, headers: { 'retry-after': over === 'day' ? '3600' : '60' } });
151
+
152
+ if (isAck) {
153
+ const body = (await request.json().catch(() => null)) as { through?: unknown } | null;
154
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return json({ ok: false, reason: 'bad_json' }, 400);
155
+ const r = await ackEvents(db, body.through, now());
156
+ return json(r, r.ok ? 200 : 400);
157
+ }
158
+
159
+ const cursor = parseCursor(url.searchParams.get('cursor'));
160
+ if (cursor === null) return json({ ok: false, reason: 'bad_cursor' }, 400);
161
+ const limit = pageLimit(url.searchParams.get('limit'));
162
+ switch (m![1]) {
163
+ case 'events': {
164
+ const r = await exportEvents(db, cursor, limit);
165
+ return ndjson(r.rows, r.next);
166
+ }
167
+ case 'campaigns': {
168
+ const r = await exportCampaigns(db, cursor, limit);
169
+ return ndjson(r.rows, r.next);
170
+ }
171
+ case 'recipients': {
172
+ const campaign = url.searchParams.get('campaign') ?? '';
173
+ if (!CAMPAIGN_ID.test(campaign)) return json({ ok: false, reason: 'bad_campaign' }, 400);
174
+ const r = await exportRecipients(db, campaign, cursor, limit);
175
+ return ndjson(r.rows, r.next);
176
+ }
177
+ default: {
178
+ const list = url.searchParams.get('list') ?? '';
179
+ if (!LIST_ID.test(list)) return json({ ok: false, reason: 'bad_list' }, 400);
180
+ const r = await exportMembers(db, list, cursor, limit);
181
+ return ndjson(r.rows, r.next);
182
+ }
183
+ }
184
+ }
@@ -0,0 +1,111 @@
1
+ // 退信與檢舉怎麼進拒收:吃「已經正規化的事件」。事件從哪家郵差來、簽章怎麼驗,不在這裡(由接郵差的那一層做完再呼叫)。
2
+ // 不 import cloudflare:*,測試用 Node 內建 SQLite 跑同一份 SQL。
3
+ //
4
+ // 規則:
5
+ // - 永久退信 → 全域拒收 hard_bounce(所有信都不寄,包含登入類通知信)。
6
+ // - 檢舉 → 全域拒收 complaint(同上),並把這個人在所有名單標 unsubscribed(unsub_source='complaint')。
7
+ // - 暫時性退信 → 不擋;信箱層級(cause=mailbox)的,同一人連續 3 期(三個不同的期別、中間沒有送達)→ 當硬退信處理;內容被拒這類不累計。
8
+ // - 送達 → 清掉這個人的暫時退信紀錄(連續中斷)。
9
+ // 全部可重複執行:同一則事件送兩次,結果一樣。
10
+
11
+ import { addSuppression, type Db } from './core.ts';
12
+ import { normalizeEmail } from './lists.ts';
13
+
14
+ export type FeedbackEvent =
15
+ | { type: 'bounce'; kind: 'permanent'; email: string; source: string; detail?: string | null }
16
+ | {
17
+ type: 'bounce';
18
+ kind: 'transient';
19
+ email: string;
20
+ /** 這封信屬於哪一期;沒有期別就不計入連續。 */
21
+ campaign?: string | null;
22
+ /**
23
+ * 為什麼暫時退信。只有 'mailbox'(信箱層級:信箱滿了、收信伺服器暫時掛了、對方限速)才累計;
24
+ * 'content'(內容被拒、附件被拒、信太大)跟信箱無關,不累計,免得把正常讀者誤判成硬退信。沒給=不累計。
25
+ * SES 對照(ses-events.ts):Transient 的 MailboxFull → mailbox;ContentRejected、AttachmentRejected、MessageTooLarge → content;
26
+ * Transient 的 General、CustomTimeoutExceeded 與 Undetermined 都不帶(原因不明,寧可不累計也不要誤判成硬退信)。
27
+ */
28
+ cause?: TransientCause;
29
+ source: string;
30
+ detail?: string | null;
31
+ }
32
+ | { type: 'complaint'; email: string; source: string; detail?: string | null }
33
+ | { type: 'delivery'; email: string };
34
+
35
+ export type TransientCause = 'mailbox' | 'content';
36
+
37
+ export type FeedbackOutcome =
38
+ | 'hard_bounce'
39
+ | 'complaint'
40
+ | 'transient_counted'
41
+ | 'transient_promoted'
42
+ | 'transient_no_campaign'
43
+ | 'transient_not_counted'
44
+ | 'delivery'
45
+ | 'rejected';
46
+
47
+ /** 連續幾期暫時性退信就當硬退信。 */
48
+ export const TRANSIENT_LIMIT = 3;
49
+
50
+ export interface FeedbackOptions {
51
+ now?: () => Date;
52
+ /** 連續幾期暫時性退信算硬退信(預設 3)。 */
53
+ transientLimit?: number;
54
+ }
55
+
56
+ const CAMPAIGN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/;
57
+
58
+ export async function applyFeedback(db: Db, ev: FeedbackEvent, opts: FeedbackOptions = {}): Promise<FeedbackOutcome> {
59
+ const email = normalizeEmail((ev as { email?: unknown })?.email);
60
+ if (!email) return 'rejected';
61
+ const now = (opts.now ?? (() => new Date()))();
62
+ const t = now.toISOString();
63
+ const source = 'source' in ev && typeof ev.source === 'string' && ev.source.trim() ? ev.source.trim().slice(0, 40) : 'feedback';
64
+
65
+ if (ev.type === 'delivery') {
66
+ await db.prepare('DELETE FROM bounce_streaks WHERE email = ?').bind(email).run();
67
+ return 'delivery';
68
+ }
69
+
70
+ if (ev.type === 'complaint') {
71
+ await addSuppression(db, email, 'complaint', source, ev.detail ?? null, now);
72
+ // 這個人明白說了「不要」:所有名單一起退出。已經退訂的保留原本的時間與來源。
73
+ await db
74
+ .prepare(
75
+ `UPDATE list_members SET
76
+ unsubscribed_at = CASE WHEN status = 'unsubscribed' THEN unsubscribed_at ELSE ? END,
77
+ unsub_source = CASE WHEN status = 'unsubscribed' THEN unsub_source ELSE 'complaint' END,
78
+ updated_at = CASE WHEN status = 'unsubscribed' THEN updated_at ELSE ? END,
79
+ status = 'unsubscribed'
80
+ WHERE contact_id = (SELECT id FROM contacts WHERE email = ?)`,
81
+ )
82
+ .bind(t, t, email)
83
+ .run();
84
+ await db.prepare('DELETE FROM bounce_streaks WHERE email = ?').bind(email).run();
85
+ return 'complaint';
86
+ }
87
+
88
+ if (ev.type === 'bounce' && ev.kind === 'permanent') {
89
+ // 名單裡的狀態不動(不是讀者的決定);拒收名單擋住所有寄送,人工解除拒收後就恢復。
90
+ await addSuppression(db, email, 'hard_bounce', source, ev.detail ?? null, now);
91
+ await db.prepare('DELETE FROM bounce_streaks WHERE email = ?').bind(email).run();
92
+ return 'hard_bounce';
93
+ }
94
+
95
+ if (ev.type === 'bounce' && ev.kind === 'transient') {
96
+ if (ev.cause !== 'mailbox') return 'transient_not_counted';
97
+ if (typeof ev.campaign !== 'string' || !CAMPAIGN.test(ev.campaign)) return 'transient_no_campaign';
98
+ // 同一期同一人只算一次(重送的事件不會重複計數)。
99
+ await db.prepare('INSERT INTO bounce_streaks (email, campaign_id, at) VALUES (?, ?, ?) ON CONFLICT (email, campaign_id) DO NOTHING').bind(email, ev.campaign, t).run();
100
+ const n = await db.prepare('SELECT COUNT(*) AS n FROM bounce_streaks WHERE email = ?').bind(email).first<{ n: number }>();
101
+ const limit = Math.max(1, Math.trunc(opts.transientLimit ?? TRANSIENT_LIMIT));
102
+ if (Number(n?.n ?? 0) >= limit) {
103
+ await addSuppression(db, email, 'hard_bounce', source, `transient_streak:${limit}`, now);
104
+ await db.prepare('DELETE FROM bounce_streaks WHERE email = ?').bind(email).run();
105
+ return 'transient_promoted';
106
+ }
107
+ return 'transient_counted';
108
+ }
109
+
110
+ return 'rejected';
111
+ }
package/src/http.ts ADDED
@@ -0,0 +1,17 @@
1
+ // 小工具:比對口令、讀 Bearer。獨立成檔,路由模組與測試不必 import cloudflare:workers。
2
+
3
+ export function sameToken(a: string, b: string): boolean {
4
+ if (!a || !b || a.length !== b.length) return false;
5
+ let diff = 0;
6
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
7
+ return diff === 0;
8
+ }
9
+
10
+ export function bearer(request: Request): string {
11
+ const m = /^Bearer\s+(.+)$/i.exec(request.headers.get('authorization') ?? '');
12
+ return m ? m[1].trim() : '';
13
+ }
14
+
15
+ export const json = (body: unknown, status = 200) =>
16
+ new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' } });
17
+ export const notFound = () => new Response('Not found', { status: 404 });