@joelincc/mailroom 0.1.0 → 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.
- package/README.md +47 -5
- package/SECURITY.md +1 -1
- package/bin/mailroom.mjs +26 -0
- package/dist/broadcast/config.js +79 -0
- package/dist/broadcast/explain.js +50 -0
- package/dist/cli/args.js +29 -0
- package/dist/cli/errors.js +31 -0
- package/dist/cli/main.js +475 -0
- package/dist/compose/clicks.js +29 -0
- package/dist/compose/compose.js +224 -0
- package/dist/compose/index.js +8 -0
- package/dist/compose/markdown.js +637 -0
- package/dist/compose/personalize.js +123 -0
- package/dist/compose/preflight.js +251 -0
- package/dist/compose/preview.js +41 -0
- package/dist/compose/render.js +136 -0
- package/dist/compose/template.js +118 -0
- package/docs/broadcast.md +199 -0
- package/docs/composing.md +135 -0
- package/docs/desk-commands.md +52 -0
- package/docs/export.md +51 -0
- package/docs/lists.md +66 -0
- package/docs/security-model.md +4 -4
- package/docs/ses.md +116 -0
- package/docs/unsubscribe.md +117 -0
- package/migrations/0004_last_error.sql +2 -0
- package/migrations/0005_lists.sql +41 -0
- package/migrations/0006_broadcast.sql +154 -0
- package/migrations/0007_unsubscribe.sql +12 -0
- package/package.json +19 -3
- package/src/alert.ts +123 -0
- package/src/aws-sigv4.ts +100 -0
- package/src/broadcast/audience.ts +96 -0
- package/src/broadcast/campaigns.ts +339 -0
- package/src/broadcast/config.ts +136 -0
- package/src/broadcast/dispatch.ts +766 -0
- package/src/broadcast/events.ts +107 -0
- package/src/broadcast/explain.ts +73 -0
- package/src/broadcast/freeze.ts +93 -0
- package/src/broadcast/index.ts +21 -0
- package/src/broadcast/postman.ts +229 -0
- package/src/broadcast/reconcile.ts +120 -0
- package/src/broadcast/routes.ts +181 -0
- package/src/broadcast/ses.ts +181 -0
- package/src/broadcast/stats.ts +59 -0
- package/src/broadcast/status.ts +60 -0
- package/src/broadcast/test-send.ts +88 -0
- package/src/broadcast/warmup.ts +150 -0
- package/src/broadcast/worker.ts +177 -0
- package/src/cf-events.ts +4 -3
- package/src/cli/args.ts +27 -0
- package/src/cli/errors.ts +33 -0
- package/src/cli/main.ts +466 -0
- package/src/compose/clicks.ts +45 -0
- package/src/compose/compose.ts +257 -0
- package/src/compose/index.ts +8 -0
- package/src/compose/markdown.ts +624 -0
- package/src/compose/personalize.ts +130 -0
- package/src/compose/preflight.ts +250 -0
- package/src/compose/preview.ts +58 -0
- package/src/compose/render.ts +153 -0
- package/src/compose/template.ts +197 -0
- package/src/core.ts +42 -1
- package/src/export.ts +184 -0
- package/src/feedback.ts +111 -0
- package/src/http.ts +17 -0
- package/src/index.ts +120 -31
- package/src/list-routes.ts +42 -0
- package/src/lists.ts +370 -0
- package/src/ses-events.ts +426 -0
- package/src/unsub-wiring.ts +64 -0
- package/src/unsub.ts +499 -0
- package/src/webhook.ts +5 -3
- package/wrangler.example.jsonc +16 -2
package/src/index.ts
CHANGED
|
@@ -3,19 +3,32 @@
|
|
|
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
|
+
// - 名單管理(帶管理口令):PUT /v1/lists/{id}、POST /v1/lists/{id}/import、POST /v1/lists/{id}/segments。
|
|
11
|
+
// - 群發(帶管理口令):/v1/campaigns/*、/v1/throttle、/v1/warmup/*、/v1/broadcast/*(見 src/broadcast/routes.ts);Queue mailroom-broadcast;排程每分鐘放水。
|
|
9
12
|
// - Queue:Cloudflare 寄信的事後回報(cf-events.ts)。
|
|
10
|
-
// - 排程:有設 cron
|
|
13
|
+
// - 排程:有設 cron 時,每次順手清舊計數窗;有設 DAILY_DRILL 時每天最多寄一輪演習信(過了 until 自動停);有設 LEDGER_RETENTION_DAYS 時清過期帳本列。
|
|
11
14
|
|
|
12
15
|
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';
|
|
16
|
+
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
17
|
import { handleCfEvent } from './cf-events.ts';
|
|
18
|
+
import { listMembers, listStatus, listSubscribe, listUnsubscribe, type SubscribeInput, type UnsubscribeInput } from './lists.ts';
|
|
19
|
+
import { bearer, json, notFound, sameToken } from './http.ts';
|
|
20
|
+
import { ADMIN_LIMITS, routeLists } from './list-routes.ts';
|
|
21
|
+
import { routeExport } from './export.ts';
|
|
22
|
+
import { handleUnsubRequest, unsubscribeLinksForEmail, unsubSecrets, type UnsubLinks } from './unsub.ts';
|
|
23
|
+
import { flushUnsubAlerts, handleEmailMessage, unsubConfig } from './unsub-wiring.ts';
|
|
24
|
+
import { warnIfNoAlert } from './alert.ts';
|
|
15
25
|
import { MAIL_ROUTES, type CloudflareSender, type MailRoute } from './transport.ts';
|
|
16
26
|
import { handleEvent, verifySignature } from './webhook.ts';
|
|
27
|
+
import { handleSesWebhook } from './ses-events.ts';
|
|
28
|
+
import { handleBroadcastRequest, isBroadcastPath } from './broadcast/routes.ts';
|
|
29
|
+
import { broadcastQueue, broadcastTick, isBroadcastBatch, testSendDeps, type BroadcastEnv } from './broadcast/worker.ts';
|
|
17
30
|
|
|
18
|
-
export interface Env {
|
|
31
|
+
export interface Env extends BroadcastEnv {
|
|
19
32
|
DB: D1Database;
|
|
20
33
|
/** 第一層(一定要到)的寄件網域,例 notify.example.com。 */
|
|
21
34
|
FROM_DOMAIN: string;
|
|
@@ -35,13 +48,33 @@ export interface Env {
|
|
|
35
48
|
HTTP_RATE_PER_MIN?: string | number;
|
|
36
49
|
/** 走公開網址的站每天最多幾次請求(預設 2000,UTC 日)。 */
|
|
37
50
|
HTTP_DAILY_LIMIT?: string | number;
|
|
38
|
-
/** 走公開網址的站准用的寄件地址(JSON:{ "站": ["app@notify.example.com"] }
|
|
51
|
+
/** 走公開網址的站准用的寄件地址(JSON:{ "站": ["app@notify.example.com"] })。每個 HTTP client 都必須列;沒列的站一律拒收(from_allowlist_required)。 */
|
|
39
52
|
HTTP_FROM?: Record<string, string[]> | string;
|
|
53
|
+
/** 帳本保存天數(正整數)。設了之後,排程(cron)每次會順手清掉超過天數的 messages 與 webhook_events;沒設=不自動清。 */
|
|
54
|
+
LEDGER_RETENTION_DAYS?: string | number;
|
|
40
55
|
RESEND_API_KEY?: string;
|
|
41
56
|
SMTP2GO_API_KEY?: string;
|
|
42
57
|
RESEND_WEBHOOK_SECRET?: string;
|
|
43
58
|
/** 管理口令(演習、查帳、統計、解除拒收);沒設=這些路徑一律 404。 */
|
|
44
59
|
DRILL_TOKEN?: string;
|
|
60
|
+
/** 退訂券簽章鑰匙(Secret,至少 16 字元)。沒設=退訂端點回 503。 */
|
|
61
|
+
UNSUB_TOKEN_SECRET?: string;
|
|
62
|
+
/** 換鑰匙過渡期:舊鑰匙(逗號分隔),只用來驗證、不簽新券。過了過渡期就拿掉。 */
|
|
63
|
+
UNSUB_TOKEN_SECRET_PREVIOUS?: string;
|
|
64
|
+
/** 退訂網址的開頭(https,不含結尾斜線),例 https://u.example.com。 */
|
|
65
|
+
UNSUB_BASE_URL?: string;
|
|
66
|
+
/** 收退訂信的地址(Email Routing 轉進本 Worker 的 email()),例 unsubscribe@mail.example.com。 */
|
|
67
|
+
UNSUB_MAILTO?: string;
|
|
68
|
+
/** 讀者退訂沒成功時的告警 webhook(https,POST JSON:event、from、subject、token、at、text)。沒設=只寫 log,並警告。見 docs/unsubscribe.md。 */
|
|
69
|
+
UNSUB_ALERT_WEBHOOK?: string;
|
|
70
|
+
/** 選填:告警 webhook 的 Bearer 口令(Secret)。 */
|
|
71
|
+
UNSUB_ALERT_TOKEN?: string;
|
|
72
|
+
/** 退訂頁文字(JSON 物件,只寫想改的欄位,見 docs/unsubscribe.md)。 */
|
|
73
|
+
UNSUB_PAGE?: string | Record<string, unknown>;
|
|
74
|
+
/** SES 事件入口准收的 SNS 主題 ARN(逗號分隔)。沒設(或沒設 SES_REGION、SES_CONFIGURATION_SET)=POST /webhooks/ses 一律 404。 */
|
|
75
|
+
SES_SNS_TOPIC_ARNS?: string;
|
|
76
|
+
/** "true"=也收 SNS SignatureVersion 1(SHA1)。預設只收 2,主題請設 SignatureVersion=2。 */
|
|
77
|
+
SES_SNS_ALLOW_SHA1?: string;
|
|
45
78
|
[key: `HTTP_KEY_${string}`]: string | undefined;
|
|
46
79
|
}
|
|
47
80
|
|
|
@@ -49,8 +82,6 @@ export interface Env {
|
|
|
49
82
|
const DEFAULT_HTTP_RATE_PER_MIN = 60;
|
|
50
83
|
/** 公開網址入口每站每天預設上限。 */
|
|
51
84
|
const DEFAULT_HTTP_DAILY_LIMIT = 2000;
|
|
52
|
-
/** 管理口令入口(演習、查帳、統計、解除拒收)合計上限:口令外洩時,別人拿它也寄不了多少演習信。 */
|
|
53
|
-
const ADMIN_LIMITS = { perMinute: 20, perDay: 200 };
|
|
54
85
|
/** 請求內文上限(位元組,一定要帶 content-length):寄信 3 MB(內文上限 html 40 萬+text 20 萬字元,中文 UTF-8 一字 3 bytes)、webhook 256 KB。 */
|
|
55
86
|
const MAX_SEND_BYTES = 3_000_000;
|
|
56
87
|
const MAX_WEBHOOK_BYTES = 256_000;
|
|
@@ -151,18 +182,24 @@ export class Mailroom extends WorkerEntrypoint<Env> {
|
|
|
151
182
|
drill(site: string, input: DrillInput) {
|
|
152
183
|
return drill(this.env, site, input);
|
|
153
184
|
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
185
|
+
// 電子報名單(內線):見 docs/lists.md。
|
|
186
|
+
listSubscribe(input: SubscribeInput) {
|
|
187
|
+
return listSubscribe(this.env.DB, input);
|
|
188
|
+
}
|
|
189
|
+
listUnsubscribe(input: UnsubscribeInput) {
|
|
190
|
+
return listUnsubscribe(this.env.DB, input);
|
|
191
|
+
}
|
|
192
|
+
listStatus(input: { list: string; email: string }) {
|
|
193
|
+
return listStatus(this.env.DB, input);
|
|
194
|
+
}
|
|
195
|
+
listMembers(input: { list: string; status?: 'subscribed' | 'unsubscribed'; cursor?: string | null; limit?: number }) {
|
|
196
|
+
return listMembers(this.env.DB, input);
|
|
197
|
+
}
|
|
198
|
+
/** 某人的退訂連結與兩個一鍵退訂標頭(url/mailto 對應 compose 的 unsubscribe_url/unsubscribe_mailto);不是成員=null。 */
|
|
199
|
+
async unsubscribeLinks(input: { list: string; email: string; campaign?: string | null }): Promise<UnsubLinks | null> {
|
|
200
|
+
const cfg = unsubConfig(this.env);
|
|
201
|
+
return unsubscribeLinksForEmail(this.env.DB, cfg.secrets, { baseUrl: this.env.UNSUB_BASE_URL ?? '', mailtoAddress: this.env.UNSUB_MAILTO }, input);
|
|
202
|
+
}
|
|
166
203
|
}
|
|
167
204
|
|
|
168
205
|
/** 帶鑰匙的站:鑰匙決定是哪個站,站名不聽請求本身的。 */
|
|
@@ -173,15 +210,11 @@ function clientSite(env: Env, token: string): string | null {
|
|
|
173
210
|
return null;
|
|
174
211
|
}
|
|
175
212
|
|
|
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
213
|
/** 公開網址查帳只回狀態欄位,不回收件人、寄件人、主旨(口令外洩時不會變成查收件人的工具)。 */
|
|
181
214
|
function publicRow(row: MessageRow | null) {
|
|
182
215
|
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 };
|
|
216
|
+
const { id, stream, tier, site, dedupe_key, kind, status, route, attempts, last_event, error, last_error, created_at, updated_at, sent_at } = row;
|
|
217
|
+
return { id, stream, tier, site, dedupe_key, kind, status, route, attempts, last_event, error, last_error, created_at, updated_at, sent_at };
|
|
185
218
|
}
|
|
186
219
|
|
|
187
220
|
export default {
|
|
@@ -200,6 +233,17 @@ export default {
|
|
|
200
233
|
return json({ ok: true });
|
|
201
234
|
}
|
|
202
235
|
|
|
236
|
+
if (url.pathname === '/webhooks/ses' && request.method === 'POST') {
|
|
237
|
+
const topicArns = (env.SES_SNS_TOPIC_ARNS ?? '').split(',').map((s) => s.trim()).filter(Boolean);
|
|
238
|
+
// 設定組也要有:沒有就無法只收自己的事件(同一個主題裡別的寄信會混進來),一律不收。
|
|
239
|
+
if (!topicArns.length || !env.SES_REGION || !env.SES_CONFIGURATION_SET) return notFound();
|
|
240
|
+
const size = bodySizeProblem(request.headers.get('content-length'), MAX_WEBHOOK_BYTES);
|
|
241
|
+
if (size) return new Response(size, { status: size === 'missing' ? 411 : 413 });
|
|
242
|
+
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'));
|
|
243
|
+
(r.status === 200 ? console.log : console.warn)('ses webhook', r.status, r.outcome.slice(0, 200));
|
|
244
|
+
return new Response(r.status === 200 ? 'ok' : 'rejected', { status: r.status });
|
|
245
|
+
}
|
|
246
|
+
|
|
203
247
|
if (url.pathname === '/v1/send' && request.method === 'POST') {
|
|
204
248
|
const site = clientSite(env, bearer(request));
|
|
205
249
|
if (!site) return notFound();
|
|
@@ -227,17 +271,42 @@ export default {
|
|
|
227
271
|
console.error('HTTP_FROM unreadable, refusing http sends');
|
|
228
272
|
return json({ status: 'failed', retryable: true, reason: 'config_error' }, 500);
|
|
229
273
|
}
|
|
230
|
-
const
|
|
231
|
-
if (
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
console.warn('http client without HTTP_FROM allowlist', site);
|
|
274
|
+
const fromProblem = checkHttpFrom(fromTable, site, req.from);
|
|
275
|
+
if (fromProblem === 'allowlist_required') {
|
|
276
|
+
// 沒列白名單就拒收:預設不能是「這把鑰匙可以用整個網域任一地址寄」。
|
|
277
|
+
console.warn('http client without HTTP_FROM allowlist, refusing', site);
|
|
278
|
+
return json({ status: 'rejected', retryable: false, reason: 'from_allowlist_required' }, 403);
|
|
236
279
|
}
|
|
280
|
+
if (fromProblem) return json({ status: 'rejected', retryable: false, reason: 'from_not_allowed' }, 400);
|
|
237
281
|
const result = await send(deps(env), { ...req, site });
|
|
238
282
|
return json(result, result.status === 'rejected' ? 400 : result.status === 'failed' ? 502 : 200);
|
|
239
283
|
}
|
|
240
284
|
|
|
285
|
+
// 名單管理入口(帶管理口令):見 list-routes.ts。
|
|
286
|
+
const listResponse = await routeLists(request, env.DB, env.DRILL_TOKEN);
|
|
287
|
+
if (listResponse) return listResponse;
|
|
288
|
+
|
|
289
|
+
// 分析匯出(帶管理口令):見 export.ts。
|
|
290
|
+
const exportResponse = await routeExport(request, env.DB, env.DRILL_TOKEN);
|
|
291
|
+
if (exportResponse) return exportResponse;
|
|
292
|
+
|
|
293
|
+
// 退訂頁與一鍵退訂:GET /u/{券}(確認頁)、POST /u/{券}、POST /u/{券}/resubscribe。
|
|
294
|
+
const unsubResponse = await handleUnsubRequest(env.DB, unsubConfig(env), request);
|
|
295
|
+
if (unsubResponse) return unsubResponse;
|
|
296
|
+
|
|
297
|
+
// 群發管理入口(帶管理口令)。
|
|
298
|
+
if (isBroadcastPath(url.pathname)) {
|
|
299
|
+
if (!sameToken(bearer(request), env.DRILL_TOKEN ?? '') || !env.MARKETING_DOMAIN) return notFound();
|
|
300
|
+
const adminOver = await takeRate(env.DB, '_admin', ADMIN_LIMITS);
|
|
301
|
+
if (adminOver) return new Response('rate limited', { status: 429, headers: { 'retry-after': adminOver === 'day' ? '3600' : '60' } });
|
|
302
|
+
if (request.method !== 'GET') {
|
|
303
|
+
const size = bodySizeProblem(request.headers.get('content-length'), MAX_SEND_BYTES);
|
|
304
|
+
if (size) return json({ ok: false, reason: size === 'missing' ? 'length_required' : 'too_large' }, size === 'missing' ? 411 : 413);
|
|
305
|
+
}
|
|
306
|
+
const config = { ...(jsonVar<Record<string, unknown>>(env.BROADCAST_CONFIG) ?? {}), ...(env.NEWSLETTER_MAX_PER_DAY !== undefined ? { maxPerDay: env.NEWSLETTER_MAX_PER_DAY } : {}) };
|
|
307
|
+
return (await handleBroadcastRequest(request, url, { db: env.DB, domain: env.MARKETING_DOMAIN.toLowerCase(), config: config as never, test: testSendDeps(env) })) ?? notFound();
|
|
308
|
+
}
|
|
309
|
+
|
|
241
310
|
const postPaths = ['/v1/drill', '/v1/unsuppress'];
|
|
242
311
|
const tokenPaths = [...postPaths, '/v1/lookup', '/v1/report'];
|
|
243
312
|
if (tokenPaths.includes(url.pathname) && (request.method === 'POST') === postPaths.includes(url.pathname)) {
|
|
@@ -269,6 +338,7 @@ export default {
|
|
|
269
338
|
|
|
270
339
|
/** Cloudflare 寄信的事後回報(wrangler.jsonc 的 queues.consumers)。處理失敗的那則讓 Queue 重送。 */
|
|
271
340
|
async queue(batch: MessageBatch<unknown>, env: Env): Promise<void> {
|
|
341
|
+
if (isBroadcastBatch(env, batch.queue)) return broadcastQueue(env, batch.messages);
|
|
272
342
|
for (const msg of batch.messages) {
|
|
273
343
|
try {
|
|
274
344
|
const outcome = await handleCfEvent(env.DB, msg.body);
|
|
@@ -281,9 +351,28 @@ export default {
|
|
|
281
351
|
}
|
|
282
352
|
},
|
|
283
353
|
|
|
354
|
+
/** 退訂信(Cloudflare Email Routing):主旨帶退訂券就退訂;沒成功的情況都通知人工,見 unsub-wiring.ts。 */
|
|
355
|
+
async email(message: ForwardableEmailMessage, env: Env): Promise<void> {
|
|
356
|
+
await handleEmailMessage(env.DB, env, message);
|
|
357
|
+
},
|
|
358
|
+
|
|
284
359
|
/** 試跑期每日演習(DAILY_DRILL)。 */
|
|
285
360
|
async scheduled(_controller: ScheduledController, env: Env): Promise<void> {
|
|
361
|
+
// 群發先跑(煞車不能被後面的雜事拖累):每分鐘放水、踩煞車、寄完對帳;沒設定群發就什麼都不做。
|
|
362
|
+
await broadcastTick(env).catch((e) => console.error('broadcast tick failed', e instanceof Error ? e.message : 'unknown'));
|
|
363
|
+
warnIfNoAlert(env.UNSUB_ALERT_WEBHOOK);
|
|
364
|
+
await flushUnsubAlerts(env).catch((e) => console.error('unsub alert flush failed', e instanceof Error ? e.message : 'unknown'));
|
|
286
365
|
const out = await dailyDrill(env);
|
|
287
366
|
if (out.length) console.log('daily drill', out.join(','));
|
|
367
|
+
const days = retentionDays(env.LEDGER_RETENTION_DAYS);
|
|
368
|
+
if (days !== null) {
|
|
369
|
+
try {
|
|
370
|
+
const n = await purgeLedger(env.DB, days);
|
|
371
|
+
if (n.messages || n.webhookEvents) console.log('ledger purge', n.messages, n.webhookEvents);
|
|
372
|
+
} catch (e) {
|
|
373
|
+
console.error('ledger purge failed', e instanceof Error ? e.message : 'unknown');
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
await pruneRate(env.DB).catch((e) => console.error('prune rate failed', e instanceof Error ? e.message : 'unknown'));
|
|
288
377
|
},
|
|
289
378
|
} satisfies ExportedHandler<Env>;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// 名單管理入口(帶管理口令)的路由:PUT /v1/lists/{id}、POST /v1/lists/{id}/import、POST /v1/lists/{id}/segments。
|
|
2
|
+
// 從 index.ts 抽出來,測試不必載入 cloudflare:workers。路徑不是這三個=回 null,交給後面的路由。
|
|
3
|
+
|
|
4
|
+
import { bodySizeProblem, takeRate, type Db } from './core.ts';
|
|
5
|
+
import { bearer, json, notFound, sameToken } from './http.ts';
|
|
6
|
+
import { importMembers, setSegments, upsertList, type ImportOptions, type ImportRow, type ListDb, type SegmentInput } from './lists.ts';
|
|
7
|
+
|
|
8
|
+
/** 管理口令入口合計上限:口令外洩時,別人拿它也做不了太多事。 */
|
|
9
|
+
export const ADMIN_LIMITS = { perMinute: 20, perDay: 200 };
|
|
10
|
+
/** 名單管理入口的請求內文上限:匯入 2,000 筆、分群 5,000 筆都放得下。 */
|
|
11
|
+
export const MAX_LIST_BYTES = 1_500_000;
|
|
12
|
+
|
|
13
|
+
const LIST_PATH = /^\/v1\/lists\/([a-z0-9][a-z0-9-]{0,39})(\/import|\/segments)?$/;
|
|
14
|
+
|
|
15
|
+
export async function routeLists(request: Request, db: ListDb & Db, adminToken: string | undefined): Promise<Response | null> {
|
|
16
|
+
const url = new URL(request.url);
|
|
17
|
+
const m = LIST_PATH.exec(url.pathname);
|
|
18
|
+
if (!m) return null;
|
|
19
|
+
const wanted = m[2] ? 'POST' : 'PUT';
|
|
20
|
+
if (request.method !== wanted) return notFound();
|
|
21
|
+
if (!sameToken(bearer(request), adminToken ?? '')) return notFound();
|
|
22
|
+
const adminOver = await takeRate(db, '_admin', ADMIN_LIMITS);
|
|
23
|
+
if (adminOver) return new Response('rate limited', { status: 429, headers: { 'retry-after': adminOver === 'day' ? '3600' : '60' } });
|
|
24
|
+
const size = bodySizeProblem(request.headers.get('content-length'), MAX_LIST_BYTES);
|
|
25
|
+
if (size) return json({ ok: false, reason: size === 'missing' ? 'length_required' : 'too_large' }, size === 'missing' ? 411 : 413);
|
|
26
|
+
const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
|
|
27
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) return json({ ok: false, reason: 'bad_json' }, 400);
|
|
28
|
+
const id = m[1];
|
|
29
|
+
if (!m[2]) {
|
|
30
|
+
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 });
|
|
31
|
+
return json(r, r.ok ? 200 : 400);
|
|
32
|
+
}
|
|
33
|
+
if (m[2] === '/segments') {
|
|
34
|
+
const r = await setSegments(db, id, body.items as SegmentInput[]);
|
|
35
|
+
return json(r, r.ok ? 200 : r.reason === 'too_many' ? 413 : 400);
|
|
36
|
+
}
|
|
37
|
+
const expected = body.expected;
|
|
38
|
+
if (expected !== undefined && (expected === null || typeof expected !== 'object' || Array.isArray(expected))) return json({ ok: false, reason: 'bad_body' }, 400);
|
|
39
|
+
const opts: ImportOptions = { importedFrom: body.importedFrom as string, dryRun: body.dryRun === true, expected: expected as ImportOptions['expected'] };
|
|
40
|
+
const r = await importMembers(db, id, body.rows as ImportRow[], opts);
|
|
41
|
+
return json(r, r.ok ? 200 : r.reason === 'too_many' ? 413 : 400);
|
|
42
|
+
}
|