@joelincc/mailroom 0.1.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.
Files changed (80) hide show
  1. package/README.md +54 -8
  2. package/SECURITY.md +1 -1
  3. package/bin/mailroom.mjs +26 -0
  4. package/dist/broadcast/config.js +79 -0
  5. package/dist/broadcast/explain.js +50 -0
  6. package/dist/cli/args.js +29 -0
  7. package/dist/cli/errors.js +37 -0
  8. package/dist/cli/main.js +533 -0
  9. package/dist/compose/clicks.js +29 -0
  10. package/dist/compose/compose.js +275 -0
  11. package/dist/compose/index.js +8 -0
  12. package/dist/compose/markdown.js +1197 -0
  13. package/dist/compose/personalize.js +123 -0
  14. package/dist/compose/preflight.js +251 -0
  15. package/dist/compose/preview.js +41 -0
  16. package/dist/compose/render.js +141 -0
  17. package/dist/compose/template.js +118 -0
  18. package/docs/broadcast.md +199 -0
  19. package/docs/composing.md +156 -0
  20. package/docs/desk-commands.md +52 -0
  21. package/docs/export.md +52 -0
  22. package/docs/lists.md +68 -0
  23. package/docs/security-model.md +6 -4
  24. package/docs/ses.md +116 -0
  25. package/docs/tracking.md +102 -0
  26. package/docs/unsubscribe.md +124 -0
  27. package/docs/welcome.md +72 -0
  28. package/migrations/0004_last_error.sql +2 -0
  29. package/migrations/0005_lists.sql +41 -0
  30. package/migrations/0006_broadcast.sql +154 -0
  31. package/migrations/0007_unsubscribe.sql +12 -0
  32. package/migrations/0008_tracking.sql +5 -0
  33. package/migrations/0009_welcome.sql +17 -0
  34. package/package.json +21 -3
  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 +352 -0
  39. package/src/broadcast/config.ts +136 -0
  40. package/src/broadcast/dispatch.ts +779 -0
  41. package/src/broadcast/events.ts +110 -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 +218 -0
  54. package/src/cf-events.ts +4 -3
  55. package/src/cli/args.ts +27 -0
  56. package/src/cli/errors.ts +39 -0
  57. package/src/cli/main.ts +515 -0
  58. package/src/compose/clicks.ts +45 -0
  59. package/src/compose/compose.ts +297 -0
  60. package/src/compose/index.ts +8 -0
  61. package/src/compose/markdown.ts +1173 -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 +158 -0
  66. package/src/compose/template.ts +197 -0
  67. package/src/core.ts +45 -2
  68. package/src/export.ts +184 -0
  69. package/src/feedback.ts +128 -0
  70. package/src/http.ts +17 -0
  71. package/src/index.ts +146 -32
  72. package/src/list-routes.ts +55 -0
  73. package/src/lists.ts +381 -0
  74. package/src/ses-events.ts +426 -0
  75. package/src/track.ts +409 -0
  76. package/src/unsub-wiring.ts +64 -0
  77. package/src/unsub.ts +499 -0
  78. package/src/webhook.ts +5 -3
  79. package/src/welcome.ts +257 -0
  80. package/wrangler.example.jsonc +16 -2
package/src/index.ts CHANGED
@@ -3,19 +3,35 @@
3
3
  // 兩個入口:
4
4
  // - 內線(service binding):同一個 Cloudflare 帳號的站在 wrangler.jsonc 加
5
5
  // { "binding": "MAILROOM", "service": "mailroom", "entrypoint": "Mailroom" },呼叫 env.MAILROOM.send({...})。
6
- // - 公開網址(workers.dev):Resend 事後回報 POST /webhooks/resend;
6
+ // - 公開網址(workers.dev):Resend 事後回報 POST /webhooks/resend;SES 事後回報(SNS)POST /webhooks/ses;
7
7
  // 別的 Cloudflare 帳號的站帶自己的鑰匙 POST /v1/send;演習 POST /v1/drill;寄信統計 GET /v1/report;
8
8
  // 人工解除拒收 POST /v1/unsuppress。
9
+ // - 退訂:GET/POST /u/{券}、POST /u/{券}/resubscribe;email() 收退訂信。
10
+ // - 追蹤(TRACK_BASE_URL 那個 host):GET /c/{券} 點擊轉址、GET /o/{券}.gif 開信圖(見 src/track.ts、docs/tracking.md)。
11
+ // - 名單管理(帶管理口令):PUT /v1/lists/{id}、POST /v1/lists/{id}/import、POST /v1/lists/{id}/segments。
12
+ // - 群發(帶管理口令):/v1/campaigns/*、/v1/throttle、/v1/warmup/*、/v1/broadcast/*(見 src/broadcast/routes.ts);Queue mailroom-broadcast;排程每分鐘放水。
9
13
  // - Queue:Cloudflare 寄信的事後回報(cf-events.ts)。
10
- // - 排程:有設 cron 與 DAILY_DRILL 時,每天最多寄一輪演習信(過了 until 自動停)。
14
+ // - 排程:有設 cron 時,每次順手清舊計數窗;有設 DAILY_DRILL 時每天最多寄一輪演習信(過了 until 自動停);有設 LEDGER_RETENTION_DAYS 時清過期帳本列。
11
15
 
12
16
  import { WorkerEntrypoint } from 'cloudflare:workers';
13
- import { bodySizeProblem, limitVar, localDay, lookup, parseAddress, pruneRate, removeSuppression, send, SUPPRESSION_REASONS, takeRate, TIERS, type SuppressionReason, type CoreDeps, type MessageRow, type RouteTable, type SendRequest, type SendResult, type Tier } from './core.ts';
17
+ import { bodySizeProblem, checkHttpFrom, limitVar, localDay, lookup, parseAddress, pruneRate, purgeLedger, removeSuppression, retentionDays, send, SUPPRESSION_REASONS, takeRate, TIERS, type SuppressionReason, type CoreDeps, type MessageRow, type RouteTable, type SendRequest, type SendResult, type Tier } from './core.ts';
14
18
  import { handleCfEvent } from './cf-events.ts';
19
+ import { listMembers, listStatus, listUnsubscribe, type SubscribeInput, type SubscribeResult, type UnsubscribeInput } from './lists.ts';
20
+ import { subscribeWithWelcome, type WelcomeQueue } from './welcome.ts';
21
+ import { bearer, json, notFound, sameToken } from './http.ts';
22
+ import { ADMIN_LIMITS, routeLists } from './list-routes.ts';
23
+ import { routeExport } from './export.ts';
24
+ import { handleUnsubRequest, unsubscribeLinksForEmail, unsubSecrets, type UnsubLinks } from './unsub.ts';
25
+ import { flushUnsubAlerts, handleEmailMessage, unsubConfig } from './unsub-wiring.ts';
26
+ import { warnIfNoAlert } from './alert.ts';
15
27
  import { MAIL_ROUTES, type CloudflareSender, type MailRoute } from './transport.ts';
16
28
  import { handleEvent, verifySignature } from './webhook.ts';
29
+ import { handleSesWebhook } from './ses-events.ts';
30
+ import { handleBroadcastRequest, isBroadcastPath } from './broadcast/routes.ts';
31
+ import { broadcastDeps, broadcastQueue, broadcastTick, isBroadcastBatch, testSendDeps, type BroadcastEnv } from './broadcast/worker.ts';
32
+ import { handleTrackRequest, resolveTrackSettings, trackHost, trackSecrets } from './track.ts';
17
33
 
18
- export interface Env {
34
+ export interface Env extends BroadcastEnv {
19
35
  DB: D1Database;
20
36
  /** 第一層(一定要到)的寄件網域,例 notify.example.com。 */
21
37
  FROM_DOMAIN: string;
@@ -35,13 +51,33 @@ export interface Env {
35
51
  HTTP_RATE_PER_MIN?: string | number;
36
52
  /** 走公開網址的站每天最多幾次請求(預設 2000,UTC 日)。 */
37
53
  HTTP_DAILY_LIMIT?: string | number;
38
- /** 走公開網址的站准用的寄件地址(JSON:{ "站": ["app@notify.example.com"] })。沒列的站=該層網域內任一地址(並記警告)。 */
54
+ /** 走公開網址的站准用的寄件地址(JSON:{ "站": ["app@notify.example.com"] })。每個 HTTP client 都必須列;沒列的站一律拒收(from_allowlist_required)。 */
39
55
  HTTP_FROM?: Record<string, string[]> | string;
56
+ /** 帳本保存天數(正整數)。設了之後,排程(cron)每次會順手清掉超過天數的 messages 與 webhook_events;沒設=不自動清。 */
57
+ LEDGER_RETENTION_DAYS?: string | number;
40
58
  RESEND_API_KEY?: string;
41
59
  SMTP2GO_API_KEY?: string;
42
60
  RESEND_WEBHOOK_SECRET?: string;
43
61
  /** 管理口令(演習、查帳、統計、解除拒收);沒設=這些路徑一律 404。 */
44
62
  DRILL_TOKEN?: string;
63
+ /** 退訂券簽章鑰匙(Secret,至少 16 字元)。沒設=退訂端點回 503。 */
64
+ UNSUB_TOKEN_SECRET?: string;
65
+ /** 換鑰匙過渡期:舊鑰匙(逗號分隔),只用來驗證、不簽新券。過了過渡期就拿掉。 */
66
+ UNSUB_TOKEN_SECRET_PREVIOUS?: string;
67
+ /** 退訂網址的開頭(https,不含結尾斜線),例 https://u.example.com。 */
68
+ UNSUB_BASE_URL?: string;
69
+ /** 收退訂信的地址(Email Routing 轉進本 Worker 的 email()),例 unsubscribe@mail.example.com。 */
70
+ UNSUB_MAILTO?: string;
71
+ /** 讀者退訂沒成功時的告警 webhook(https,POST JSON:event、from、subject、token、at、text)。沒設=只寫 log,並警告。見 docs/unsubscribe.md。 */
72
+ UNSUB_ALERT_WEBHOOK?: string;
73
+ /** 選填:告警 webhook 的 Bearer 口令(Secret)。 */
74
+ UNSUB_ALERT_TOKEN?: string;
75
+ /** 退訂頁文字(JSON 物件,只寫想改的欄位,見 docs/unsubscribe.md)。 */
76
+ UNSUB_PAGE?: string | Record<string, unknown>;
77
+ /** SES 事件入口准收的 SNS 主題 ARN(逗號分隔)。沒設(或沒設 SES_REGION、SES_CONFIGURATION_SET)=POST /webhooks/ses 一律 404。 */
78
+ SES_SNS_TOPIC_ARNS?: string;
79
+ /** "true"=也收 SNS SignatureVersion 1(SHA1)。預設只收 2,主題請設 SignatureVersion=2。 */
80
+ SES_SNS_ALLOW_SHA1?: string;
45
81
  [key: `HTTP_KEY_${string}`]: string | undefined;
46
82
  }
47
83
 
@@ -49,8 +85,6 @@ export interface Env {
49
85
  const DEFAULT_HTTP_RATE_PER_MIN = 60;
50
86
  /** 公開網址入口每站每天預設上限。 */
51
87
  const DEFAULT_HTTP_DAILY_LIMIT = 2000;
52
- /** 管理口令入口(演習、查帳、統計、解除拒收)合計上限:口令外洩時,別人拿它也寄不了多少演習信。 */
53
- const ADMIN_LIMITS = { perMinute: 20, perDay: 200 };
54
88
  /** 請求內文上限(位元組,一定要帶 content-length):寄信 3 MB(內文上限 html 40 萬+text 20 萬字元,中文 UTF-8 一字 3 bytes)、webhook 256 KB。 */
55
89
  const MAX_SEND_BYTES = 3_000_000;
56
90
  const MAX_WEBHOOK_BYTES = 256_000;
@@ -151,18 +185,32 @@ export class Mailroom extends WorkerEntrypoint<Env> {
151
185
  drill(site: string, input: DrillInput) {
152
186
  return drill(this.env, site, input);
153
187
  }
154
- }
155
-
156
- function sameToken(a: string, b: string): boolean {
157
- if (!a || !b || a.length !== b.length) return false;
158
- let diff = 0;
159
- for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
160
- return diff === 0;
161
- }
162
-
163
- function bearer(request: Request): string {
164
- const m = /^Bearer\s+(.+)$/i.exec(request.headers.get('authorization') ?? '');
165
- return m ? m[1].trim() : '';
188
+ // 電子報名單(內線):見 docs/lists.md。
189
+ /** 加入名單。第一次加入(firstTime)而且群發總開關開著、這份名單的歡迎信打開時,排一封歡迎信(見 src/welcome.ts)。 */
190
+ async listSubscribe(input: SubscribeInput): Promise<SubscribeResult> {
191
+ // 總開關=群發設得起來(寄件網域、郵差、Queue 都有);關著就一封都不排。排信失敗不影響加入結果。
192
+ let switchOn = false;
193
+ try {
194
+ switchOn = broadcastDeps(this.env) !== null;
195
+ } catch {
196
+ switchOn = false;
197
+ }
198
+ return subscribeWithWelcome(this.env.DB, input, { queue: this.env.BROADCAST as unknown as WelcomeQueue | undefined, switchOn });
199
+ }
200
+ listUnsubscribe(input: UnsubscribeInput) {
201
+ return listUnsubscribe(this.env.DB, input);
202
+ }
203
+ listStatus(input: { list: string; email: string }) {
204
+ return listStatus(this.env.DB, input);
205
+ }
206
+ listMembers(input: { list: string; status?: 'subscribed' | 'unsubscribed'; cursor?: string | null; limit?: number }) {
207
+ return listMembers(this.env.DB, input);
208
+ }
209
+ /** 某人的退訂連結與兩個一鍵退訂標頭(url/mailto 對應 compose 的 unsubscribe_url/unsubscribe_mailto);不是成員=null。 */
210
+ async unsubscribeLinks(input: { list: string; email: string; campaign?: string | null }): Promise<UnsubLinks | null> {
211
+ const cfg = unsubConfig(this.env);
212
+ return unsubscribeLinksForEmail(this.env.DB, cfg.secrets, { baseUrl: this.env.UNSUB_BASE_URL ?? '', mailtoAddress: this.env.UNSUB_MAILTO }, input);
213
+ }
166
214
  }
167
215
 
168
216
  /** 帶鑰匙的站:鑰匙決定是哪個站,站名不聽請求本身的。 */
@@ -173,21 +221,31 @@ function clientSite(env: Env, token: string): string | null {
173
221
  return null;
174
222
  }
175
223
 
176
- const json = (body: unknown, status = 200) =>
177
- new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' } });
178
- const notFound = () => new Response('Not found', { status: 404 });
179
-
180
224
  /** 公開網址查帳只回狀態欄位,不回收件人、寄件人、主旨(口令外洩時不會變成查收件人的工具)。 */
181
225
  function publicRow(row: MessageRow | null) {
182
226
  if (!row) return null;
183
- const { id, stream, tier, site, dedupe_key, kind, status, route, attempts, last_event, error, created_at, updated_at, sent_at } = row;
184
- return { id, stream, tier, site, dedupe_key, kind, status, route, attempts, last_event, error, created_at, updated_at, sent_at };
227
+ const { id, stream, tier, site, dedupe_key, kind, status, route, attempts, last_event, error, last_error, created_at, updated_at, sent_at } = row;
228
+ return { id, stream, tier, site, dedupe_key, kind, status, route, attempts, last_event, error, last_error, created_at, updated_at, sent_at };
185
229
  }
186
230
 
187
231
  export default {
188
- async fetch(request: Request, env: Env): Promise<Response> {
232
+ async fetch(request: Request, env: Env, ctx?: ExecutionContext): Promise<Response> {
189
233
  const url = new URL(request.url);
190
234
 
235
+ // 開信與點擊追蹤:只在 TRACK_BASE_URL 的 host 上接 /c/、/o/;鑰匙或網址沒設=不處理。
236
+ const tHost = trackHost(env.TRACK_BASE_URL);
237
+ if (tHost && url.hostname.toLowerCase() === tHost) {
238
+ const site = (jsonVar<Record<string, unknown>>(env.BROADCAST_CONFIG) ?? {}).site;
239
+ const tracked = await handleTrackRequest(request, {
240
+ db: env.DB,
241
+ secrets: trackSecrets(env.TRACK_TOKEN_SECRET, env.TRACK_TOKEN_SECRET_PREVIOUS),
242
+ host: tHost,
243
+ settings: resolveTrackSettings(env.TRACK_CONFIG, typeof site === 'string' ? site : undefined),
244
+ waitUntil: ctx ? (p) => ctx.waitUntil(p) : undefined,
245
+ });
246
+ if (tracked) return tracked;
247
+ }
248
+
191
249
  if (url.pathname === '/webhooks/resend' && request.method === 'POST') {
192
250
  const size = bodySizeProblem(request.headers.get('content-length'), MAX_WEBHOOK_BYTES);
193
251
  if (size) return new Response(size, { status: size === 'missing' ? 411 : 413 });
@@ -200,6 +258,17 @@ export default {
200
258
  return json({ ok: true });
201
259
  }
202
260
 
261
+ if (url.pathname === '/webhooks/ses' && request.method === 'POST') {
262
+ const topicArns = (env.SES_SNS_TOPIC_ARNS ?? '').split(',').map((s) => s.trim()).filter(Boolean);
263
+ // 設定組也要有:沒有就無法只收自己的事件(同一個主題裡別的寄信會混進來),一律不收。
264
+ if (!topicArns.length || !env.SES_REGION || !env.SES_CONFIGURATION_SET) return notFound();
265
+ const size = bodySizeProblem(request.headers.get('content-length'), MAX_WEBHOOK_BYTES);
266
+ if (size) return new Response(size, { status: size === 'missing' ? 411 : 413 });
267
+ const r = await handleSesWebhook(env.DB, await request.text(), { region: env.SES_REGION, topicArns, configurationSet: env.SES_CONFIGURATION_SET, allowSha1: env.SES_SNS_ALLOW_SHA1 === 'true' }, request.headers.get('x-amz-sns-message-type'));
268
+ (r.status === 200 ? console.log : console.warn)('ses webhook', r.status, r.outcome.slice(0, 200));
269
+ return new Response(r.status === 200 ? 'ok' : 'rejected', { status: r.status });
270
+ }
271
+
203
272
  if (url.pathname === '/v1/send' && request.method === 'POST') {
204
273
  const site = clientSite(env, bearer(request));
205
274
  if (!site) return notFound();
@@ -227,17 +296,42 @@ export default {
227
296
  console.error('HTTP_FROM unreadable, refusing http sends');
228
297
  return json({ status: 'failed', retryable: true, reason: 'config_error' }, 500);
229
298
  }
230
- const allowed = fromTable?.[site];
231
- if (allowed) {
232
- const from = parseAddress(String(req.from ?? ''));
233
- if (!from || !allowed.map((a) => a.toLowerCase()).includes(from.addr)) return json({ status: 'rejected', retryable: false, reason: 'from_not_allowed' }, 400);
234
- } else {
235
- console.warn('http client without HTTP_FROM allowlist', site);
299
+ const fromProblem = checkHttpFrom(fromTable, site, req.from);
300
+ if (fromProblem === 'allowlist_required') {
301
+ // 沒列白名單就拒收:預設不能是「這把鑰匙可以用整個網域任一地址寄」。
302
+ console.warn('http client without HTTP_FROM allowlist, refusing', site);
303
+ return json({ status: 'rejected', retryable: false, reason: 'from_allowlist_required' }, 403);
236
304
  }
305
+ if (fromProblem) return json({ status: 'rejected', retryable: false, reason: 'from_not_allowed' }, 400);
237
306
  const result = await send(deps(env), { ...req, site });
238
307
  return json(result, result.status === 'rejected' ? 400 : result.status === 'failed' ? 502 : 200);
239
308
  }
240
309
 
310
+ // 名單管理入口(帶管理口令):見 list-routes.ts。
311
+ const listResponse = await routeLists(request, env.DB, env.DRILL_TOKEN, env.MARKETING_DOMAIN);
312
+ if (listResponse) return listResponse;
313
+
314
+ // 分析匯出(帶管理口令):見 export.ts。
315
+ const exportResponse = await routeExport(request, env.DB, env.DRILL_TOKEN);
316
+ if (exportResponse) return exportResponse;
317
+
318
+ // 退訂頁與一鍵退訂:GET /u/{券}(確認頁)、POST /u/{券}、POST /u/{券}/resubscribe。
319
+ const unsubResponse = await handleUnsubRequest(env.DB, unsubConfig(env), request);
320
+ if (unsubResponse) return unsubResponse;
321
+
322
+ // 群發管理入口(帶管理口令)。
323
+ if (isBroadcastPath(url.pathname)) {
324
+ if (!sameToken(bearer(request), env.DRILL_TOKEN ?? '') || !env.MARKETING_DOMAIN) return notFound();
325
+ const adminOver = await takeRate(env.DB, '_admin', ADMIN_LIMITS);
326
+ if (adminOver) return new Response('rate limited', { status: 429, headers: { 'retry-after': adminOver === 'day' ? '3600' : '60' } });
327
+ if (request.method !== 'GET') {
328
+ const size = bodySizeProblem(request.headers.get('content-length'), MAX_SEND_BYTES);
329
+ if (size) return json({ ok: false, reason: size === 'missing' ? 'length_required' : 'too_large' }, size === 'missing' ? 411 : 413);
330
+ }
331
+ const config = { ...(jsonVar<Record<string, unknown>>(env.BROADCAST_CONFIG) ?? {}), ...(env.NEWSLETTER_MAX_PER_DAY !== undefined ? { maxPerDay: env.NEWSLETTER_MAX_PER_DAY } : {}) };
332
+ return (await handleBroadcastRequest(request, url, { db: env.DB, domain: env.MARKETING_DOMAIN.toLowerCase(), config: config as never, test: testSendDeps(env) })) ?? notFound();
333
+ }
334
+
241
335
  const postPaths = ['/v1/drill', '/v1/unsuppress'];
242
336
  const tokenPaths = [...postPaths, '/v1/lookup', '/v1/report'];
243
337
  if (tokenPaths.includes(url.pathname) && (request.method === 'POST') === postPaths.includes(url.pathname)) {
@@ -269,6 +363,7 @@ export default {
269
363
 
270
364
  /** Cloudflare 寄信的事後回報(wrangler.jsonc 的 queues.consumers)。處理失敗的那則讓 Queue 重送。 */
271
365
  async queue(batch: MessageBatch<unknown>, env: Env): Promise<void> {
366
+ if (isBroadcastBatch(env, batch.queue)) return broadcastQueue(env, batch.messages);
272
367
  for (const msg of batch.messages) {
273
368
  try {
274
369
  const outcome = await handleCfEvent(env.DB, msg.body);
@@ -281,9 +376,28 @@ export default {
281
376
  }
282
377
  },
283
378
 
379
+ /** 退訂信(Cloudflare Email Routing):主旨帶退訂券就退訂;沒成功的情況都通知人工,見 unsub-wiring.ts。 */
380
+ async email(message: ForwardableEmailMessage, env: Env): Promise<void> {
381
+ await handleEmailMessage(env.DB, env, message);
382
+ },
383
+
284
384
  /** 試跑期每日演習(DAILY_DRILL)。 */
285
385
  async scheduled(_controller: ScheduledController, env: Env): Promise<void> {
386
+ // 群發先跑(煞車不能被後面的雜事拖累):每分鐘放水、踩煞車、寄完對帳;沒設定群發就什麼都不做。
387
+ await broadcastTick(env).catch((e) => console.error('broadcast tick failed', e instanceof Error ? e.message : 'unknown'));
388
+ warnIfNoAlert(env.UNSUB_ALERT_WEBHOOK);
389
+ await flushUnsubAlerts(env).catch((e) => console.error('unsub alert flush failed', e instanceof Error ? e.message : 'unknown'));
286
390
  const out = await dailyDrill(env);
287
391
  if (out.length) console.log('daily drill', out.join(','));
392
+ const days = retentionDays(env.LEDGER_RETENTION_DAYS);
393
+ if (days !== null) {
394
+ try {
395
+ const n = await purgeLedger(env.DB, days);
396
+ if (n.messages || n.webhookEvents) console.log('ledger purge', n.messages, n.webhookEvents);
397
+ } catch (e) {
398
+ console.error('ledger purge failed', e instanceof Error ? e.message : 'unknown');
399
+ }
400
+ }
401
+ await pruneRate(env.DB).catch((e) => console.error('prune rate failed', e instanceof Error ? e.message : 'unknown'));
288
402
  },
289
403
  } satisfies ExportedHandler<Env>;
@@ -0,0 +1,55 @@
1
+ // 名單管理入口(帶管理口令)的路由:PUT /v1/lists/{id}、POST /v1/lists/{id}/import、POST /v1/lists/{id}/segments、
2
+ // PUT/GET /v1/lists/{id}/welcome(歡迎信,見 src/welcome.ts)。
3
+ // 從 index.ts 抽出來,測試不必載入 cloudflare:workers。路徑不是這三個=回 null,交給後面的路由。
4
+
5
+ import { bodySizeProblem, takeRate, type Db } from './core.ts';
6
+ import { bearer, json, notFound, sameToken } from './http.ts';
7
+ import { importMembers, setSegments, upsertList, type ImportOptions, type ImportRow, type ListDb, type SegmentInput } from './lists.ts';
8
+ import { getWelcome, saveWelcome, type WelcomeInput } from './welcome.ts';
9
+
10
+ /** 管理口令入口合計上限:口令外洩時,別人拿它也做不了太多事。 */
11
+ export const ADMIN_LIMITS = { perMinute: 20, perDay: 200 };
12
+ /** 名單管理入口的請求內文上限:匯入 2,000 筆、分群 5,000 筆都放得下。 */
13
+ export const MAX_LIST_BYTES = 1_500_000;
14
+
15
+ const LIST_PATH = /^\/v1\/lists\/([a-z0-9][a-z0-9-]{0,39})(\/import|\/segments|\/welcome)?$/;
16
+
17
+ export async function routeLists(request: Request, db: ListDb & Db, adminToken: string | undefined, marketingDomain?: string): Promise<Response | null> {
18
+ const url = new URL(request.url);
19
+ const m = LIST_PATH.exec(url.pathname);
20
+ if (!m) return null;
21
+ const wanted = m[2] === '/welcome' ? ['PUT', 'GET'] : m[2] ? ['POST'] : ['PUT'];
22
+ if (!wanted.includes(request.method)) return notFound();
23
+ if (!sameToken(bearer(request), adminToken ?? '')) return notFound();
24
+ const adminOver = await takeRate(db, '_admin', ADMIN_LIMITS);
25
+ if (adminOver) return new Response('rate limited', { status: 429, headers: { 'retry-after': adminOver === 'day' ? '3600' : '60' } });
26
+ if (m[2] === '/welcome' && request.method === 'GET') {
27
+ const w = await getWelcome(db, m[1]);
28
+ return w
29
+ ? json({ ok: true, list: w.list_id, subject: w.subject, from: w.from_addr, replyTo: w.reply_to, webUrl: w.web_url, enabled: Boolean(w.enabled), contentHash: w.content_hash, updatedAt: w.updated_at, html: w.html, text: w.text })
30
+ : json({ ok: false, reason: 'not_found' }, 404);
31
+ }
32
+ const size = bodySizeProblem(request.headers.get('content-length'), MAX_LIST_BYTES);
33
+ if (size) return json({ ok: false, reason: size === 'missing' ? 'length_required' : 'too_large' }, size === 'missing' ? 411 : 413);
34
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
35
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return json({ ok: false, reason: 'bad_json' }, 400);
36
+ const id = m[1];
37
+ if (m[2] === '/welcome') {
38
+ if (!marketingDomain) return json({ ok: false, reason: 'marketing_domain_not_set' }, 400);
39
+ const r = await saveWelcome(db, id, body as unknown as WelcomeInput, { marketingDomain });
40
+ return json(r, r.ok ? 200 : 400);
41
+ }
42
+ if (!m[2]) {
43
+ const r = await upsertList(db, { id, name: body.name as string, fromAddr: body.fromAddr as string | undefined, replyTo: body.replyTo as string | undefined, welcomeTemplate: body.welcomeTemplate as string | undefined });
44
+ return json(r, r.ok ? 200 : 400);
45
+ }
46
+ if (m[2] === '/segments') {
47
+ const r = await setSegments(db, id, body.items as SegmentInput[]);
48
+ return json(r, r.ok ? 200 : r.reason === 'too_many' ? 413 : 400);
49
+ }
50
+ const expected = body.expected;
51
+ if (expected !== undefined && (expected === null || typeof expected !== 'object' || Array.isArray(expected))) return json({ ok: false, reason: 'bad_body' }, 400);
52
+ const opts: ImportOptions = { importedFrom: body.importedFrom as string, dryRun: body.dryRun === true, expected: expected as ImportOptions['expected'] };
53
+ const r = await importMembers(db, id, body.rows as ImportRow[], opts);
54
+ return json(r, r.ok ? 200 : r.reason === 'too_many' ? 413 : 400);
55
+ }