@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
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
// Amazon SES 的事後回報:SES 設定組 → SNS 主題 → HTTPS 訂閱 → 郵務室 POST /webhooks/ses。
|
|
2
|
+
//
|
|
3
|
+
// 進來的每一則先驗 SNS 簽章,過了才處理(官方作法:
|
|
4
|
+
// https://docs.aws.amazon.com/sns/latest/dg/sns-verify-signature-of-message.html):
|
|
5
|
+
// 1. 主題 ARN 必須在白名單(部署端設定),而且跟設定的地區一致。
|
|
6
|
+
// 2. 憑證網址必須是 https://sns.{地區}.amazonaws.com/…pem(AWS 自己的網域、同一個地區,不收別的主機、連接埠、帳密)。
|
|
7
|
+
// 3. 從憑證取公鑰(只用 WebCrypto+一小段 DER 解析),照 Type 組「待簽字串」,SignatureVersion 2=SHA256(預設只收這版)、
|
|
8
|
+
// 1=SHA1(要部署端明確打開才收)。憑證過期或還沒生效一律不收。
|
|
9
|
+
// 4. Timestamp 太舊(預設 7 天)或在未來太遠的不收(防重播;更近的重播靠下面的去重)。
|
|
10
|
+
// 訂閱確認(SubscriptionConfirmation):驗過簽章、SubscribeURL 也是同一個 SNS 主機時,才去打那個網址確認。
|
|
11
|
+
// 通知(Notification):Message 裡是 SES 的事件 JSON → 正規化成 ProviderEvent → ingestEvent(退信、檢舉進 applyFeedback)。
|
|
12
|
+
// 同一則 SNS 訊息(MessageId)重送只處理一次:跟其他郵差共用 webhook_events。
|
|
13
|
+
// 不 import cloudflare:*;收件人、鑰匙不進 log。
|
|
14
|
+
|
|
15
|
+
import type { Db } from './core.ts';
|
|
16
|
+
import { ingestEvent, type IngestOptions } from './broadcast/events.ts';
|
|
17
|
+
import type { EventType, ProviderEvent } from './broadcast/postman.ts';
|
|
18
|
+
|
|
19
|
+
export interface SnsVerifyOptions {
|
|
20
|
+
/** SES/SNS 所在地區,例 ap-northeast-1。憑證與訂閱確認網址都必須是這個地區的 SNS 主機。 */
|
|
21
|
+
region: string;
|
|
22
|
+
/** 准收的 SNS 主題 ARN(完全相同才收)。空的=一律不收。 */
|
|
23
|
+
topicArns: readonly string[];
|
|
24
|
+
/** 也收 SignatureVersion 1(SHA1)。預設 false:主題請設成 SignatureVersion 2。 */
|
|
25
|
+
allowSha1?: boolean;
|
|
26
|
+
/** Timestamp 最多多舊(秒),預設 7 天。 */
|
|
27
|
+
maxAgeSeconds?: number;
|
|
28
|
+
fetcher?: typeof fetch;
|
|
29
|
+
now?: () => Date;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface SnsMessage {
|
|
33
|
+
Type: string;
|
|
34
|
+
MessageId: string;
|
|
35
|
+
TopicArn: string;
|
|
36
|
+
Message: string;
|
|
37
|
+
Timestamp: string;
|
|
38
|
+
SignatureVersion: string;
|
|
39
|
+
Signature: string;
|
|
40
|
+
SigningCertURL: string;
|
|
41
|
+
Subject?: string;
|
|
42
|
+
SubscribeURL?: string;
|
|
43
|
+
Token?: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export type VerifyResult = { ok: true; msg: SnsMessage } | { ok: false; reason: string };
|
|
47
|
+
|
|
48
|
+
const DEFAULT_MAX_AGE_S = 7 * 86_400;
|
|
49
|
+
const FUTURE_SKEW_S = 15 * 60;
|
|
50
|
+
const CERT_TTL_MS = 60 * 60_000;
|
|
51
|
+
const MAX_CERT_BYTES = 16_000;
|
|
52
|
+
const TYPES = ['Notification', 'SubscriptionConfirmation', 'UnsubscribeConfirmation'];
|
|
53
|
+
|
|
54
|
+
// ---------- 憑證:PEM → DER → 公鑰(SubjectPublicKeyInfo)與有效期間 ----------
|
|
55
|
+
|
|
56
|
+
interface Tlv { tag: number; start: number; end: number; next: number }
|
|
57
|
+
|
|
58
|
+
function readTlv(b: Uint8Array, at: number, limit = b.length): Tlv {
|
|
59
|
+
if (at + 2 > limit) throw new Error('asn1 short');
|
|
60
|
+
const tag = b[at];
|
|
61
|
+
let len = b[at + 1];
|
|
62
|
+
let p = at + 2;
|
|
63
|
+
if (len & 0x80) {
|
|
64
|
+
const n = len & 0x7f;
|
|
65
|
+
if (n < 1 || n > 3 || p + n > limit) throw new Error('asn1 length');
|
|
66
|
+
len = 0;
|
|
67
|
+
for (let i = 0; i < n; i++) len = (len << 8) | b[p + i];
|
|
68
|
+
p += n;
|
|
69
|
+
}
|
|
70
|
+
if (p + len > limit) throw new Error('asn1 overflow');
|
|
71
|
+
return { tag, start: p, end: p + len, next: p + len };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function asn1Time(b: Uint8Array, t: Tlv): number {
|
|
75
|
+
const s = new TextDecoder().decode(b.subarray(t.start, t.end));
|
|
76
|
+
let m: RegExpExecArray | null;
|
|
77
|
+
if (t.tag === 0x17 && (m = /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(s))) {
|
|
78
|
+
const yy = Number(m[1]);
|
|
79
|
+
return Date.UTC(yy >= 50 ? 1900 + yy : 2000 + yy, Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6]));
|
|
80
|
+
}
|
|
81
|
+
if (t.tag === 0x18 && (m = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(s))) {
|
|
82
|
+
return Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6]));
|
|
83
|
+
}
|
|
84
|
+
throw new Error('asn1 time');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface ParsedCert { spki: Uint8Array; notBefore: number; notAfter: number }
|
|
88
|
+
|
|
89
|
+
/** X.509 憑證(PEM)→ 公鑰與有效期間。只解析用得到的欄位;格式不對就丟例外。 */
|
|
90
|
+
export function parseCertificate(pem: string): ParsedCert {
|
|
91
|
+
const m = /-----BEGIN CERTIFICATE-----([A-Za-z0-9+/=\s]+)-----END CERTIFICATE-----/.exec(pem);
|
|
92
|
+
if (!m) throw new Error('not a certificate');
|
|
93
|
+
const bin = atob(m[1].replace(/\s+/g, ''));
|
|
94
|
+
const der = new Uint8Array(bin.length);
|
|
95
|
+
for (let i = 0; i < bin.length; i++) der[i] = bin.charCodeAt(i);
|
|
96
|
+
const cert = readTlv(der, 0);
|
|
97
|
+
if (cert.tag !== 0x30) throw new Error('cert not sequence');
|
|
98
|
+
const tbs = readTlv(der, cert.start, cert.end);
|
|
99
|
+
if (tbs.tag !== 0x30) throw new Error('tbs not sequence');
|
|
100
|
+
let p = tbs.start;
|
|
101
|
+
let f = readTlv(der, p, tbs.end);
|
|
102
|
+
if (f.tag === 0xa0) f = readTlv(der, (p = f.next), tbs.end); // version
|
|
103
|
+
// serialNumber, signature, issuer
|
|
104
|
+
for (const tag of [0x02, 0x30, 0x30]) {
|
|
105
|
+
if (f.tag !== tag) throw new Error('tbs layout');
|
|
106
|
+
f = readTlv(der, (p = f.next), tbs.end);
|
|
107
|
+
}
|
|
108
|
+
if (f.tag !== 0x30) throw new Error('validity');
|
|
109
|
+
const nb = readTlv(der, f.start, f.end);
|
|
110
|
+
const na = readTlv(der, nb.next, f.end);
|
|
111
|
+
const notBefore = asn1Time(der, nb);
|
|
112
|
+
const notAfter = asn1Time(der, na);
|
|
113
|
+
const subject = readTlv(der, (p = f.next), tbs.end);
|
|
114
|
+
if (subject.tag !== 0x30) throw new Error('subject');
|
|
115
|
+
const spkiStart = subject.next;
|
|
116
|
+
const spki = readTlv(der, spkiStart, tbs.end);
|
|
117
|
+
if (spki.tag !== 0x30) throw new Error('spki');
|
|
118
|
+
return { spki: der.slice(spkiStart, spki.end), notBefore, notAfter };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// ---------- 網址檢查 ----------
|
|
122
|
+
|
|
123
|
+
const REGION = /^[a-z]{2}(-[a-z]+)+-\d{1,2}$/;
|
|
124
|
+
|
|
125
|
+
/** 必須是 https://sns.{地區}.amazonaws.com/(沒有連接埠、帳密);回 URL 或 null。 */
|
|
126
|
+
function snsUrl(raw: string | undefined, region: string): URL | null {
|
|
127
|
+
if (typeof raw !== 'string' || raw.length > 2048 || !REGION.test(region)) return null;
|
|
128
|
+
let u: URL;
|
|
129
|
+
try {
|
|
130
|
+
u = new URL(raw);
|
|
131
|
+
} catch {
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
if (u.protocol !== 'https:' || u.username || u.password || u.port || u.hostname !== `sns.${region}.amazonaws.com`) return null;
|
|
135
|
+
return u;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function isTrustedCertUrl(raw: string | undefined, region: string): boolean {
|
|
139
|
+
const u = snsUrl(raw, region);
|
|
140
|
+
return !!u && /^\/SimpleNotificationService-[A-Za-z0-9]+\.pem$/.test(u.pathname) && !u.search && !u.hash;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function isTrustedSubscribeUrl(raw: string | undefined, region: string, topicArn: string): boolean {
|
|
144
|
+
const u = snsUrl(raw, region);
|
|
145
|
+
return !!u && u.pathname === '/' && u.searchParams.get('Action') === 'ConfirmSubscription' && u.searchParams.get('TopicArn') === topicArn && !!u.searchParams.get('Token');
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// ---------- 簽章 ----------
|
|
149
|
+
|
|
150
|
+
/** 照 Type 組待簽字串:欄位名、值各一行,固定順序,最後一行後面也有換行。 */
|
|
151
|
+
export function stringToSign(msg: SnsMessage): string | null {
|
|
152
|
+
const fields =
|
|
153
|
+
msg.Type === 'Notification'
|
|
154
|
+
? ['Message', 'MessageId', ...(msg.Subject !== undefined ? ['Subject'] : []), 'Timestamp', 'TopicArn', 'Type']
|
|
155
|
+
: ['Message', 'MessageId', 'SubscribeURL', 'Timestamp', 'Token', 'TopicArn', 'Type'];
|
|
156
|
+
let out = '';
|
|
157
|
+
for (const f of fields) {
|
|
158
|
+
const v = (msg as unknown as Record<string, unknown>)[f];
|
|
159
|
+
if (typeof v !== 'string') return null;
|
|
160
|
+
out += `${f}\n${v}\n`;
|
|
161
|
+
}
|
|
162
|
+
return out;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const certCache = new Map<string, { cert: ParsedCert; at: number }>();
|
|
166
|
+
|
|
167
|
+
/** 測試用:清掉憑證快取。 */
|
|
168
|
+
export function clearCertCache(): void {
|
|
169
|
+
certCache.clear();
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async function loadCert(url: string, fetcher: typeof fetch, nowMs: number): Promise<ParsedCert> {
|
|
173
|
+
const hit = certCache.get(url);
|
|
174
|
+
if (hit && nowMs - hit.at < CERT_TTL_MS) return hit.cert;
|
|
175
|
+
const controller = new AbortController();
|
|
176
|
+
const timer = setTimeout(() => controller.abort(), 5_000);
|
|
177
|
+
try {
|
|
178
|
+
const res = await fetcher(url, { method: 'GET', redirect: 'manual', signal: controller.signal });
|
|
179
|
+
if (res.status !== 200) throw new Error(`cert ${res.status}`);
|
|
180
|
+
const text = await res.text();
|
|
181
|
+
if (text.length > MAX_CERT_BYTES) throw new Error('cert too large');
|
|
182
|
+
const cert = parseCertificate(text);
|
|
183
|
+
if (certCache.size > 20) certCache.clear();
|
|
184
|
+
certCache.set(url, { cert, at: nowMs });
|
|
185
|
+
return cert;
|
|
186
|
+
} finally {
|
|
187
|
+
clearTimeout(timer);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function b64(s: string): Uint8Array | null {
|
|
192
|
+
try {
|
|
193
|
+
const bin = atob(s);
|
|
194
|
+
const out = new Uint8Array(bin.length);
|
|
195
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
196
|
+
return out;
|
|
197
|
+
} catch {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** 驗一則 SNS 訊息(已 JSON.parse)。過了才回 ok。 */
|
|
203
|
+
export async function verifySnsMessage(raw: unknown, opts: SnsVerifyOptions): Promise<VerifyResult> {
|
|
204
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { ok: false, reason: 'bad_message' };
|
|
205
|
+
const msg = raw as SnsMessage;
|
|
206
|
+
for (const k of ['Type', 'MessageId', 'TopicArn', 'Message', 'Timestamp', 'SignatureVersion', 'Signature', 'SigningCertURL'] as const) {
|
|
207
|
+
if (typeof msg[k] !== 'string' || !msg[k]) return { ok: false, reason: `missing_${k}` };
|
|
208
|
+
}
|
|
209
|
+
if (!TYPES.includes(msg.Type)) return { ok: false, reason: 'bad_type' };
|
|
210
|
+
if (!REGION.test(opts.region)) return { ok: false, reason: 'bad_region_config' };
|
|
211
|
+
if (!opts.topicArns.includes(msg.TopicArn) || msg.TopicArn.split(':')[3] !== opts.region) return { ok: false, reason: 'topic_not_allowed' };
|
|
212
|
+
const hash = msg.SignatureVersion === '2' ? 'SHA-256' : msg.SignatureVersion === '1' && opts.allowSha1 ? 'SHA-1' : null;
|
|
213
|
+
if (!hash) return { ok: false, reason: 'signature_version_not_allowed' };
|
|
214
|
+
if (!isTrustedCertUrl(msg.SigningCertURL, opts.region)) return { ok: false, reason: 'untrusted_cert_url' };
|
|
215
|
+
const nowMs = (opts.now ?? (() => new Date()))().getTime();
|
|
216
|
+
const ts = Date.parse(msg.Timestamp);
|
|
217
|
+
if (!Number.isFinite(ts)) return { ok: false, reason: 'bad_timestamp' };
|
|
218
|
+
if (nowMs - ts > (opts.maxAgeSeconds ?? DEFAULT_MAX_AGE_S) * 1000 || ts - nowMs > FUTURE_SKEW_S * 1000) return { ok: false, reason: 'stale_timestamp' };
|
|
219
|
+
const toSign = stringToSign(msg);
|
|
220
|
+
if (toSign === null) return { ok: false, reason: 'missing_fields' };
|
|
221
|
+
const sig = b64(msg.Signature);
|
|
222
|
+
if (!sig || sig.length < 64) return { ok: false, reason: 'bad_signature_encoding' };
|
|
223
|
+
let cert: ParsedCert;
|
|
224
|
+
try {
|
|
225
|
+
cert = await loadCert(msg.SigningCertURL, opts.fetcher ?? fetch, nowMs);
|
|
226
|
+
} catch {
|
|
227
|
+
return { ok: false, reason: 'cert_unavailable' };
|
|
228
|
+
}
|
|
229
|
+
if (nowMs < cert.notBefore || nowMs > cert.notAfter) return { ok: false, reason: 'cert_expired' };
|
|
230
|
+
try {
|
|
231
|
+
const key = await crypto.subtle.importKey('spki', Uint8Array.from(cert.spki), { name: 'RSASSA-PKCS1-v1_5', hash }, false, ['verify']);
|
|
232
|
+
const ok = await crypto.subtle.verify('RSASSA-PKCS1-v1_5', key, Uint8Array.from(sig), new TextEncoder().encode(toSign));
|
|
233
|
+
return ok ? { ok: true, msg } : { ok: false, reason: 'bad_signature' };
|
|
234
|
+
} catch {
|
|
235
|
+
return { ok: false, reason: 'bad_signature' };
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// ---------- SES 事件 → ProviderEvent ----------
|
|
240
|
+
|
|
241
|
+
interface SesMail { messageId?: unknown; destination?: unknown; tags?: unknown; timestamp?: unknown }
|
|
242
|
+
interface SesEvent {
|
|
243
|
+
eventType?: unknown;
|
|
244
|
+
notificationType?: unknown;
|
|
245
|
+
mail?: SesMail;
|
|
246
|
+
bounce?: { bounceType?: unknown; bounceSubType?: unknown; bouncedRecipients?: unknown; feedbackId?: unknown; timestamp?: unknown };
|
|
247
|
+
complaint?: { complainedRecipients?: unknown; complaintFeedbackType?: unknown; complaintSubType?: unknown; feedbackId?: unknown; timestamp?: unknown };
|
|
248
|
+
delivery?: { recipients?: unknown; timestamp?: unknown; smtpResponse?: unknown };
|
|
249
|
+
reject?: { reason?: unknown };
|
|
250
|
+
failure?: { errorMessage?: unknown };
|
|
251
|
+
deliveryDelay?: { delayType?: unknown; delayedRecipients?: unknown; timestamp?: unknown };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const str = (v: unknown, max = 200): string | null => (typeof v === 'string' && v ? v.slice(0, max) : null);
|
|
255
|
+
const addr = (v: unknown): string | null => {
|
|
256
|
+
if (typeof v !== 'string') return null;
|
|
257
|
+
const m = /<([^<>\s]+)>\s*$/.exec(v);
|
|
258
|
+
const a = (m ? m[1] : v).trim().toLowerCase();
|
|
259
|
+
return /^[^\s@]+@[^\s@]+$/.test(a) && a.length <= 320 ? a : null;
|
|
260
|
+
};
|
|
261
|
+
function tag(tags: unknown, name: string): string | null {
|
|
262
|
+
if (!tags || typeof tags !== 'object') return null;
|
|
263
|
+
const v = (tags as Record<string, unknown>)[name];
|
|
264
|
+
return Array.isArray(v) && typeof v[0] === 'string' ? v[0].slice(0, 64) : null;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* 事件說的收件人,只認原信收件人裡有的(mail.destination)。
|
|
269
|
+
* 事件沒列任何地址、原信只有一位收件人 → 算他的;事件列了地址卻對不上(例:讀者自動轉寄,退信報的是轉寄目的地)→ 不認,
|
|
270
|
+
* 不能把轉寄目的地的退信算成讀者自己的信箱壞了。
|
|
271
|
+
*/
|
|
272
|
+
function recipients(listed: string[], destination: string[], anyListed: boolean): string[] {
|
|
273
|
+
const matched = listed.filter((a) => destination.includes(a));
|
|
274
|
+
if (matched.length) return [...new Set(matched)];
|
|
275
|
+
return !anyListed && destination.length === 1 ? destination : [];
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** SES 根本沒寄(收件人已在 SES 自己的拒收名單):只記事件,不當成新的退信或檢舉。 */
|
|
279
|
+
const NOT_SENT_SUBTYPES = new Set(['OnAccountSuppressionList', 'OnTenantSuppressionList', 'EmailValidationSuppressed']);
|
|
280
|
+
|
|
281
|
+
/** SES 暫時退信子類型 → 給 applyFeedback 的原因。只有信箱滿算信箱層級;原因不明的不給(不累計)。 */
|
|
282
|
+
export function transientCause(subType: string | null): 'mailbox' | 'content' | undefined {
|
|
283
|
+
if (subType === 'MailboxFull') return 'mailbox';
|
|
284
|
+
if (subType === 'ContentRejected' || subType === 'AttachmentRejected' || subType === 'MessageTooLarge') return 'content';
|
|
285
|
+
return undefined;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** 一則 SES 事件 → 0~多則 ProviderEvent(每個收件人一則)。Open、Click、Subscription 不處理(開信點擊自己追蹤)。 */
|
|
289
|
+
export function normalizeSesEvent(ev: unknown, snsMessageId: string, opts: { configurationSet?: string } = {}): ProviderEvent[] {
|
|
290
|
+
if (!ev || typeof ev !== 'object') return [];
|
|
291
|
+
const e = ev as SesEvent;
|
|
292
|
+
// 只收自己設定組的事件:同一個帳號或主題裡別的寄信不能影響我們的拒收名單。
|
|
293
|
+
if (opts.configurationSet && tag(e.mail?.tags, 'ses:configuration-set') !== opts.configurationSet) return [];
|
|
294
|
+
const kind = str(e.eventType) ?? str(e.notificationType);
|
|
295
|
+
const mail = e.mail ?? {};
|
|
296
|
+
const providerMessageId = str(mail.messageId);
|
|
297
|
+
if (!kind || !providerMessageId) return [];
|
|
298
|
+
const destination = (Array.isArray(mail.destination) ? mail.destination : []).map(addr).filter((a): a is string => !!a);
|
|
299
|
+
const campaign = tag(mail.tags, 'campaign');
|
|
300
|
+
const contactRaw = tag(mail.tags, 'contact');
|
|
301
|
+
// 'test'=測試信的標記,原樣保留(下游靠它不把測試信箱加進拒收名單);其餘只收數字。
|
|
302
|
+
const contact = contactRaw === 'test' || (contactRaw && /^\d{1,15}$/.test(contactRaw)) ? contactRaw : null;
|
|
303
|
+
const base = { provider: 'ses', providerMessageId, campaign, contact };
|
|
304
|
+
const make = (type: EventType, list: string[], at: unknown, extra: Partial<ProviderEvent> = {}): ProviderEvent[] =>
|
|
305
|
+
list.map((email, i) => ({
|
|
306
|
+
...base,
|
|
307
|
+
providerEventId: `ses:${snsMessageId}:${i}`.slice(0, 200),
|
|
308
|
+
type,
|
|
309
|
+
at: str(at, 40) ?? str(mail.timestamp, 40) ?? new Date().toISOString(),
|
|
310
|
+
email,
|
|
311
|
+
...extra,
|
|
312
|
+
}));
|
|
313
|
+
const listed = (v: unknown, field: string) => (Array.isArray(v) ? v.map((r) => addr(field ? (r as Record<string, unknown>)?.[field] : r)).filter((a): a is string => !!a) : []);
|
|
314
|
+
const pick = (v: unknown, field: string) => recipients(listed(v, field), destination, Array.isArray(v) && v.length > 0);
|
|
315
|
+
|
|
316
|
+
switch (kind) {
|
|
317
|
+
case 'Send':
|
|
318
|
+
return make('send', destination.slice(0, 1), mail.timestamp);
|
|
319
|
+
case 'Delivery': {
|
|
320
|
+
const d = e.delivery ?? {};
|
|
321
|
+
return make('delivery', pick(d.recipients, ''), d.timestamp);
|
|
322
|
+
}
|
|
323
|
+
case 'Bounce': {
|
|
324
|
+
const b = e.bounce ?? {};
|
|
325
|
+
const type = str(b.bounceType, 40) ?? 'Undetermined';
|
|
326
|
+
const subType = str(b.bounceSubType, 60);
|
|
327
|
+
const rs = Array.isArray(b.bouncedRecipients) ? (b.bouncedRecipients as Record<string, unknown>[]) : [];
|
|
328
|
+
const list = pick(rs, 'emailAddress');
|
|
329
|
+
return list.map((email, i) => {
|
|
330
|
+
const r = rs.find((x) => addr(x?.emailAddress) === email) ?? {};
|
|
331
|
+
const cause = type === 'Transient' ? transientCause(subType) : undefined;
|
|
332
|
+
// SES 根本沒寄(已在 SES 自己的拒收名單):記成拒收(reject),不算退信率、不進拒收名單。
|
|
333
|
+
if (subType && NOT_SENT_SUBTYPES.has(subType)) {
|
|
334
|
+
return { ...make('reject', [email], b.timestamp, { subtype: subType, skipFeedback: true, detail: { from: 'Bounce', feedbackId: str(b.feedbackId, 120) } })[0], providerEventId: `ses:${snsMessageId}:${i}` };
|
|
335
|
+
}
|
|
336
|
+
return {
|
|
337
|
+
...make('bounce', [email], b.timestamp)[0],
|
|
338
|
+
providerEventId: `ses:${snsMessageId}:${i}`,
|
|
339
|
+
// 只有 bounceType 正好是 Permanent 才是硬退信;Undetermined、Transient 都不是。
|
|
340
|
+
subtype: type === 'Permanent' ? 'Permanent' : type === 'Transient' ? 'Transient' : 'Undetermined',
|
|
341
|
+
...(cause ? { cause } : {}),
|
|
342
|
+
detail: { bounceSubType: subType, status: str(r.status, 20), diagnosticCode: str(r.diagnosticCode, 200), feedbackId: str(b.feedbackId, 120) },
|
|
343
|
+
};
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
case 'Complaint': {
|
|
347
|
+
const c = e.complaint ?? {};
|
|
348
|
+
// 「不是垃圾信」是更正,不是檢舉。
|
|
349
|
+
if (str(c.complaintFeedbackType) === 'not-spam') return [];
|
|
350
|
+
const notSentSub = str(c.complaintSubType, 60);
|
|
351
|
+
if (notSentSub && NOT_SENT_SUBTYPES.has(notSentSub)) {
|
|
352
|
+
// 同上:SES 沒寄,不是新的檢舉;記成拒收,不算檢舉率。
|
|
353
|
+
return make('reject', pick(c.complainedRecipients, 'emailAddress'), c.timestamp, { subtype: notSentSub, skipFeedback: true, detail: { from: 'Complaint', feedbackId: str(c.feedbackId, 120) } });
|
|
354
|
+
}
|
|
355
|
+
return make('complaint', pick(c.complainedRecipients, 'emailAddress'), c.timestamp, {
|
|
356
|
+
subtype: str(c.complaintFeedbackType, 40),
|
|
357
|
+
detail: { feedbackType: str(c.complaintFeedbackType, 40), complaintSubType: str(c.complaintSubType, 60), feedbackId: str(c.feedbackId, 120) },
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
case 'Reject':
|
|
361
|
+
return make('reject', destination, mail.timestamp, { subtype: 'Reject', detail: { reason: str(e.reject?.reason, 100) } });
|
|
362
|
+
case 'Rendering Failure':
|
|
363
|
+
return make('reject', destination, mail.timestamp, { subtype: 'RenderingFailure', detail: { error: str(e.failure?.errorMessage, 200) } });
|
|
364
|
+
case 'DeliveryDelay': {
|
|
365
|
+
const d = e.deliveryDelay ?? {};
|
|
366
|
+
return make('delay', pick(d.delayedRecipients, 'emailAddress'), d.timestamp, { subtype: str(d.delayType, 40) });
|
|
367
|
+
}
|
|
368
|
+
default:
|
|
369
|
+
return [];
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// ---------- HTTP 入口 ----------
|
|
374
|
+
|
|
375
|
+
export interface SesWebhookOptions extends SnsVerifyOptions {
|
|
376
|
+
/** 只收這個 SES 設定組的事件(mail.tags 的 ses:configuration-set)。強烈建議設;沒設=不檢查。 */
|
|
377
|
+
configurationSet?: string;
|
|
378
|
+
ingest?: IngestOptions;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
export interface SesWebhookResult {
|
|
382
|
+
status: number;
|
|
383
|
+
outcome: string;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** 處理 POST /webhooks/ses 的內文。回 HTTP 狀態與做了什麼(給 log、測試;不含收件人)。2xx 以外 SNS 會照重試政策重送。 */
|
|
387
|
+
export async function handleSesWebhook(db: Db, body: string, opts: SesWebhookOptions, messageTypeHeader?: string | null): Promise<SesWebhookResult> {
|
|
388
|
+
let raw: unknown;
|
|
389
|
+
try {
|
|
390
|
+
raw = JSON.parse(body);
|
|
391
|
+
} catch {
|
|
392
|
+
return { status: 400, outcome: 'bad_json' };
|
|
393
|
+
}
|
|
394
|
+
const v = await verifySnsMessage(raw, opts);
|
|
395
|
+
if (!v.ok) return { status: 403, outcome: `rejected:${v.reason}` };
|
|
396
|
+
const msg = v.msg;
|
|
397
|
+
if (messageTypeHeader && messageTypeHeader !== msg.Type) return { status: 400, outcome: 'type_mismatch' };
|
|
398
|
+
|
|
399
|
+
if (msg.Type === 'SubscriptionConfirmation') {
|
|
400
|
+
if (!isTrustedSubscribeUrl(msg.SubscribeURL, opts.region, msg.TopicArn)) return { status: 403, outcome: 'rejected:untrusted_subscribe_url' };
|
|
401
|
+
try {
|
|
402
|
+
const res = await (opts.fetcher ?? fetch)(msg.SubscribeURL!, { method: 'GET', redirect: 'manual' });
|
|
403
|
+
if (res.status !== 200) return { status: 502, outcome: `subscribe_confirm_failed:${res.status}` };
|
|
404
|
+
} catch {
|
|
405
|
+
return { status: 502, outcome: 'subscribe_confirm_failed:network' };
|
|
406
|
+
}
|
|
407
|
+
return { status: 200, outcome: 'subscription_confirmed' };
|
|
408
|
+
}
|
|
409
|
+
if (msg.Type === 'UnsubscribeConfirmation') return { status: 200, outcome: 'unsubscribe_confirmation_ignored' };
|
|
410
|
+
|
|
411
|
+
const key = `ses:${msg.MessageId}`.slice(0, 200);
|
|
412
|
+
const seen = await db.prepare('SELECT 1 AS x FROM webhook_events WHERE id = ?').bind(key).first();
|
|
413
|
+
if (seen) return { status: 200, outcome: 'repeat' };
|
|
414
|
+
let ses: unknown;
|
|
415
|
+
try {
|
|
416
|
+
ses = JSON.parse(msg.Message);
|
|
417
|
+
} catch {
|
|
418
|
+
ses = null;
|
|
419
|
+
}
|
|
420
|
+
const events = normalizeSesEvent(ses, msg.MessageId, { configurationSet: opts.configurationSet });
|
|
421
|
+
const outcomes: string[] = [];
|
|
422
|
+
for (const ev of events) outcomes.push(`${ev.type}:${await ingestEvent(db, ev, opts.ingest)}`);
|
|
423
|
+
const kind = ses && typeof ses === 'object' ? String((ses as SesEvent).eventType ?? (ses as SesEvent).notificationType ?? 'unknown').slice(0, 40) : 'unparsed';
|
|
424
|
+
await db.prepare('INSERT INTO webhook_events (id, type, received_at) VALUES (?, ?, ?) ON CONFLICT (id) DO NOTHING').bind(key, `ses.${kind}`, (opts.now ?? (() => new Date()))().toISOString()).run();
|
|
425
|
+
return { status: 200, outcome: outcomes.length ? outcomes.join(',') : `ignored:${kind}` };
|
|
426
|
+
}
|
package/src/transport.ts
ADDED
|
@@ -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
|
+
}
|