@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.
- package/LICENSE +21 -0
- package/README.md +207 -2
- package/SECURITY.md +11 -0
- 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 +82 -0
- package/docs/ses.md +116 -0
- package/docs/unsubscribe.md +117 -0
- package/migrations/0001_init.sql +42 -0
- package/migrations/0002_tier.sql +4 -0
- package/migrations/0003_rate.sql +9 -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 +64 -4
- 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 +84 -0
- 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 +328 -0
- package/src/export.ts +184 -0
- package/src/feedback.ts +111 -0
- package/src/http.ts +17 -0
- package/src/index.ts +378 -0
- package/src/list-routes.ts +42 -0
- package/src/lists.ts +370 -0
- package/src/ses-events.ts +426 -0
- package/src/transport.ts +193 -0
- package/src/unsub-wiring.ts +64 -0
- package/src/unsub.ts +499 -0
- package/src/webhook.ts +101 -0
- package/wrangler.example.jsonc +56 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
// 郵務室(mailroom):多個站共用的寄信 Worker。運作說明見 README。
|
|
2
|
+
//
|
|
3
|
+
// 兩個入口:
|
|
4
|
+
// - 內線(service binding):同一個 Cloudflare 帳號的站在 wrangler.jsonc 加
|
|
5
|
+
// { "binding": "MAILROOM", "service": "mailroom", "entrypoint": "Mailroom" },呼叫 env.MAILROOM.send({...})。
|
|
6
|
+
// - 公開網址(workers.dev):Resend 事後回報 POST /webhooks/resend;SES 事後回報(SNS)POST /webhooks/ses;
|
|
7
|
+
// 別的 Cloudflare 帳號的站帶自己的鑰匙 POST /v1/send;演習 POST /v1/drill;寄信統計 GET /v1/report;
|
|
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;排程每分鐘放水。
|
|
12
|
+
// - Queue:Cloudflare 寄信的事後回報(cf-events.ts)。
|
|
13
|
+
// - 排程:有設 cron 時,每次順手清舊計數窗;有設 DAILY_DRILL 時每天最多寄一輪演習信(過了 until 自動停);有設 LEDGER_RETENTION_DAYS 時清過期帳本列。
|
|
14
|
+
|
|
15
|
+
import { WorkerEntrypoint } from 'cloudflare:workers';
|
|
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';
|
|
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';
|
|
25
|
+
import { MAIL_ROUTES, type CloudflareSender, type MailRoute } from './transport.ts';
|
|
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';
|
|
30
|
+
|
|
31
|
+
export interface Env extends BroadcastEnv {
|
|
32
|
+
DB: D1Database;
|
|
33
|
+
/** 第一層(一定要到)的寄件網域,例 notify.example.com。 */
|
|
34
|
+
FROM_DOMAIN: string;
|
|
35
|
+
/** 第二層(服務提醒)的寄件網域,例 remind.example.com。沒設=第二層不收。 */
|
|
36
|
+
REMIND_DOMAIN?: string;
|
|
37
|
+
/** 郵差順序表(JSON 物件,鍵=`站:層`/`*:層`)。改這裡+部署=換郵差順序/退回原狀。 */
|
|
38
|
+
ROUTES?: RouteTable | string;
|
|
39
|
+
/** Cloudflare 寄信綁定(send_email),只准第二層的寄件地址。 */
|
|
40
|
+
EMAIL?: SendEmail;
|
|
41
|
+
/** 第二層專用的 Resend 鑰匙(只能從第二層網域寄);沒放=第二層備援跳過 Resend。 */
|
|
42
|
+
RESEND_API_KEY_REMIND?: string;
|
|
43
|
+
/** 每日演習:{ until: 'YYYY-MM-DD'(含當天;日期照 utcOffsetHours,預設 UTC), to: [...], site, tier, routes?, utcOffsetHours? }。 */
|
|
44
|
+
DAILY_DRILL?: DailyDrill | string;
|
|
45
|
+
/** 走公開網址寄信的站(逗號分隔,例 "shop");每站一把 Secret:HTTP_KEY_<站名大寫>。 */
|
|
46
|
+
HTTP_CLIENTS?: string;
|
|
47
|
+
/** 走公開網址的站每分鐘最多幾次請求(預設 60;鑰匙外洩時的上限)。 */
|
|
48
|
+
HTTP_RATE_PER_MIN?: string | number;
|
|
49
|
+
/** 走公開網址的站每天最多幾次請求(預設 2000,UTC 日)。 */
|
|
50
|
+
HTTP_DAILY_LIMIT?: string | number;
|
|
51
|
+
/** 走公開網址的站准用的寄件地址(JSON:{ "站": ["app@notify.example.com"] })。每個 HTTP client 都必須列;沒列的站一律拒收(from_allowlist_required)。 */
|
|
52
|
+
HTTP_FROM?: Record<string, string[]> | string;
|
|
53
|
+
/** 帳本保存天數(正整數)。設了之後,排程(cron)每次會順手清掉超過天數的 messages 與 webhook_events;沒設=不自動清。 */
|
|
54
|
+
LEDGER_RETENTION_DAYS?: string | number;
|
|
55
|
+
RESEND_API_KEY?: string;
|
|
56
|
+
SMTP2GO_API_KEY?: string;
|
|
57
|
+
RESEND_WEBHOOK_SECRET?: string;
|
|
58
|
+
/** 管理口令(演習、查帳、統計、解除拒收);沒設=這些路徑一律 404。 */
|
|
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;
|
|
78
|
+
[key: `HTTP_KEY_${string}`]: string | undefined;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 公開網址入口每站每分鐘預設上限。 */
|
|
82
|
+
const DEFAULT_HTTP_RATE_PER_MIN = 60;
|
|
83
|
+
/** 公開網址入口每站每天預設上限。 */
|
|
84
|
+
const DEFAULT_HTTP_DAILY_LIMIT = 2000;
|
|
85
|
+
/** 請求內文上限(位元組,一定要帶 content-length):寄信 3 MB(內文上限 html 40 萬+text 20 萬字元,中文 UTF-8 一字 3 bytes)、webhook 256 KB。 */
|
|
86
|
+
const MAX_SEND_BYTES = 3_000_000;
|
|
87
|
+
const MAX_WEBHOOK_BYTES = 256_000;
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
interface DailyDrill { until: string; to: string[]; site?: string; tier?: Tier; routes?: MailRoute[]; utcOffsetHours?: number }
|
|
91
|
+
|
|
92
|
+
function jsonVar<T>(v: T | string | undefined): T | undefined {
|
|
93
|
+
if (typeof v !== 'string') return v;
|
|
94
|
+
try {
|
|
95
|
+
return JSON.parse(v) as T;
|
|
96
|
+
} catch {
|
|
97
|
+
console.error('bad json var');
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function deps(env: Env): CoreDeps {
|
|
103
|
+
const base = { resend: env.RESEND_API_KEY, smtp2go: env.SMTP2GO_API_KEY };
|
|
104
|
+
return {
|
|
105
|
+
db: env.DB,
|
|
106
|
+
keys: base,
|
|
107
|
+
fromDomain: env.FROM_DOMAIN,
|
|
108
|
+
tierDomains: env.REMIND_DOMAIN ? { remind: env.REMIND_DOMAIN } : {},
|
|
109
|
+
// 第二層:Resend 用自己的鑰匙(Resend 鑰匙綁網域);Cloudflare 綁定只給第二層。
|
|
110
|
+
tierKeys: { remind: { resend: env.RESEND_API_KEY_REMIND, smtp2go: env.SMTP2GO_API_KEY, cloudflare: env.EMAIL as unknown as CloudflareSender | undefined } },
|
|
111
|
+
routes: jsonVar<RouteTable>(env.ROUTES),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export type DrillMode = 'fallback' | 'normal';
|
|
116
|
+
export interface DrillInput { to: string; mode?: DrillMode; key?: string; tier?: Tier; only?: MailRoute }
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* 演習信:fallback 故意給錯的 Resend 鑰匙(Resend 真的回 401)→ 應改走下一個郵差;normal 走正式路徑。
|
|
120
|
+
* tier=哪一層(寄件網域跟著換);only=只走這一個郵差(看單一郵差能不能寄、簽章對不對)。
|
|
121
|
+
*/
|
|
122
|
+
async function drill(env: Env, site: string, input: DrillInput): Promise<SendResult & { row: MessageRow | null }> {
|
|
123
|
+
const mode: DrillMode = input.mode === 'normal' ? 'normal' : 'fallback';
|
|
124
|
+
const tier: Tier = input.tier && TIERS.includes(input.tier) ? input.tier : 'notify';
|
|
125
|
+
const only = input.only && MAIL_ROUTES.includes(input.only) ? input.only : undefined;
|
|
126
|
+
const domain = tier === 'remind' ? env.REMIND_DOMAIN : env.FROM_DOMAIN;
|
|
127
|
+
const stamp = new Date().toISOString();
|
|
128
|
+
const label = [site, tier, only ? `only-${only}` : mode].join(' / ');
|
|
129
|
+
// 演習的去重鍵一律加 drill: 前綴:不能拿演習去搶真信的去重鍵(否則那封真信會被當成已寄)。
|
|
130
|
+
const raw = input.key || `${tier}:${only ?? mode}:${stamp}`;
|
|
131
|
+
const key = raw.startsWith('drill:') ? raw : `drill:${raw}`;
|
|
132
|
+
const result = await send(
|
|
133
|
+
deps(env),
|
|
134
|
+
{
|
|
135
|
+
site, key, tier, kind: 'drill', to: input.to,
|
|
136
|
+
from: `Mailroom drill <mailroom@${domain ?? 'unset.invalid'}>`,
|
|
137
|
+
subject: `[mailroom drill] ${label} ${stamp}`,
|
|
138
|
+
text: `This is a mailroom delivery drill (${label}). No reply needed.\n${stamp}`,
|
|
139
|
+
html: `<p>This is a mailroom delivery drill (${label}). No reply needed.</p><p>${stamp}</p>`,
|
|
140
|
+
},
|
|
141
|
+
{ forceInvalidResend: !only && mode === 'fallback', routes: only ? [only] : undefined },
|
|
142
|
+
);
|
|
143
|
+
return { ...result, row: await lookup(env.DB, site, key) };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
/** 試跑期每日演習:每個收件人一封,同一天同一人只寄一次(去重鍵含日期)。 */
|
|
148
|
+
async function dailyDrill(env: Env, now = new Date()): Promise<string[]> {
|
|
149
|
+
const cfg = jsonVar<DailyDrill>(env.DAILY_DRILL);
|
|
150
|
+
if (!cfg || !Array.isArray(cfg.to) || !/^\d{4}-\d{2}-\d{2}$/.test(cfg.until ?? '')) return [];
|
|
151
|
+
const day = localDay(now, cfg.utcOffsetHours);
|
|
152
|
+
if (day > cfg.until) return [];
|
|
153
|
+
const out: string[] = [];
|
|
154
|
+
for (const to of cfg.to) {
|
|
155
|
+
const only = cfg.routes && cfg.routes.length === 1 ? cfg.routes[0] : undefined;
|
|
156
|
+
const r = await drill(env, cfg.site || 'drill', { to, mode: 'normal', tier: cfg.tier, only, key: `daily:${day}:${to.toLowerCase()}` });
|
|
157
|
+
out.push(`${r.status}:${r.route ?? '-'}`);
|
|
158
|
+
}
|
|
159
|
+
return out;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** 最近 N 天的寄信統計(試跑驗收用):依站、層、郵差、結果、事後回報分組。不含收件人。 */
|
|
163
|
+
async function report(env: Env, days: number) {
|
|
164
|
+
const since = new Date(Date.now() - days * 86_400_000).toISOString();
|
|
165
|
+
const rows = await env.DB.prepare(
|
|
166
|
+
`SELECT site, tier, route, status, COALESCE(last_event, '-') AS last_event, COUNT(*) AS n,
|
|
167
|
+
SUBSTR(to_email, INSTR(to_email, '@') + 1) AS to_domain
|
|
168
|
+
FROM messages WHERE created_at >= ? GROUP BY site, tier, route, status, last_event, to_domain ORDER BY site, tier, n DESC`,
|
|
169
|
+
).bind(since).all();
|
|
170
|
+
const suppressions = await env.DB.prepare('SELECT reason, source, COUNT(*) AS n FROM suppressions WHERE created_at >= ? GROUP BY reason, source').bind(since).all();
|
|
171
|
+
return { since, rows: rows.results, suppressions: suppressions.results };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** 內線入口(RPC)。 */
|
|
175
|
+
export class Mailroom extends WorkerEntrypoint<Env> {
|
|
176
|
+
send(req: SendRequest): Promise<SendResult> {
|
|
177
|
+
return send(deps(this.env), req);
|
|
178
|
+
}
|
|
179
|
+
lookup(site: string, key: string): Promise<MessageRow | null> {
|
|
180
|
+
return lookup(this.env.DB, site, key);
|
|
181
|
+
}
|
|
182
|
+
drill(site: string, input: DrillInput) {
|
|
183
|
+
return drill(this.env, site, input);
|
|
184
|
+
}
|
|
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
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** 帶鑰匙的站:鑰匙決定是哪個站,站名不聽請求本身的。 */
|
|
206
|
+
function clientSite(env: Env, token: string): string | null {
|
|
207
|
+
for (const site of (env.HTTP_CLIENTS ?? '').split(',').map((s) => s.trim()).filter(Boolean)) {
|
|
208
|
+
if (sameToken(token, env[`HTTP_KEY_${site.toUpperCase().replace(/-/g, '_')}`] ?? '')) return site;
|
|
209
|
+
}
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** 公開網址查帳只回狀態欄位,不回收件人、寄件人、主旨(口令外洩時不會變成查收件人的工具)。 */
|
|
214
|
+
function publicRow(row: MessageRow | null) {
|
|
215
|
+
if (!row) return null;
|
|
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 };
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export default {
|
|
221
|
+
async fetch(request: Request, env: Env): Promise<Response> {
|
|
222
|
+
const url = new URL(request.url);
|
|
223
|
+
|
|
224
|
+
if (url.pathname === '/webhooks/resend' && request.method === 'POST') {
|
|
225
|
+
const size = bodySizeProblem(request.headers.get('content-length'), MAX_WEBHOOK_BYTES);
|
|
226
|
+
if (size) return new Response(size, { status: size === 'missing' ? 411 : 413 });
|
|
227
|
+
const body = await request.text();
|
|
228
|
+
const h = request.headers;
|
|
229
|
+
const ok = await verifySignature(env.RESEND_WEBHOOK_SECRET ?? '', h.get('svix-id') ?? '', h.get('svix-timestamp') ?? '', h.get('svix-signature') ?? '', body);
|
|
230
|
+
if (!ok) return new Response('bad signature', { status: 401 });
|
|
231
|
+
const outcome = await handleEvent(env.DB, h.get('svix-id') ?? '', body);
|
|
232
|
+
console.log('resend webhook', outcome);
|
|
233
|
+
return json({ ok: true });
|
|
234
|
+
}
|
|
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
|
+
|
|
247
|
+
if (url.pathname === '/v1/send' && request.method === 'POST') {
|
|
248
|
+
const site = clientSite(env, bearer(request));
|
|
249
|
+
if (!site) return notFound();
|
|
250
|
+
const limits = {
|
|
251
|
+
perMinute: limitVar(env.HTTP_RATE_PER_MIN, DEFAULT_HTTP_RATE_PER_MIN),
|
|
252
|
+
perDay: limitVar(env.HTTP_DAILY_LIMIT, DEFAULT_HTTP_DAILY_LIMIT),
|
|
253
|
+
};
|
|
254
|
+
const over = await takeRate(env.DB, site, limits);
|
|
255
|
+
// 舊計數窗順手清(約每 100 次請求一次),不另開排程。
|
|
256
|
+
if (Math.random() < 0.01) await pruneRate(env.DB).catch((e) => console.error('prune rate failed', e instanceof Error ? e.message : 'unknown'));
|
|
257
|
+
if (over) {
|
|
258
|
+
console.warn('http client rate limited', site, over);
|
|
259
|
+
return new Response(JSON.stringify({ status: 'failed', retryable: true, reason: `rate_limited_${over}` }), {
|
|
260
|
+
status: 429,
|
|
261
|
+
headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'retry-after': over === 'day' ? '3600' : '60' },
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
const size = bodySizeProblem(request.headers.get('content-length'), MAX_SEND_BYTES);
|
|
265
|
+
if (size) return json({ status: 'rejected', retryable: false, reason: size === 'missing' ? 'length_required' : 'too_large' }, size === 'missing' ? 411 : 413);
|
|
266
|
+
const req = (await request.json().catch(() => null)) as SendRequest | null;
|
|
267
|
+
if (!req || typeof req !== 'object') return json({ status: 'rejected', retryable: false, reason: 'bad_json' }, 400);
|
|
268
|
+
// 白名單有設但讀不懂(JSON 寫壞)=設定錯誤,整個入口先不收;不能當成「沒設」放行。
|
|
269
|
+
const fromTable = jsonVar<Record<string, string[]>>(env.HTTP_FROM);
|
|
270
|
+
if (env.HTTP_FROM !== undefined && env.HTTP_FROM !== '' && (!fromTable || typeof fromTable !== 'object' || Array.isArray(fromTable))) {
|
|
271
|
+
console.error('HTTP_FROM unreadable, refusing http sends');
|
|
272
|
+
return json({ status: 'failed', retryable: true, reason: 'config_error' }, 500);
|
|
273
|
+
}
|
|
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);
|
|
279
|
+
}
|
|
280
|
+
if (fromProblem) return json({ status: 'rejected', retryable: false, reason: 'from_not_allowed' }, 400);
|
|
281
|
+
const result = await send(deps(env), { ...req, site });
|
|
282
|
+
return json(result, result.status === 'rejected' ? 400 : result.status === 'failed' ? 502 : 200);
|
|
283
|
+
}
|
|
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
|
+
|
|
310
|
+
const postPaths = ['/v1/drill', '/v1/unsuppress'];
|
|
311
|
+
const tokenPaths = [...postPaths, '/v1/lookup', '/v1/report'];
|
|
312
|
+
if (tokenPaths.includes(url.pathname) && (request.method === 'POST') === postPaths.includes(url.pathname)) {
|
|
313
|
+
if (!sameToken(bearer(request), env.DRILL_TOKEN ?? '')) return notFound();
|
|
314
|
+
// 管理入口也有速度上限(站名用 _admin,不會跟真站撞:站名規則不准底線開頭)。
|
|
315
|
+
const adminOver = await takeRate(env.DB, '_admin', ADMIN_LIMITS);
|
|
316
|
+
if (adminOver) return new Response('rate limited', { status: 429, headers: { 'retry-after': adminOver === 'day' ? '3600' : '60' } });
|
|
317
|
+
if (Math.random() < 0.05) await pruneRate(env.DB).catch((e) => console.error('prune rate failed', e instanceof Error ? e.message : 'unknown'));
|
|
318
|
+
if (url.pathname === '/v1/unsuppress') {
|
|
319
|
+
const body = (await request.json().catch(() => null)) as { email?: unknown; reasons?: unknown } | null;
|
|
320
|
+
const email = typeof body?.email === 'string' ? body.email.trim() : '';
|
|
321
|
+
const reasons = Array.isArray(body?.reasons) ? body.reasons : [];
|
|
322
|
+
if (!/^[^\s@]+@[^\s@]+$/.test(email) || email.length > 320) return json({ ok: false, reason: 'bad_email' }, 400);
|
|
323
|
+
if (!reasons.length || !reasons.every((r) => SUPPRESSION_REASONS.includes(r as SuppressionReason))) return json({ ok: false, reason: 'bad_reasons' }, 400);
|
|
324
|
+
const removed = await removeSuppression(env.DB, email, [...new Set(reasons as SuppressionReason[])]);
|
|
325
|
+
console.log('manual unsuppress', removed.join(',') || 'none');
|
|
326
|
+
return json({ ok: true, removed });
|
|
327
|
+
}
|
|
328
|
+
if (url.pathname === '/v1/lookup') return json(publicRow(await lookup(env.DB, url.searchParams.get('site') ?? '', url.searchParams.get('key') ?? '')));
|
|
329
|
+
if (url.pathname === '/v1/report') return json(await report(env, Math.min(Math.max(Number(url.searchParams.get('days')) || 7, 1), 90)));
|
|
330
|
+
const body = (await request.json().catch(() => ({}))) as DrillInput & { site?: string };
|
|
331
|
+
const result = await drill(env, body.site || 'drill', { to: String(body.to ?? ''), mode: body.mode, key: body.key, tier: body.tier, only: body.only });
|
|
332
|
+
return json({ ...result, row: publicRow(result.row) }, result.status === 'failed' ? 502 : 200);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
if (url.pathname === '/' && request.method === 'GET') return new Response('mailroom', { status: 200 });
|
|
336
|
+
return notFound();
|
|
337
|
+
},
|
|
338
|
+
|
|
339
|
+
/** Cloudflare 寄信的事後回報(wrangler.jsonc 的 queues.consumers)。處理失敗的那則讓 Queue 重送。 */
|
|
340
|
+
async queue(batch: MessageBatch<unknown>, env: Env): Promise<void> {
|
|
341
|
+
if (isBroadcastBatch(env, batch.queue)) return broadcastQueue(env, batch.messages);
|
|
342
|
+
for (const msg of batch.messages) {
|
|
343
|
+
try {
|
|
344
|
+
const outcome = await handleCfEvent(env.DB, msg.body);
|
|
345
|
+
if (outcome !== 'event:delivered' && outcome !== 'repeat') console.log('cloudflare email event', outcome);
|
|
346
|
+
msg.ack();
|
|
347
|
+
} catch (error) {
|
|
348
|
+
console.error('cloudflare email event failed', error instanceof Error ? error.message : 'unknown');
|
|
349
|
+
msg.retry();
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
},
|
|
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
|
+
|
|
359
|
+
/** 試跑期每日演習(DAILY_DRILL)。 */
|
|
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'));
|
|
365
|
+
const out = await dailyDrill(env);
|
|
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'));
|
|
377
|
+
},
|
|
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
|
+
}
|