@joelincc/mailroom 0.0.0-stage → 0.1.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.
@@ -0,0 +1,193 @@
1
+ // 郵差層:照「郵差順序」一個一個試(順序依站+信件層級設定,見 core.ts routeFor)。
2
+ //
3
+ // 三種郵差:
4
+ // - cloudflare:Cloudflare 寄信(Workers 的 send_email 綁定,不用鑰匙),只給第二層。
5
+ // 8 秒上限;收件人在 Cloudflare 自己的拒收名單(E_RECIPIENT_SUPPRESSED)→ 不換郵差,回 suppressed。
6
+ // 其他錯誤(額度用完、限流、網域沒驗證、逾時)→ 換下一個郵差。逾時時 Cloudflare 可能其實寄出了:寧可重複不要漏寄。
7
+ // - resend:帶 Idempotency-Key(=站名/去重鍵)POST Resend,8 秒上限。
8
+ // 逾時/連線錯/5xx(不確定 Resend 有沒有收下)→ 同一把鑰匙、同一份內容再問一次,3 秒上限。
9
+ // Resend 24 小時內認得這把鑰匙:收過就回原本那封的 id、不會再寄。4xx=確定沒寄 → 換下一個。
10
+ // - smtp2go:最後一道。
11
+ // 全部失敗回 ok:false(不丟例外),由呼叫端記帳。
12
+ // 只回狀態碼與郵差回的錯誤名稱,鑰匙與信件內容不進 log。
13
+
14
+ export interface OutgoingMail {
15
+ from: string;
16
+ to: string;
17
+ subject: string;
18
+ html: string;
19
+ text: string;
20
+ replyTo?: string;
21
+ }
22
+
23
+ export type MailRoute = 'cloudflare' | 'resend' | 'smtp2go';
24
+ export const MAIL_ROUTES: readonly MailRoute[] = ['cloudflare', 'resend', 'smtp2go'];
25
+
26
+ /** Cloudflare send_email 綁定用得到的那一小塊(SendEmail 本身就符合)。 */
27
+ export interface CloudflareSender {
28
+ send(message: {
29
+ from: string | { email: string; name?: string };
30
+ to: string;
31
+ subject: string;
32
+ html?: string;
33
+ text?: string;
34
+ replyTo?: string | { email: string; name?: string };
35
+ }): Promise<{ messageId?: string }>;
36
+ }
37
+
38
+ export interface TransportKeys {
39
+ resend?: string;
40
+ smtp2go?: string;
41
+ cloudflare?: CloudflareSender;
42
+ }
43
+
44
+ export interface TransportResult {
45
+ ok: boolean;
46
+ route?: MailRoute;
47
+ providerId?: string | null;
48
+ error?: string;
49
+ /** true=郵差說收件人在它的拒收名單(不換郵差、不重試)。 */
50
+ suppressed?: boolean;
51
+ }
52
+
53
+ const RESEND_URL = 'https://api.resend.com/emails';
54
+ const SMTP2GO_URL = 'https://api.smtp2go.com/v3/email/send';
55
+ const PRIMARY_TIMEOUT_MS = 8_000;
56
+ const RECHECK_TIMEOUT_MS = 3_000;
57
+ const FALLBACK_TIMEOUT_MS = 10_000;
58
+ /** 沒有備援鑰匙時 Resend 是唯一一條路,給寬一點。 */
59
+ const SOLO_TIMEOUT_MS = 15_000;
60
+
61
+ interface Attempt {
62
+ ok: boolean;
63
+ id?: string | null;
64
+ error?: string;
65
+ /** true=不確定對方有沒有收下(逾時/連線錯/5xx),值得拿同一把鑰匙補問。 */
66
+ uncertain?: boolean;
67
+ suppressed?: boolean;
68
+ }
69
+
70
+ async function postJson(fetcher: typeof fetch, url: string, headers: Record<string, string>, body: string, timeoutMs: number) {
71
+ const controller = new AbortController();
72
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
73
+ try {
74
+ const res = await fetcher(url, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body, signal: controller.signal });
75
+ const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;
76
+ return { status: res.status, ok: res.ok, json };
77
+ } catch (error) {
78
+ if (error instanceof Error && error.name === 'AbortError') throw new Error(`逾時(${timeoutMs}ms)`);
79
+ throw error;
80
+ } finally {
81
+ clearTimeout(timer);
82
+ }
83
+ }
84
+
85
+ async function viaResend(fetcher: typeof fetch, key: string, idempotencyKey: string, body: string, timeoutMs: number): Promise<Attempt> {
86
+ try {
87
+ const { ok, status, json } = await postJson(fetcher, RESEND_URL, { authorization: `Bearer ${key}`, 'idempotency-key': idempotencyKey }, body, timeoutMs);
88
+ if (!ok) {
89
+ return { ok: false, uncertain: status >= 500, error: `resend ${status} ${String(json.name ?? '')}`.trim().slice(0, 200) };
90
+ }
91
+ return { ok: true, id: typeof json.id === 'string' ? json.id : null };
92
+ } catch (error) {
93
+ return { ok: false, uncertain: true, error: `resend ${error instanceof Error ? error.message : 'error'}` };
94
+ }
95
+ }
96
+
97
+ async function viaSmtp2go(fetcher: typeof fetch, key: string, mail: OutgoingMail): Promise<Attempt> {
98
+ try {
99
+ const payload: Record<string, unknown> = { sender: mail.from, to: [mail.to], subject: mail.subject, text_body: mail.text, html_body: mail.html };
100
+ if (mail.replyTo) payload.custom_headers = [{ header: 'Reply-To', value: mail.replyTo }];
101
+ const { ok, status, json } = await postJson(fetcher, SMTP2GO_URL, { 'X-Smtp2go-Api-Key': key }, JSON.stringify(payload), FALLBACK_TIMEOUT_MS);
102
+ const data = (json.data ?? {}) as { succeeded?: number; email_id?: string; error_code?: string };
103
+ // SMTP2GO 部分錯誤也回 200,一律以 data.succeeded 為準。
104
+ if (!ok || data.succeeded !== 1) return { ok: false, error: `smtp2go ${status} ${String(data.error_code ?? '')}`.trim().slice(0, 200) };
105
+ return { ok: true, id: data.email_id ?? null };
106
+ } catch (error) {
107
+ return { ok: false, error: `smtp2go ${error instanceof Error ? error.message : 'error'}` };
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Resend 的 Idempotency-Key 上限 256 字;太長就改用 sha256。
113
+ * 去重鍵含非 ASCII 可見字元(中文、換行…)時也改用 sha256:HTTP 標頭放不進這些字,
114
+ * 照放會讓 Resend 那一趟直接丟例外、每封都悄悄落到備援郵差。
115
+ */
116
+ export async function idempotencyKeyFor(site: string, dedupeKey: string): Promise<string> {
117
+ const raw = `${site}/${dedupeKey}`;
118
+ if (raw.length <= 200 && /^[\x20-\x7e]+$/.test(raw)) return raw;
119
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw));
120
+ return `${site}/sha256-${[...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')}`;
121
+ }
122
+
123
+ /** `名稱 <地址>` 或 `地址` → Cloudflare 要的 { email, name }(core.ts 已驗過、重組過)。 */
124
+ export function splitAddress(a: string): { email: string; name?: string } {
125
+ const m = /^(.*?)\s*<([^<>\s]+)>$/.exec(a.trim());
126
+ return m ? (m[1] ? { email: m[2], name: m[1] } : { email: m[2] }) : { email: a.trim() };
127
+ }
128
+
129
+ async function viaCloudflare(sender: CloudflareSender, mail: OutgoingMail, timeoutMs: number): Promise<Attempt> {
130
+ let timer: ReturnType<typeof setTimeout> | undefined;
131
+ try {
132
+ const sent = sender.send({
133
+ from: splitAddress(mail.from), to: mail.to, subject: mail.subject, html: mail.html, text: mail.text,
134
+ ...(mail.replyTo ? { replyTo: splitAddress(mail.replyTo) } : {}),
135
+ });
136
+ const timeout = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(`逾時(${timeoutMs}ms)`)), timeoutMs); });
137
+ const r = await Promise.race([sent, timeout]);
138
+ return { ok: true, id: typeof r?.messageId === 'string' ? r.messageId : null };
139
+ } catch (error) {
140
+ const code = error && typeof error === 'object' && 'code' in error ? String((error as { code: unknown }).code) : '';
141
+ const msg = error instanceof Error ? error.message : 'error';
142
+ // 沒有錯誤碼時不記郵差的原文訊息(內容我們管不到,可能帶收件地址);只留自己的逾時訊息。
143
+ const detail = code || (msg.startsWith('逾時') ? msg : 'error');
144
+ return { ok: false, suppressed: code === 'E_RECIPIENT_SUPPRESSED', error: `cloudflare ${detail}`.slice(0, 200) };
145
+ } finally {
146
+ if (timer) clearTimeout(timer);
147
+ }
148
+ }
149
+
150
+ const has = (keys: TransportKeys, r: MailRoute): boolean => (r === 'cloudflare' ? !!keys.cloudflare : !!keys[r]);
151
+
152
+ /**
153
+ * 照 routes 的順序試;沒有鑰匙(或沒有綁定)的郵差跳過。
154
+ * routes 預設 resend → smtp2go(第一層的預設順序)。
155
+ */
156
+ export async function deliver(
157
+ keys: TransportKeys,
158
+ mail: OutgoingMail,
159
+ idempotencyKey: string,
160
+ fetcher: typeof fetch = fetch,
161
+ routes: readonly MailRoute[] = ['resend', 'smtp2go'],
162
+ ): Promise<TransportResult> {
163
+ const usable = routes.filter((r, i) => routes.indexOf(r) === i && has(keys, r));
164
+ if (usable.length === 0) return { ok: false, error: `no-route ${routes.join('>')}` };
165
+ const errors: string[] = [];
166
+ for (let i = 0; i < usable.length; i++) {
167
+ const route = usable[i];
168
+ const last = i === usable.length - 1;
169
+ let a: Attempt;
170
+ if (route === 'cloudflare') {
171
+ a = await viaCloudflare(keys.cloudflare!, mail, last ? SOLO_TIMEOUT_MS : PRIMARY_TIMEOUT_MS);
172
+ if (a.suppressed) return { ok: false, suppressed: true, error: a.error };
173
+ } else if (route === 'resend') {
174
+ const payload: Record<string, unknown> = { from: mail.from, to: [mail.to], subject: mail.subject, html: mail.html, text: mail.text };
175
+ if (mail.replyTo) payload.reply_to = mail.replyTo;
176
+ // 補問時鑰匙與內容必須完全相同(內容不同=Resend 回 409)。
177
+ const body = JSON.stringify(payload);
178
+ a = await viaResend(fetcher, keys.resend!, idempotencyKey, body, last ? SOLO_TIMEOUT_MS : PRIMARY_TIMEOUT_MS);
179
+ if (!a.ok && a.uncertain && !last) {
180
+ const recheck = await viaResend(fetcher, keys.resend!, idempotencyKey, body, RECHECK_TIMEOUT_MS);
181
+ if (recheck.ok) a = recheck;
182
+ }
183
+ } else {
184
+ a = await viaSmtp2go(fetcher, keys.smtp2go!, mail);
185
+ }
186
+ if (a.ok) {
187
+ if (i > 0) console.warn(`mail via ${route} after`, errors.join('; '));
188
+ return { ok: true, route, providerId: a.id };
189
+ }
190
+ errors.push(a.error ?? `${route} error`);
191
+ }
192
+ return { ok: false, error: errors.join('; ') };
193
+ }
package/src/webhook.ts ADDED
@@ -0,0 +1,99 @@
1
+ // Resend 的事後回報(webhook):退信、檢舉、送達。驗簽章(Svix/Standard Webhooks)後才處理。
2
+ // Resend 的 webhook 是整個帳號一份:同一個 Resend 帳號下其他程式寄的信也會回報到這裡,所以拒收名單是共用的一份。
3
+
4
+ import { addSuppression, type Db } from './core.ts';
5
+
6
+ /** 簽章時間跟現在差超過 5 分鐘就不收(防重播)。 */
7
+ const TOLERANCE_S = 5 * 60;
8
+
9
+ function b64ToBytes(b64: string): Uint8Array {
10
+ const bin = atob(b64);
11
+ const out = new Uint8Array(bin.length);
12
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
13
+ return out;
14
+ }
15
+
16
+ function equal(a: Uint8Array, b: Uint8Array): boolean {
17
+ if (a.length !== b.length) return false;
18
+ let diff = 0;
19
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
20
+ return diff === 0;
21
+ }
22
+
23
+ /** secret 是 Resend 給的 `whsec_<base64>`;header 是 svix-id/svix-timestamp/svix-signature(`v1,<b64> v1,<b64>`)。 */
24
+ export async function verifySignature(secret: string, id: string, timestamp: string, signature: string, body: string, nowS = Math.floor(Date.now() / 1000)): Promise<boolean> {
25
+ if (!secret || !id || !timestamp || !signature) return false;
26
+ const ts = Number(timestamp);
27
+ if (!Number.isFinite(ts) || Math.abs(nowS - ts) > TOLERANCE_S) return false;
28
+ let keyBytes: Uint8Array;
29
+ try {
30
+ keyBytes = b64ToBytes(secret.trim().replace(/^whsec_/, ''));
31
+ } catch {
32
+ return false;
33
+ }
34
+ const key = await crypto.subtle.importKey('raw', Uint8Array.from(keyBytes), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
35
+ const expected = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(`${id}.${timestamp}.${body}`)));
36
+ for (const part of signature.split(' ').filter(Boolean)) {
37
+ const [ver, sig] = part.split(',');
38
+ if (ver !== 'v1' || !sig) continue;
39
+ try {
40
+ if (equal(b64ToBytes(sig), expected)) return true;
41
+ } catch {
42
+ /* 壞掉的那組跳過 */
43
+ }
44
+ }
45
+ return false;
46
+ }
47
+
48
+ interface ResendEvent {
49
+ type?: string;
50
+ data?: { email_id?: string; to?: string[] | string; bounce?: { type?: string; subType?: string; message?: string } };
51
+ }
52
+
53
+ const LAST_EVENT: Record<string, string> = {
54
+ 'email.delivered': 'delivered',
55
+ 'email.bounced': 'bounced',
56
+ 'email.complained': 'complained',
57
+ 'email.failed': 'failed',
58
+ 'email.delivery_delayed': 'delayed',
59
+ };
60
+
61
+ /** 處理一則已驗過簽章的事件;回傳做了什麼(給 log/測試看)。 */
62
+ export async function handleEvent(db: Db, eventId: string, raw: string, now = new Date()): Promise<string> {
63
+ let ev: ResendEvent;
64
+ try {
65
+ ev = JSON.parse(raw) as ResendEvent;
66
+ } catch {
67
+ return 'bad_json';
68
+ }
69
+ const type = String(ev.type ?? '');
70
+ // 先查有沒有處理過;處理完才記「已處理」(中途出錯時郵差重送還會再處理一次)。下面每一步都可重複執行不出錯。
71
+ const seen = await db.prepare('SELECT 1 AS x FROM webhook_events WHERE id = ?').bind(eventId).first();
72
+ if (seen) return 'repeat';
73
+ const outcome = await applyEvent(db, ev, now);
74
+ await db.prepare('INSERT INTO webhook_events (id, type, received_at) VALUES (?, ?, ?) ON CONFLICT (id) DO NOTHING').bind(eventId, type, now.toISOString()).run();
75
+ return outcome;
76
+ }
77
+
78
+ async function applyEvent(db: Db, ev: ResendEvent, now: Date): Promise<string> {
79
+ const type = String(ev.type ?? '');
80
+ const data = ev.data ?? {};
81
+ const recipients = (Array.isArray(data.to) ? data.to : data.to ? [data.to] : []).map((e) => String(e).trim().toLowerCase()).filter(Boolean);
82
+ const last = LAST_EVENT[type];
83
+ if (last && data.email_id) {
84
+ await db.prepare('UPDATE messages SET last_event = ?, updated_at = ? WHERE provider_id = ?').bind(last, now.toISOString(), data.email_id).run();
85
+ }
86
+
87
+ if (type === 'email.bounced') {
88
+ // 只有永久退信(信箱不存在、網域收不到信)才進拒收名單;信箱滿了這類暫時性的不擋。
89
+ if (data.bounce?.type !== 'Permanent') return `bounce_${String(data.bounce?.type ?? 'unknown').toLowerCase()}`;
90
+ const detail = [data.bounce.subType, data.bounce.message].filter(Boolean).join(': ');
91
+ for (const email of recipients) await addSuppression(db, email, 'hard_bounce', 'resend-webhook', detail || null, now);
92
+ return `hard_bounce:${recipients.length}`;
93
+ }
94
+ if (type === 'email.complained') {
95
+ for (const email of recipients) await addSuppression(db, email, 'complaint', 'resend-webhook', null, now);
96
+ return `complaint:${recipients.length}`;
97
+ }
98
+ return last ? `event:${last}` : 'ignored';
99
+ }
@@ -0,0 +1,42 @@
1
+ {
2
+ // Deploy template: copy to wrangler.jsonc, fill in your own account and database ids, then `npm run deploy`.
3
+ // wrangler.jsonc is git-ignored so your real ids never land in a fork.
4
+ "$schema": "node_modules/wrangler/config-schema.json",
5
+ "name": "mailroom",
6
+ // Recommended: deploying to the wrong account then fails loudly.
7
+ // "account_id": "<your Cloudflare account id>",
8
+ "main": "src/index.ts",
9
+ "compatibility_date": "2026-10-01",
10
+ // The public endpoints (Resend webhooks, clients on other Cloudflare accounts) live on workers.dev.
11
+ // If you don't need them, set this to false (or move them to a custom domain).
12
+ "workers_dev": true,
13
+ "preview_urls": false,
14
+ "d1_databases": [
15
+ { "binding": "DB", "database_name": "mailroom", "database_id": "<fill in after: npx wrangler d1 create mailroom>", "migrations_dir": "migrations" }
16
+ ],
17
+ "vars": {
18
+ // Sender domain for tier 1 "must deliver" mail (sign-in, invites, payments). Verify it with your providers first.
19
+ "FROM_DOMAIN": "notify.example.com",
20
+ // Sender domain for tier 2 "service reminders" (off by default). If you enable it, also set the secret
21
+ // RESEND_API_KEY_REMIND — without it tier 2 skips Resend and uses SMTP2GO only.
22
+ // "REMIND_DOMAIN": "remind.example.com",
23
+ // Provider order. Keys are "site:tier" or "*:tier"; anything not listed uses Resend -> SMTP2GO.
24
+ // Example: { "*:remind": ["cloudflare", "resend", "smtp2go"] }
25
+ "ROUTES": {},
26
+ // Clients that send over the public HTTP endpoint (comma separated). Each needs a secret HTTP_KEY_<SITE_NAME_UPPERCASE>.
27
+ "HTTP_CLIENTS": "",
28
+ // Per-client limits on the public HTTP endpoint (caps the damage if a client key leaks).
29
+ // Missing or invalid -> default; an explicit 0 means unlimited.
30
+ "HTTP_RATE_PER_MIN": 60,
31
+ "HTTP_DAILY_LIMIT": 2000
32
+ // Per-client sender allowlist for the public HTTP endpoint (strongly recommended):
33
+ // "HTTP_FROM": { "shop": ["orders@notify.example.com"] }
34
+ },
35
+ // Only needed if you send through Cloudflare Email Sending. List every allowed sender address.
36
+ // "send_email": [{ "name": "EMAIL", "remote": true, "allowed_sender_addresses": ["app@remind.example.com"] }],
37
+ // Delivery / bounce / complaint events from Cloudflare Email Sending (only if you use it).
38
+ // "queues": { "consumers": [{ "queue": "mailroom-email-events", "max_batch_size": 50, "max_batch_timeout": 30, "max_retries": 5 }] },
39
+ // Secrets (always add as Secret, never as a plain variable):
40
+ // RESEND_API_KEY, SMTP2GO_API_KEY, RESEND_WEBHOOK_SECRET, DRILL_TOKEN, HTTP_KEY_*, RESEND_API_KEY_REMIND (optional)
41
+ "observability": { "enabled": true }
42
+ }