@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
@@ -0,0 +1,339 @@
1
+ // 一期信:存草稿、記寄前檢查、核准、排程、暫停、續寄、取消。狀態只能照下表走,其他一律擋。
2
+ //
3
+ // draft → approved → scheduled → sending ⇄ paused → done
4
+ // draft/approved/scheduled/paused → cancelled
5
+ // approved → draft(內容改了)、scheduled → approved(取消排程)、scheduled → draft(內容改了)
6
+ //
7
+ // sending/done 只有派送程式(dispatch.ts)能進;人能做的是 pause/resume/cancel。
8
+ // 內容(讀者看得到的一切)算一個雜湊:核准與寄前檢查都綁在那個雜湊上,內容一改就退回 draft、要重新核准。
9
+
10
+ import { parseAddress, type Db } from '../core.ts';
11
+
12
+ export type CampaignStatus = 'draft' | 'approved' | 'scheduled' | 'sending' | 'paused' | 'done' | 'cancelled';
13
+ export const CAMPAIGN_STATUSES: readonly CampaignStatus[] = ['draft', 'approved', 'scheduled', 'sending', 'paused', 'done', 'cancelled'];
14
+
15
+ /** 合法轉換(from → 可去的狀態)。 */
16
+ export const TRANSITIONS: Readonly<Record<CampaignStatus, readonly CampaignStatus[]>> = {
17
+ draft: ['approved', 'cancelled'],
18
+ approved: ['draft', 'scheduled', 'cancelled'],
19
+ scheduled: ['draft', 'approved', 'sending', 'cancelled'],
20
+ sending: ['paused', 'done'],
21
+ paused: ['sending', 'cancelled'],
22
+ done: [],
23
+ cancelled: [],
24
+ };
25
+
26
+ export function canTransition(from: CampaignStatus, to: CampaignStatus): boolean {
27
+ return TRANSITIONS[from]?.includes(to) ?? false;
28
+ }
29
+
30
+ export type Audience = { plan: string } | { waves: string[][]; maxCount?: number };
31
+
32
+ export interface CampaignInput {
33
+ id: string;
34
+ list: string;
35
+ subject: string;
36
+ preheader?: string;
37
+ from: string;
38
+ replyTo?: string;
39
+ html: string;
40
+ text: string;
41
+ headers?: Record<string, string>;
42
+ /** 這期的網頁版網址(https;信裡的 {{web_url}})。排程前一定要有。 */
43
+ webUrl?: string;
44
+ sourceRef?: string;
45
+ audience: Audience;
46
+ }
47
+
48
+ export interface CampaignRow {
49
+ id: string; list_id: string; subject: string; preheader: string | null; from_addr: string; reply_to: string | null;
50
+ html: string; text: string; headers: string | null; web_url: string | null; source_ref: string | null; status: CampaignStatus;
51
+ audience: string; audience_resolved: string | null; content_hash: string; approved_hash: string | null;
52
+ approved_at: string | null; approved_note: string | null; preflight: string | null; scheduled_at: string | null;
53
+ started_at: string | null; frozen_at: string | null; last_release_at: string | null; waiting_since: string | null; last_progress_at: string | null;
54
+ finished_at: string | null; pause_reason: string | null; counts: string | null; created_at: string; updated_at: string;
55
+ }
56
+
57
+ export type Fail = { ok: false; reason: string; status?: CampaignStatus; twin?: string; twinStatus?: CampaignStatus; twinBy?: 'web_url' | 'content' | 'source_ref' };
58
+ export type Ok<T = object> = { ok: true } & T;
59
+
60
+ export const CAMPAIGN_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
61
+ const LIST_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
62
+ const SEGMENT = /^[^\u0000-\u001f\u007f]{1,64}$/;
63
+ /** 一期信能自帶的標頭:只收退訂兩個標頭、List-Id 與 X- 開頭的(寄件人、收件人、主旨等一律由引擎自己組,不准從這裡帶)。 */
64
+ export const EXTRA_HEADER = /^(?:list-unsubscribe|list-unsubscribe-post|list-id|x-[a-z0-9-]{1,60})$/i;
65
+ const LIMITS = { subject: 300, preheader: 300, html: 400_000, text: 200_000, note: 300, reason: 200, sourceRef: 300 };
66
+ const nowIso = (now?: () => Date) => (now ?? (() => new Date()))().toISOString();
67
+ const ctl = (s: string) => /[\u0000-\u001f\u007f]/.test(s);
68
+
69
+ /** 讀者看得到的一切(含名單與寄件人)算一個雜湊。 */
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 raw = JSON.stringify([c.list, c.subject, c.preheader ?? '', c.from, c.replyTo ?? '', c.html, c.text, Object.entries(c.headers ?? {}).sort(), c.webUrl ?? '']);
72
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw));
73
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
74
+ }
75
+
76
+ /** 收件群設定檢查:plan 要有名字;waves 要是非空的二維字串陣列、同一個群不能出現兩次。 */
77
+ export function checkAudience(a: unknown): Audience | null {
78
+ if (!a || typeof a !== 'object' || Array.isArray(a)) return null;
79
+ const o = a as Record<string, unknown>;
80
+ if ('plan' in o) return typeof o.plan === 'string' && CAMPAIGN_ID.test(o.plan) && Object.keys(o).length === 1 ? { plan: o.plan } : null;
81
+ const waves = checkWaves(o.waves);
82
+ if (!waves) return null;
83
+ if (o.maxCount !== undefined && !(Number.isInteger(o.maxCount) && (o.maxCount as number) > 0)) return null;
84
+ return o.maxCount === undefined ? { waves } : { waves, maxCount: o.maxCount as number };
85
+ }
86
+
87
+ export function checkWaves(w: unknown): string[][] | null {
88
+ if (!Array.isArray(w) || w.length === 0 || w.length > 20) return null;
89
+ const seen = new Set<string>();
90
+ const out: string[][] = [];
91
+ for (const wave of w) {
92
+ if (!Array.isArray(wave) || wave.length === 0 || wave.length > 50) return null;
93
+ const segs: string[] = [];
94
+ for (const s of wave) {
95
+ if (typeof s !== 'string' || !SEGMENT.test(s) || seen.has(s)) return null;
96
+ seen.add(s);
97
+ segs.push(s);
98
+ }
99
+ out.push(segs);
100
+ }
101
+ // 「*」(其他所有人)只能放在最後一波的最後一個。群總數上限 20(凍結那條 SQL 的綁定值才不會超過 D1 上限)。
102
+ const flat = out.flat();
103
+ if (flat.length > 20) return null;
104
+ if (flat.includes('*') && flat.indexOf('*') !== flat.length - 1) return null;
105
+ return out;
106
+ }
107
+
108
+ /** 網頁版網址比對用:主機小寫、去掉 utm 參數與 #片段、路徑結尾斜線、預設埠。 */
109
+ export function normalizeWebUrl(u: string): string {
110
+ try {
111
+ const x = new URL(u);
112
+ x.hash = '';
113
+ for (const k of [...x.searchParams.keys()]) if (/^utm_/i.test(k)) x.searchParams.delete(k);
114
+ x.searchParams.sort();
115
+ const path = x.pathname.replace(/\/+$/, '') || '/';
116
+ return `${x.protocol}//${x.host.toLowerCase()}${path}${x.search}`;
117
+ } catch {
118
+ return u.trim().toLowerCase();
119
+ }
120
+ }
121
+
122
+ async function findTwin(db: Db, input: CampaignInput, _hash: string): Promise<{ id: string; status: CampaignStatus; by: 'web_url' | 'content' | 'source_ref' } | null> {
123
+ const rows = (
124
+ await db
125
+ .prepare("SELECT id, status, web_url, source_ref, (list_id = ? AND html = ? AND text = ?) AS same_body FROM campaigns WHERE id <> ? AND status <> 'cancelled'")
126
+ .bind(input.list, input.html, input.text, input.id)
127
+ .all<{ id: string; status: CampaignStatus; web_url: string | null; source_ref: string | null; same_body: number }>()
128
+ ).results;
129
+ const mine = input.webUrl ? normalizeWebUrl(input.webUrl) : null;
130
+ for (const r of rows) {
131
+ if (mine && r.web_url && normalizeWebUrl(r.web_url) === mine) return { id: r.id, status: r.status, by: 'web_url' };
132
+ if (Number(r.same_body) === 1) return { id: r.id, status: r.status, by: 'content' };
133
+ if (input.sourceRef && r.source_ref === input.sourceRef && r.status !== 'done') return { id: r.id, status: r.status, by: 'source_ref' };
134
+ }
135
+ return null;
136
+ }
137
+
138
+ function checkInput(input: CampaignInput, marketingDomain: string): string | null {
139
+ if (!input || typeof input !== 'object') return 'bad_request';
140
+ if (typeof input.id !== 'string' || !CAMPAIGN_ID.test(input.id)) return 'bad_id';
141
+ if (typeof input.list !== 'string' || !LIST_ID.test(input.list)) return 'bad_list';
142
+ if (typeof input.subject !== 'string' || !input.subject.trim() || input.subject.length > LIMITS.subject || ctl(input.subject)) return 'bad_subject';
143
+ if (input.preheader !== undefined && (typeof input.preheader !== 'string' || input.preheader.length > LIMITS.preheader || ctl(input.preheader))) return 'bad_preheader';
144
+ const from = parseAddress(String(input.from ?? ''));
145
+ if (!from || !marketingDomain || !from.addr.endsWith(`@${marketingDomain.toLowerCase()}`)) return 'bad_from';
146
+ if (input.replyTo !== undefined && !parseAddress(input.replyTo)) return 'bad_reply_to';
147
+ if (typeof input.html !== 'string' || !input.html || input.html.length > LIMITS.html) return 'bad_html';
148
+ if (typeof input.text !== 'string' || !input.text || input.text.length > LIMITS.text) return 'bad_text';
149
+ if (input.headers !== undefined) {
150
+ if (!input.headers || typeof input.headers !== 'object' || Array.isArray(input.headers)) return 'bad_headers';
151
+ for (const [k, v] of Object.entries(input.headers)) if (!EXTRA_HEADER.test(k) || typeof v !== 'string' || v.length > 2000 || /[\r\n]/.test(v)) return 'bad_headers';
152
+ }
153
+ if (input.webUrl !== undefined && (typeof input.webUrl !== 'string' || input.webUrl.length > 2000 || !/^https:\/\/[^\s<>"]+$/i.test(input.webUrl))) return 'bad_web_url';
154
+ if (input.sourceRef !== undefined && (typeof input.sourceRef !== 'string' || input.sourceRef.length > LIMITS.sourceRef || ctl(input.sourceRef))) return 'bad_source_ref';
155
+ if (!checkAudience(input.audience)) return 'bad_audience';
156
+ return null;
157
+ }
158
+
159
+ export async function getCampaign(db: Db, id: string): Promise<CampaignRow | null> {
160
+ if (typeof id !== 'string' || !CAMPAIGN_ID.test(id)) return null;
161
+ return db.prepare('SELECT * FROM campaigns WHERE id = ?').bind(id).first<CampaignRow>();
162
+ }
163
+
164
+ /**
165
+ * 存草稿:新的一期建成 draft;已存在的只有 draft/approved/scheduled 能改,改了一律退回 draft
166
+ * (清掉核准與寄前檢查)。sending 之後不能改內容。
167
+ */
168
+ export async function saveDraft(db: Db, input: CampaignInput, opts: { marketingDomain: string; now?: () => Date }): Promise<Ok<{ status: CampaignStatus; changed: boolean }> | Fail> {
169
+ const bad = checkInput(input, opts.marketingDomain);
170
+ if (bad) return { ok: false, reason: bad };
171
+ 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);
173
+ const audience = JSON.stringify(checkAudience(input.audience));
174
+ const headers = input.headers ? JSON.stringify(input.headers) : null;
175
+ const t = nowIso(opts.now);
176
+ const existing = await getCampaign(db, input.id);
177
+ // 同一份內容不能用不同期號建兩次(會寄兩封):網頁版網址(正規化後)、同名單同內文、原稿位置任一相同,且對方沒被取消,就擋。
178
+ // 原稿位置只跟「還沒寄完」的期比(同一個原稿路徑每期都會重用,寄完的舊期不該擋新的一期);網址與內文跟寄完的也比。
179
+ const twin = await findTwin(db, input, hash);
180
+ if (twin) return { ok: false, reason: 'duplicate_content', twin: twin.id, twinStatus: twin.status, twinBy: twin.by };
181
+ if (!existing) {
182
+ const r = await db
183
+ .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`,
186
+ )
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)
188
+ .run();
189
+ if ((r.meta.changes ?? 0) === 1) return { ok: true, status: 'draft', changed: true };
190
+ return { ok: false, reason: 'conflict' };
191
+ }
192
+ if (!['draft', 'approved', 'scheduled'].includes(existing.status)) return { ok: false, reason: 'locked', status: existing.status };
193
+ if (existing.content_hash === hash && existing.audience === audience && existing.list_id === input.list && (existing.source_ref ?? null) === (input.sourceRef ?? null)) {
194
+ return { ok: true, status: existing.status, changed: false };
195
+ }
196
+ const r = await db
197
+ .prepare(
198
+ `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 = ?
200
+ WHERE id = ? AND status IN ('draft', 'approved', 'scheduled')`,
201
+ )
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)
203
+ .run();
204
+ if ((r.meta.changes ?? 0) !== 1) return { ok: false, reason: 'locked' };
205
+ return { ok: true, status: 'draft', changed: true };
206
+ }
207
+
208
+ /** 寄前檢查結果(compose 的 preflight 產生)的最小形狀。 */
209
+ export interface PreflightRecord { ok: boolean; issues?: { severity?: string; code?: string; message?: string }[] }
210
+
211
+ /**
212
+ * 記下寄前檢查結果,綁在目前的內容雜湊上。檢查是在呼叫端跑的(要打網路查連結),
213
+ * 引擎只認「ok 而且雜湊對得上」才准排程。
214
+ */
215
+ export async function recordPreflight(db: Db, id: string, result: PreflightRecord, now?: () => Date): Promise<Ok<{ preflightOk: boolean }> | Fail> {
216
+ const c = await getCampaign(db, id);
217
+ if (!c) return { ok: false, reason: 'not_found' };
218
+ if (!['draft', 'approved', 'scheduled'].includes(c.status)) return { ok: false, reason: 'locked', status: c.status };
219
+ if (!result || typeof result !== 'object' || typeof result.ok !== 'boolean') return { ok: false, reason: 'bad_preflight' };
220
+ const errors = Array.isArray(result.issues) ? result.issues.filter((i) => i && i.severity === 'error').slice(0, 50).map((i) => String(i.code ?? i.message ?? 'error').slice(0, 100)) : [];
221
+ // 回報 ok 但列了 error=自相矛盾,當沒過。
222
+ const ok = result.ok && errors.length === 0;
223
+ // 給預覽頁看的明細(只留嚴重度、代碼、說明,截長;不放收件人資料)。
224
+ const issues = Array.isArray(result.issues)
225
+ ? result.issues.filter((i) => i && typeof i === 'object').slice(0, 50).map((i) => ({ severity: String(i.severity ?? '').slice(0, 10), code: String(i.code ?? '').slice(0, 60), message: String(i.message ?? '').slice(0, 300) }))
226
+ : [];
227
+ const record = JSON.stringify({ ok, hash: c.content_hash, at: nowIso(now), errors, issues });
228
+ const r = await db.prepare('UPDATE campaigns SET preflight = ?, updated_at = ? WHERE id = ? AND content_hash = ?').bind(record, nowIso(now), id, c.content_hash).run();
229
+ if ((r.meta.changes ?? 0) !== 1) return { ok: false, reason: 'changed_meanwhile' };
230
+ // 檢查沒過:已排程的退回 approved(不准留在 scheduled)。
231
+ if (!ok && c.status === 'scheduled') await db.prepare("UPDATE campaigns SET status = 'approved', scheduled_at = NULL WHERE id = ? AND status = 'scheduled'").bind(id).run();
232
+ return { ok: true, preflightOk: ok };
233
+ }
234
+
235
+ function preflightPasses(c: CampaignRow): boolean {
236
+ if (!c.preflight) return false;
237
+ try {
238
+ const p = JSON.parse(c.preflight) as { ok?: unknown; hash?: unknown };
239
+ return p.ok === true && p.hash === c.content_hash;
240
+ } catch {
241
+ return false;
242
+ }
243
+ }
244
+
245
+ async function move(db: Db, id: string, from: CampaignStatus[], to: CampaignStatus, sets: string, binds: unknown[], now?: () => Date): Promise<Ok<{ status: CampaignStatus }> | Fail> {
246
+ for (const f of from) if (!canTransition(f, to)) throw new Error(`transition table forbids ${f} -> ${to}`);
247
+ const c = await getCampaign(db, id);
248
+ if (!c) return { ok: false, reason: 'not_found' };
249
+ if (!from.includes(c.status)) return { ok: false, reason: 'illegal_transition', status: c.status };
250
+ const r = await db
251
+ .prepare(`UPDATE campaigns SET status = ?, ${sets ? `${sets}, ` : ''}updated_at = ? WHERE id = ? AND status = ? AND content_hash = ?`)
252
+ .bind(to, ...binds, nowIso(now), id, c.status, c.content_hash)
253
+ .run();
254
+ if ((r.meta.changes ?? 0) !== 1) return { ok: false, reason: 'changed_meanwhile' };
255
+ return { ok: true, status: to };
256
+ }
257
+
258
+ function cleanText(v: unknown, max: number): string | null {
259
+ return typeof v === 'string' && v.trim() && !ctl(v) ? v.trim().slice(0, max) : null;
260
+ }
261
+
262
+ /** 核准:只在本人看過預覽、明確說好之後執行;note 要寫「誰、什麼時候、在哪說的」。 */
263
+ export async function approveCampaign(db: Db, id: string, note: string, now?: () => Date): Promise<Ok<{ status: CampaignStatus }> | Fail> {
264
+ const n = cleanText(note, LIMITS.note);
265
+ if (!n) return { ok: false, reason: 'note_required' };
266
+ const c = await getCampaign(db, id);
267
+ if (!c) return { ok: false, reason: 'not_found' };
268
+ return move(db, id, ['draft'], 'approved', 'approved_hash = content_hash, approved_at = ?, approved_note = ?', [nowIso(now), n], now);
269
+ }
270
+
271
+ /** 排程(at=ISO 時間):要已核准、核准的就是現在這份內容、寄前檢查過了、收件群有效。 */
272
+ export async function scheduleCampaign(db: Db, id: string, at: string, now?: () => Date): Promise<Ok<{ status: CampaignStatus; scheduledAt: string }> | Fail> {
273
+ const c = await getCampaign(db, id);
274
+ if (!c) return { ok: false, reason: 'not_found' };
275
+ if (c.status !== 'approved') return { ok: false, reason: 'illegal_transition', status: c.status };
276
+ if (c.approved_hash !== c.content_hash) return { ok: false, reason: 'not_approved' };
277
+ if (!preflightPasses(c)) return { ok: false, reason: 'preflight_not_passed' };
278
+ if (!c.web_url) return { ok: false, reason: 'web_url_required' };
279
+ if (typeof at !== 'string' || Number.isNaN(Date.parse(at))) return { ok: false, reason: 'bad_time' };
280
+ let audience: Audience | null = null;
281
+ try {
282
+ audience = checkAudience(JSON.parse(c.audience));
283
+ } catch {
284
+ /* 下面擋 */
285
+ }
286
+ if (!audience) return { ok: false, reason: 'bad_audience' };
287
+ if ('plan' in audience && !(await db.prepare('SELECT 1 AS x FROM warmup_steps WHERE plan_id = ? LIMIT 1').bind(audience.plan).first())) return { ok: false, reason: 'unknown_plan' };
288
+ const iso = new Date(at).toISOString();
289
+ const r = await move(db, id, ['approved'], 'scheduled', 'scheduled_at = ?', [iso], now);
290
+ return r.ok ? { ok: true, status: r.status, scheduledAt: iso } : r;
291
+ }
292
+
293
+ /** 取消排程(退回 approved)。 */
294
+ export function unscheduleCampaign(db: Db, id: string, now?: () => Date) {
295
+ return move(db, id, ['scheduled'], 'approved', 'scheduled_at = NULL', [], now);
296
+ }
297
+
298
+ /** 人工暫停(寄送中)。 */
299
+ export function pauseCampaign(db: Db, id: string, reason: string, now?: () => Date) {
300
+ const r = cleanText(reason, LIMITS.reason);
301
+ if (!r) return Promise.resolve<Fail>({ ok: false, reason: 'reason_required' });
302
+ return move(db, id, ['sending'], 'paused', 'pause_reason = ?', [`manual: ${r}`], now);
303
+ }
304
+
305
+ /**
306
+ * 續寄:只有 paused 能續;note 必填(寫查過什麼、為什麼可以繼續)。
307
+ * 寄件網域被整個停掉時不能續(要先解除網域停寄)。
308
+ */
309
+ export async function resumeCampaign(db: Db, id: string, note: string, opts: { marketingDomain: string; now?: () => Date }): Promise<Ok<{ status: CampaignStatus }> | Fail> {
310
+ const n = cleanText(note, LIMITS.note);
311
+ if (!n) return { ok: false, reason: 'note_required' };
312
+ const hold = await db.prepare('SELECT reason FROM domain_holds WHERE domain = ? AND released_at IS NULL LIMIT 1').bind(opts.marketingDomain).first<{ reason: string }>();
313
+ if (hold) return { ok: false, reason: 'domain_held' };
314
+ // 「最後進度」順便更新:不然暫停很久之後一續寄,就被當成 Queue 卡住。
315
+ // 只有「讓這期停下來的那一道煞車」從續寄這一刻重新起算(ackBrake+brakeSince):人查過的就是那一項。
316
+ // 為了別的原因暫停(人工、Queue 卡住、對帳…)再續寄,比率照舊全部算,不會被清零。
317
+ const c = await getCampaign(db, id);
318
+ const m = /^brake:(hard_bounce_rate|complaint_rate|wave_gate)\b/.exec(c?.pause_reason ?? '');
319
+ const t = nowIso(opts.now);
320
+ return move(
321
+ db, id, ['paused'], 'sending',
322
+ "pause_reason = NULL, last_progress_at = ?, waiting_since = NULL, counts = json_set(COALESCE(counts, '{}'), '$.lastResumeNote', ?, '$.ackBrake', ?, '$.brakeSince', ?)",
323
+ [t, n, m ? m[1] : null, m ? t : null], opts.now,
324
+ );
325
+ }
326
+
327
+ /**
328
+ * 取消:開寄前(draft/approved/scheduled)或暫停中才能取消;寄送中要先暫停。
329
+ * 暫停中取消:還沒寄的人記成 skipped/cancelled(已經交出去的那幾封由派送端看到 cancelled 後跳過)。
330
+ */
331
+ export async function cancelCampaign(db: Db, id: string, reason: string, now?: () => Date): Promise<Ok<{ status: CampaignStatus }> | Fail> {
332
+ const r = cleanText(reason, LIMITS.reason);
333
+ if (!r) return { ok: false, reason: 'reason_required' };
334
+ const out = await move(db, id, ['draft', 'approved', 'scheduled', 'paused'], 'cancelled', 'pause_reason = ?, finished_at = ?', [`cancelled: ${r}`, nowIso(now)], now);
335
+ if (out.ok) {
336
+ await db.prepare("UPDATE campaign_recipients SET state = 'skipped', skip_reason = 'cancelled' WHERE campaign_id = ? AND state IN ('planned', 'enqueued')").bind(id).run();
337
+ }
338
+ return out;
339
+ }
@@ -0,0 +1,136 @@
1
+ // 群發的設定值(門檻、配速、暖機過關條件)。引擎給保守預設值;部署端用 JSON 只覆寫想改的欄位。
2
+
3
+ export interface BroadcastConfig {
4
+ /** 電子報那類帳本列的「站名」(messages.site)。 */
5
+ site: string;
6
+ /** 自己的每日上限(防程式錯誤一次寄爆),跟郵差給的每日上限取小。 */
7
+ maxPerDay: number;
8
+ /** 每分鐘放水最多用到郵差每秒上限的幾成(×60)。 */
9
+ rateFactor: number;
10
+ /** 一期要拉多長寄完(分鐘):每分鐘放水 ≤ ceil(這期要寄的人數 ÷ 這個數)。 */
11
+ paceMinutes: number;
12
+ /** 下一波最早在上一波開始後幾分鐘開始。 */
13
+ waveGapMinutes: number;
14
+ /** 上一波最後一封寄出後,至少等幾分鐘收退信,才判斷能不能開下一波。 */
15
+ waveGateWaitMinutes: number;
16
+ /** 上一波的永久退信率達到(≥)這個值,下一波不開、這期暫停。 */
17
+ waveGateBounceRate: number;
18
+ /** 本期寄出滿這麼多封,才開始算「寄到一半停」的比率。 */
19
+ brakeMinSent: number;
20
+ /** 本期永久退信率 ≥ 這個值 → 暫停本期。 */
21
+ brakeHardBounceRate: number;
22
+ /** 本期檢舉件數 ≥ 這個值、且檢舉率 ≥ brakeComplaintRate → 暫停本期。 */
23
+ brakeComplaintCount: number;
24
+ brakeComplaintRate: number;
25
+ /** 寄件網域的滾動退信率 ≥ 這個值 → 整個寄件網域停寄。 */
26
+ domainBounceRate: number;
27
+ /** 寄件網域的滾動檢舉率 ≥ 這個值 → 整個寄件網域停寄。 */
28
+ domainComplaintRate: number;
29
+ /** 滾動比率看最近幾天寄出的信。 */
30
+ domainWindowDays: number;
31
+ /** 視窗內寄出少於這個數,不算滾動比率(樣本太小)。 */
32
+ domainMinSent: number;
33
+ /** 寄件網域檢舉率要停整個網域,除了比率之外,視窗內至少要有這麼多件檢舉(預設 1=沒有額外下限,照原本規則)。樣本小時 1 件就過線,試寄演練前依實況決定要不要調高。 */
34
+ domainMinComplaints: number;
35
+ /** 分波閘門要判斷上一波,至少要有這麼多封已寄出(預設 1=沒有額外下限)。每波人數少時 1 封退信就會讓比率過線。 */
36
+ waveGateMinSent: number;
37
+ /** 已排程的期過了原定時間超過這麼多分鐘還沒開寄(郵差不健康、網域停寄、Worker 停擺…),就退回「已核准」等人重排,不自動開寄。 */
38
+ startGraceMinutes: number;
39
+ /** 「已交 Queue」超過幾分鐘沒有結果 → 退回待放水、重新放(去重鍵保證不重寄)。 */
40
+ stuckMinutes: number;
41
+ /** 有交出去的工作、卻這麼多分鐘沒有任何一封有結果 → 判定 Queue 壞了,暫停本期。 */
42
+ stallMinutes: number;
43
+ /** 同一人暫時失敗最多試幾次,之後記成失敗。 */
44
+ maxAttempts: number;
45
+ /** 最近連續這麼多位都被郵差永久拒收(中間沒有寄成功的)→ 暫停本期(多半是設定問題)。 */
46
+ permanentStreak: number;
47
+ /** 郵差回限流時,那一封幾秒後再試。 */
48
+ throttleRetrySeconds: number;
49
+ /** 「今天」的時差(小時),每日上限以這個日期換日。 */
50
+ utcOffsetHours: number;
51
+ /** 多久重新讀一次郵差的上限與健康狀態(分鐘)。 */
52
+ limitsRefreshMinutes: number;
53
+ /** 暖機過關:上一期結束後滿幾小時才評。 */
54
+ gateWaitHours: number;
55
+ /** 暖機過關:永久退信率要 ≤ 這個值。 */
56
+ gateBounceRate: number;
57
+ /** 暖機過關:檢舉率要 ≤ 這個值。 */
58
+ gateComplaintRate: number;
59
+ /** 暖機過關:開信率不得比同一批人的基準低超過這麼多(0.05=5 個百分點)。 */
60
+ gateOpenDrop: number;
61
+ /** 連續幾期不過關 → 這條梯子鎖住,要明確解鎖才繼續寄。 */
62
+ gateMaxFails: number;
63
+ }
64
+
65
+ export const DEFAULT_BROADCAST_CONFIG: Readonly<BroadcastConfig> = Object.freeze({
66
+ site: 'newsletter',
67
+ maxPerDay: 3000,
68
+ rateFactor: 0.8,
69
+ paceMinutes: 150,
70
+ waveGapMinutes: 60,
71
+ waveGateWaitMinutes: 30,
72
+ waveGateBounceRate: 0.02,
73
+ brakeMinSent: 200,
74
+ brakeHardBounceRate: 0.04,
75
+ brakeComplaintCount: 3,
76
+ brakeComplaintRate: 0.001,
77
+ domainBounceRate: 0.04,
78
+ domainComplaintRate: 0.0008,
79
+ domainWindowDays: 30,
80
+ domainMinSent: 200,
81
+ domainMinComplaints: 1,
82
+ waveGateMinSent: 1,
83
+ startGraceMinutes: 360,
84
+ stuckMinutes: 10,
85
+ stallMinutes: 30,
86
+ maxAttempts: 3,
87
+ permanentStreak: 5,
88
+ throttleRetrySeconds: 30,
89
+ utcOffsetHours: 8,
90
+ limitsRefreshMinutes: 60,
91
+ gateWaitHours: 72,
92
+ gateBounceRate: 0.02,
93
+ gateComplaintRate: 0.001,
94
+ gateOpenDrop: 0.05,
95
+ gateMaxFails: 2,
96
+ });
97
+
98
+ const SITE = /^[a-z0-9][a-z0-9-]{0,39}$/;
99
+ /** 「下限」類設定的上限:設太大等於把那道煞車關掉,超過就當寫錯、用預設值(並在 log 留一行)。 */
100
+ const MAX_VALUE: Partial<Record<keyof BroadcastConfig, number>> = { domainMinComplaints: 10, waveGateMinSent: 100, startGraceMinutes: 2880 };
101
+
102
+ /**
103
+ * 合併設定:只收「型別對、數值合理」的欄位,其他一律用預設值(寫錯不能變成「不設防」)。
104
+ * 比率要在 0~1 之間;次數、分鐘要是正數。
105
+ */
106
+ export function resolveConfig(over?: Partial<BroadcastConfig> | string | null): BroadcastConfig {
107
+ let o: Record<string, unknown> = {};
108
+ if (typeof over === 'string') {
109
+ try {
110
+ const parsed = JSON.parse(over);
111
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) o = parsed;
112
+ } catch {
113
+ console.error('bad broadcast config json');
114
+ }
115
+ } else if (over && typeof over === 'object') o = over as Record<string, unknown>;
116
+ const out: BroadcastConfig = { ...DEFAULT_BROADCAST_CONFIG };
117
+ for (const key of Object.keys(DEFAULT_BROADCAST_CONFIG) as (keyof BroadcastConfig)[]) {
118
+ const v = o[key];
119
+ if (v === undefined || v === null) continue;
120
+ if (key === 'site') {
121
+ if (typeof v === 'string' && SITE.test(v)) out.site = v;
122
+ continue;
123
+ }
124
+ const n = typeof v === 'string' && v.trim() !== '' ? Number(v) : v;
125
+ if (typeof n !== 'number' || !Number.isFinite(n)) continue;
126
+ const isRate = key.endsWith('Rate') || key === 'rateFactor' || key === 'gateOpenDrop';
127
+ if (isRate ? n < 0 || n > 1 : key === 'utcOffsetHours' ? n < -14 || n > 14 : n <= 0) continue;
128
+ const cap = MAX_VALUE[key];
129
+ if (cap !== undefined && n > cap) {
130
+ console.error(`broadcast config ${key} above ${cap}: using the default`);
131
+ continue;
132
+ }
133
+ (out as unknown as Record<string, number>)[key] = n;
134
+ }
135
+ return out;
136
+ }