@joelincc/mailroom 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -4
- package/dist/cli/errors.js +6 -0
- package/dist/cli/main.js +60 -2
- package/dist/compose/compose.js +51 -0
- package/dist/compose/markdown.js +837 -277
- package/dist/compose/render.js +8 -3
- package/docs/composing.md +25 -4
- package/docs/export.md +2 -1
- package/docs/lists.md +4 -2
- package/docs/security-model.md +2 -0
- package/docs/ses.md +1 -1
- package/docs/tracking.md +102 -0
- package/docs/unsubscribe.md +11 -4
- package/docs/welcome.md +72 -0
- package/migrations/0008_tracking.sql +5 -0
- package/migrations/0009_welcome.sql +17 -0
- package/package.json +3 -1
- package/src/broadcast/campaigns.ts +21 -8
- package/src/broadcast/dispatch.ts +16 -3
- package/src/broadcast/events.ts +6 -3
- package/src/broadcast/worker.ts +44 -3
- package/src/cli/errors.ts +6 -0
- package/src/cli/main.ts +51 -2
- package/src/compose/compose.ts +40 -0
- package/src/compose/markdown.ts +796 -247
- package/src/compose/render.ts +8 -3
- package/src/core.ts +3 -1
- package/src/feedback.ts +21 -4
- package/src/index.ts +31 -6
- package/src/list-routes.ts +18 -5
- package/src/lists.ts +13 -2
- package/src/track.ts +409 -0
- package/src/welcome.ts +257 -0
package/src/track.ts
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
// 開信與點擊追蹤(自己追蹤,不用郵差的追蹤):
|
|
2
|
+
// GET|HEAD {TRACK_BASE_URL}/c/{券} → 302 轉到這一期信裡第 N 個連結(記一筆 click)
|
|
3
|
+
// GET|HEAD {TRACK_BASE_URL}/o/{券}.gif → 1×1 透明圖(記一筆 open)
|
|
4
|
+
//
|
|
5
|
+
// 券=「種類|期別|聯絡人|連結序號」加 HMAC 簽章。轉去哪裡不寫在券裡:用期別+序號查那一期存下的連結表,
|
|
6
|
+
// 所以只能轉到那一期信裡真的有的連結(不是開放轉址),也沒辦法拿券去換任意網址。
|
|
7
|
+
// 簽章不對、期別不存在、序號不在表裡:一律同樣的 404(不讀資料庫就先擋掉偽造的券,也不透露哪一期、哪個人存在)。
|
|
8
|
+
// 事件不帶信箱(只帶期別與聯絡人編號)。寫事件在回應之後做(waitUntil),寫失敗也照樣轉址。
|
|
9
|
+
// 聯絡人 0=測試信:照樣轉址、不記事件。
|
|
10
|
+
//
|
|
11
|
+
// 規則與依據見 docs/tracking.md。
|
|
12
|
+
|
|
13
|
+
import { detectScannerClicks, type ClickEvent } from './compose/clicks.ts';
|
|
14
|
+
import { scrubEmails } from './export.ts';
|
|
15
|
+
import type { Db } from './core.ts';
|
|
16
|
+
|
|
17
|
+
export type TrackKind = 'c' | 'o';
|
|
18
|
+
|
|
19
|
+
export interface TrackSettings {
|
|
20
|
+
/** 寄出後幾毫秒內、同一封信點了幾個不同連結就標成掃描器(同 detectScannerClicks)。 */
|
|
21
|
+
scannerWindowMs: number;
|
|
22
|
+
scannerMinLinks: number;
|
|
23
|
+
/** 來源網路(ASN)在這份清單裡的點擊直接標成掃描器。預設空:企業代理與雲端桌面的真人也可能從這些網路來,要自己評估。 */
|
|
24
|
+
scannerAsns: number[];
|
|
25
|
+
/** 來源網路在這份清單裡的開信標 prefetch=true。預設 [714](Apple 的網路;Apple 郵件隱私保護的預載從 Apple 的代理伺服器發出)。 */
|
|
26
|
+
prefetchAsns: number[];
|
|
27
|
+
/** User-Agent 含這些字(不分大小寫)的開信也標 prefetch=true。預設空。 */
|
|
28
|
+
prefetchUserAgents: string[];
|
|
29
|
+
/** 同一人同一期同一連結,幾秒內的重複點擊只記一筆(預設 60)。 */
|
|
30
|
+
clickDedupeSeconds: number;
|
|
31
|
+
/** 同一人同一期,幾秒內的重複開信只記一筆(預設 3600;預載與非預載分開算)。 */
|
|
32
|
+
openDedupeSeconds: number;
|
|
33
|
+
/** 帳本裡電子報那類的站名(=群發設定的 site),用來對到這封信的帳本列。 */
|
|
34
|
+
site: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const DEFAULT_TRACK_SETTINGS: Readonly<TrackSettings> = Object.freeze({
|
|
38
|
+
scannerWindowMs: 60_000,
|
|
39
|
+
scannerMinLinks: 3,
|
|
40
|
+
scannerAsns: [],
|
|
41
|
+
prefetchAsns: [714],
|
|
42
|
+
prefetchUserAgents: [],
|
|
43
|
+
clickDedupeSeconds: 60,
|
|
44
|
+
openDedupeSeconds: 3600,
|
|
45
|
+
site: 'newsletter',
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
const CAMPAIGN = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
|
49
|
+
const TOKEN = /^[A-Za-z0-9_-]{4,120}\.[A-Za-z0-9_-]{22}$/;
|
|
50
|
+
const enc = new TextEncoder();
|
|
51
|
+
const keyCache = new Map<string, Promise<CryptoKey>>();
|
|
52
|
+
|
|
53
|
+
function b64url(bytes: Uint8Array): string {
|
|
54
|
+
let s = '';
|
|
55
|
+
for (const b of bytes) s += String.fromCharCode(b);
|
|
56
|
+
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
57
|
+
}
|
|
58
|
+
function fromB64url(s: string): Uint8Array | null {
|
|
59
|
+
try {
|
|
60
|
+
const bin = atob(s.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (s.length % 4)) % 4));
|
|
61
|
+
return Uint8Array.from(bin, (c) => c.charCodeAt(0));
|
|
62
|
+
} catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function hmacKey(secret: string): Promise<CryptoKey> {
|
|
68
|
+
let k = keyCache.get(secret);
|
|
69
|
+
if (!k) {
|
|
70
|
+
k = crypto.subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
71
|
+
keyCache.set(secret, k);
|
|
72
|
+
}
|
|
73
|
+
return k;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function mac(secret: string, payload: string): Promise<Uint8Array> {
|
|
77
|
+
const sig = await crypto.subtle.sign('HMAC', await hmacKey(secret), enc.encode(`mailroom-track:v1:${payload}`));
|
|
78
|
+
return new Uint8Array(sig).slice(0, 16);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 追蹤鑰匙:第一把簽新券,其餘只驗證(換鑰匙過渡期)。每把至少 16 字元,太短的丟掉。 */
|
|
82
|
+
export function trackSecrets(current?: string, previous?: string): string[] {
|
|
83
|
+
// 目前的鑰匙沒設或太短=追蹤關閉(不能讓舊鑰匙補位去簽新券:換鑰匙常常就是因為舊的外洩了)。
|
|
84
|
+
const cur = (current ?? '').trim();
|
|
85
|
+
if (cur.length < 16) return [];
|
|
86
|
+
return [cur, ...(previous ?? '').split(',').map((s) => s.trim()).filter((s) => s.length >= 16)];
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface TrackClaim { kind: TrackKind; campaign: string; contact: number; index: number | null }
|
|
90
|
+
|
|
91
|
+
/** 簽一張券。index 只給點擊(1 起算)。 */
|
|
92
|
+
export async function signTrack(secret: string, claim: TrackClaim): Promise<string> {
|
|
93
|
+
if (!CAMPAIGN.test(claim.campaign) || !Number.isInteger(claim.contact) || claim.contact < 0) throw new Error('bad track claim');
|
|
94
|
+
if (claim.kind === 'c' ? !Number.isInteger(claim.index) || (claim.index as number) < 1 : claim.index !== null) throw new Error('bad track claim');
|
|
95
|
+
const payload = [claim.kind, claim.campaign, String(claim.contact), claim.kind === 'c' ? String(claim.index) : ''].join('|');
|
|
96
|
+
return `${b64url(enc.encode(payload))}.${b64url(await mac(secret, payload))}`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 驗券:任何一把鑰匙對得上才回內容;格式、簽章、內容有一點不對就回 null。 */
|
|
100
|
+
export async function verifyTrack(secrets: readonly string[], token: string, kind: TrackKind): Promise<TrackClaim | null> {
|
|
101
|
+
if (!secrets.length || typeof token !== 'string' || !TOKEN.test(token)) return null;
|
|
102
|
+
const [p, s] = token.split('.');
|
|
103
|
+
const raw = fromB64url(p);
|
|
104
|
+
const sig = fromB64url(s);
|
|
105
|
+
if (!raw || !sig || sig.length !== 16) return null;
|
|
106
|
+
let payload: string;
|
|
107
|
+
try {
|
|
108
|
+
payload = new TextDecoder('utf-8', { fatal: true, ignoreBOM: false }).decode(raw);
|
|
109
|
+
} catch {
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
let ok = false;
|
|
113
|
+
for (const secret of secrets) {
|
|
114
|
+
const want = await mac(secret, payload);
|
|
115
|
+
let diff = 0;
|
|
116
|
+
for (let i = 0; i < 16; i++) diff |= want[i] ^ sig[i];
|
|
117
|
+
if (diff === 0) ok = true;
|
|
118
|
+
}
|
|
119
|
+
if (!ok) return null;
|
|
120
|
+
const m = /^([co])\|([a-z0-9][a-z0-9-]{0,39})\|(0|[1-9]\d{0,14})\|(0|[1-9]\d{0,4})?$/.exec(payload);
|
|
121
|
+
if (!m || m[1] !== kind) return null;
|
|
122
|
+
if (kind === 'c' ? m[4] === undefined || m[4] === '0' : m[4] !== undefined) return null;
|
|
123
|
+
return { kind, campaign: m[2], contact: Number(m[3]), index: kind === 'c' ? Number(m[4]) : null };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* 給個人化用:先把內容裡用到的 {{c:N}}、{{o}} 都簽好,回傳 personalize 要的同步函式。
|
|
128
|
+
* 內容裡的序號必須在這期的連結表裡(不在=資料壞了,丟例外讓這期暫停,不寄出點了會 404 的信)。
|
|
129
|
+
*/
|
|
130
|
+
export async function trackSigner(secret: string, campaign: string, contact: number, contents: string[], linkCount: number | null): Promise<(kind: TrackKind, index?: number) => string> {
|
|
131
|
+
const indexes = new Set<number>();
|
|
132
|
+
let open = false;
|
|
133
|
+
for (const s of contents) {
|
|
134
|
+
for (const m of s.matchAll(/\{\{\s*c:(\d+)\s*\}\}/g)) indexes.add(Number(m[1]));
|
|
135
|
+
if (/\{\{\s*o\s*\}\}/.test(s)) open = true;
|
|
136
|
+
}
|
|
137
|
+
const signed = new Map<number, string>();
|
|
138
|
+
for (const i of indexes) {
|
|
139
|
+
if (linkCount !== null && (i < 1 || i > linkCount)) throw new Error(`link ${i} is not in the campaign's link table`);
|
|
140
|
+
signed.set(i, await signTrack(secret, { kind: 'c', campaign, contact, index: i }));
|
|
141
|
+
}
|
|
142
|
+
const pixel = open ? await signTrack(secret, { kind: 'o', campaign, contact, index: null }) : '';
|
|
143
|
+
return (kind, index) => {
|
|
144
|
+
if (kind === 'o') return pixel;
|
|
145
|
+
const t = signed.get(index as number);
|
|
146
|
+
if (!t) throw new Error(`link ${index} was not signed`);
|
|
147
|
+
return t;
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** 存進 campaigns.links 的形狀:序號 → 最終網址。 */
|
|
152
|
+
export interface StoredLink { index: number; url: string }
|
|
153
|
+
|
|
154
|
+
/** 連結表檢查(存草稿時用):序號 1..N 連號、網址 http(s)、不含空白控制字元、不太長。 */
|
|
155
|
+
export function checkLinks(v: unknown): StoredLink[] | null {
|
|
156
|
+
if (!Array.isArray(v) || v.length > 500) return null;
|
|
157
|
+
const out: StoredLink[] = [];
|
|
158
|
+
for (const [i, x] of v.entries()) {
|
|
159
|
+
if (!x || typeof x !== 'object') return null;
|
|
160
|
+
const { index, url } = x as Record<string, unknown>;
|
|
161
|
+
if (index !== i + 1 || typeof url !== 'string' || url.length > 2000 || !/^https?:\/\/[^\s<>"\u0000-\u001f\u007f]+$/i.test(url)) return null;
|
|
162
|
+
// 存正規化後的網址(中文路徑變成 %XX、反斜線等瀏覽器會改寫的寫法先改寫好):轉址標頭只能放 ASCII,也不留解讀不一致的空間。
|
|
163
|
+
let href: string;
|
|
164
|
+
try {
|
|
165
|
+
const u = new URL(url);
|
|
166
|
+
if (u.protocol !== 'https:' && u.protocol !== 'http:') return null;
|
|
167
|
+
href = u.href;
|
|
168
|
+
} catch {
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
if (!/^[\x21-\x7e]+$/.test(href) || href.length > 2000) return null;
|
|
172
|
+
out.push({ index, url: href });
|
|
173
|
+
}
|
|
174
|
+
return out;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// ---------- 端點 ----------
|
|
178
|
+
|
|
179
|
+
export interface TrackDeps {
|
|
180
|
+
db: Db;
|
|
181
|
+
secrets: readonly string[];
|
|
182
|
+
/** 追蹤網址的 host(小寫);請求的 host 不同就不處理(回 null 讓別的路由接)。 */
|
|
183
|
+
host: string;
|
|
184
|
+
settings: TrackSettings;
|
|
185
|
+
/** 回應之後才做的事(Worker 的 ctx.waitUntil)。沒給=當場等它做完(測試用)。 */
|
|
186
|
+
waitUntil?: (p: Promise<unknown>) => void;
|
|
187
|
+
now?: () => Date;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const GIF = Uint8Array.from(atob('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'), (c) => c.charCodeAt(0));
|
|
191
|
+
const NO_STORE = { 'cache-control': 'no-store, private', 'referrer-policy': 'no-referrer', 'x-robots-tag': 'noindex' };
|
|
192
|
+
|
|
193
|
+
function gif(head: boolean): Response {
|
|
194
|
+
return new Response(head ? null : GIF, { status: 200, headers: { ...NO_STORE, 'content-type': 'image/gif', 'content-length': String(GIF.length) } });
|
|
195
|
+
}
|
|
196
|
+
function notFoundLink(): Response {
|
|
197
|
+
return new Response('This link is not valid.', { status: 404, headers: { ...NO_STORE, 'content-type': 'text/plain; charset=utf-8' } });
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** 一期的連結表,每個執行個體快取 5 分鐘(只快取讀到的結果;期別送出後連結表不會再變)。 */
|
|
201
|
+
const linkCache = new Map<string, { at: number; links: StoredLink[] | null }>();
|
|
202
|
+
const LINK_CACHE_MS = 300_000;
|
|
203
|
+
|
|
204
|
+
async function campaignLinks(db: Db, campaign: string, nowMs: number): Promise<StoredLink[] | null> {
|
|
205
|
+
const hit = linkCache.get(campaign);
|
|
206
|
+
if (hit && nowMs - hit.at < LINK_CACHE_MS) return hit.links;
|
|
207
|
+
const row = await db.prepare('SELECT links FROM campaigns WHERE id = ?').bind(campaign).first<{ links: string | null }>();
|
|
208
|
+
let links: StoredLink[] | null = null;
|
|
209
|
+
if (row?.links) {
|
|
210
|
+
try {
|
|
211
|
+
links = checkLinks(JSON.parse(row.links));
|
|
212
|
+
} catch {
|
|
213
|
+
links = null;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (linkCache.size > 200) linkCache.clear();
|
|
217
|
+
linkCache.set(campaign, { at: nowMs, links });
|
|
218
|
+
return links;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** 測試用:清快取。 */
|
|
222
|
+
export function clearTrackCache(): void {
|
|
223
|
+
linkCache.clear();
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
interface RequestFacts { asn: number | null; ua: string; method: string }
|
|
227
|
+
|
|
228
|
+
function facts(request: Request): RequestFacts {
|
|
229
|
+
const cf = (request as unknown as { cf?: { asn?: unknown } }).cf;
|
|
230
|
+
const asn = typeof cf?.asn === 'number' && Number.isInteger(cf.asn) ? cf.asn : null;
|
|
231
|
+
return { asn, ua: (request.headers.get('user-agent') ?? '').slice(0, 200), method: request.method };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** 處理追蹤請求;不是追蹤網址就回 null。 */
|
|
235
|
+
export async function handleTrackRequest(request: Request, deps: TrackDeps): Promise<Response | null> {
|
|
236
|
+
const url = new URL(request.url);
|
|
237
|
+
if (!deps.secrets.length || !deps.host || url.hostname.toLowerCase() !== deps.host) return null;
|
|
238
|
+
const m = /^\/(c|o)\/([^/]+)$/.exec(url.pathname);
|
|
239
|
+
if (!m) return null;
|
|
240
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') return new Response('method not allowed', { status: 405, headers: { ...NO_STORE, allow: 'GET, HEAD' } });
|
|
241
|
+
const head = request.method === 'HEAD';
|
|
242
|
+
const now = (deps.now ?? (() => new Date()))();
|
|
243
|
+
const later = (p: Promise<unknown>) => {
|
|
244
|
+
const safe = p.catch((e) => console.error('track event write failed', e instanceof Error ? e.message.slice(0, 200) : 'unknown'));
|
|
245
|
+
if (deps.waitUntil) deps.waitUntil(safe);
|
|
246
|
+
return safe;
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
if (m[1] === 'o') {
|
|
250
|
+
const token = m[2].endsWith('.gif') ? m[2].slice(0, -4) : '';
|
|
251
|
+
const claim = token ? await verifyTrack(deps.secrets, token, 'o') : null;
|
|
252
|
+
// HEAD 不是讀者打開信(連結檢查器之類),不記開信。
|
|
253
|
+
if (claim && claim.contact > 0 && !head) {
|
|
254
|
+
const p = later(recordOpen(deps, claim, facts(request), now));
|
|
255
|
+
if (!deps.waitUntil) await p;
|
|
256
|
+
}
|
|
257
|
+
// 開信圖一律回圖(不論券對不對):看回應分辨不出哪張券是真的。
|
|
258
|
+
return gif(head);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const claim = await verifyTrack(deps.secrets, m[2], 'c');
|
|
262
|
+
if (!claim) return notFoundLink();
|
|
263
|
+
let links: StoredLink[] | null;
|
|
264
|
+
try {
|
|
265
|
+
links = await campaignLinks(deps.db, claim.campaign, now.getTime());
|
|
266
|
+
} catch (e) {
|
|
267
|
+
console.error('track link lookup failed', e instanceof Error ? e.message.slice(0, 200) : 'unknown');
|
|
268
|
+
return new Response('Temporarily unavailable, please try again.', { status: 503, headers: { ...NO_STORE, 'retry-after': '5', 'content-type': 'text/plain; charset=utf-8' } });
|
|
269
|
+
}
|
|
270
|
+
const link = links?.find((l) => l.index === claim.index);
|
|
271
|
+
if (!link) return notFoundLink();
|
|
272
|
+
if (!/^https?:\/\/[\x21-\x7e]+$/.test(link.url)) {
|
|
273
|
+
console.error('track link not ascii', claim.campaign, claim.index);
|
|
274
|
+
return notFoundLink();
|
|
275
|
+
}
|
|
276
|
+
if (claim.contact > 0) {
|
|
277
|
+
const p = later(recordClick(deps, claim, link, facts(request), now));
|
|
278
|
+
if (!deps.waitUntil) await p;
|
|
279
|
+
}
|
|
280
|
+
return new Response(null, { status: 302, headers: { ...NO_STORE, location: link.url } });
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// ---------- 記事件 ----------
|
|
284
|
+
|
|
285
|
+
function bucket(now: Date, seconds: number): number {
|
|
286
|
+
return Math.floor(now.getTime() / 1000 / Math.max(1, seconds));
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
async function insertEvent(deps: TrackDeps, claim: TrackClaim, type: 'click' | 'open', eventId: string, detail: Record<string, unknown>, now: Date): Promise<boolean> {
|
|
290
|
+
const r = await deps.db
|
|
291
|
+
.prepare(
|
|
292
|
+
`INSERT INTO events (provider, provider_event_id, message_id, provider_message_id, campaign_id, contact_id, type, subtype, at, detail)
|
|
293
|
+
VALUES ('self', ?, (SELECT id FROM messages WHERE site = ? AND dedupe_key = ?), NULL, ?, ?, ?, NULL, ?, ?)
|
|
294
|
+
ON CONFLICT (provider_event_id) DO NOTHING`,
|
|
295
|
+
)
|
|
296
|
+
.bind(eventId, deps.settings.site, `c:${claim.campaign}:${claim.contact}`, claim.campaign, claim.contact, type, now.toISOString(), JSON.stringify(scrubEmails(detail)).slice(0, 2000))
|
|
297
|
+
.run();
|
|
298
|
+
return (r.meta.changes ?? 0) === 1;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
async function touchMember(deps: TrackDeps, claim: TrackClaim, column: 'last_open_at' | 'last_click_at', now: Date): Promise<void> {
|
|
302
|
+
await deps.db
|
|
303
|
+
.prepare(`UPDATE list_members SET ${column} = ? WHERE contact_id = ? AND list_id = (SELECT list_id FROM campaigns WHERE id = ?) AND (${column} IS NULL OR ${column} < ?)`)
|
|
304
|
+
.bind(now.toISOString(), claim.contact, claim.campaign, now.toISOString())
|
|
305
|
+
.run();
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
export function isPrefetch(f: RequestFacts, s: TrackSettings): boolean {
|
|
309
|
+
if (f.asn !== null && s.prefetchAsns.includes(f.asn)) return true;
|
|
310
|
+
const ua = f.ua.toLowerCase();
|
|
311
|
+
return s.prefetchUserAgents.some((p) => p && ua.includes(p.toLowerCase()));
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async function recordOpen(deps: TrackDeps, claim: TrackClaim, f: RequestFacts, now: Date): Promise<void> {
|
|
315
|
+
const prefetch = isPrefetch(f, deps.settings);
|
|
316
|
+
const id = `self:o:${claim.campaign}:${claim.contact}:${prefetch ? 'p' : 'h'}:${bucket(now, deps.settings.openDedupeSeconds)}`;
|
|
317
|
+
const detail: Record<string, unknown> = { ...(prefetch ? { prefetch: true } : {}), ...(f.asn !== null ? { asn: f.asn } : {}), ...(f.ua ? { ua: f.ua } : {}) };
|
|
318
|
+
const inserted = await insertEvent(deps, claim, 'open', id, detail, now);
|
|
319
|
+
if (inserted && !prefetch) await touchMember(deps, claim, 'last_open_at', now);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async function recordClick(deps: TrackDeps, claim: TrackClaim, link: StoredLink, f: RequestFacts, now: Date): Promise<void> {
|
|
323
|
+
const s = deps.settings;
|
|
324
|
+
const id = `self:c:${claim.campaign}:${claim.contact}:${claim.index}:${bucket(now, s.clickDedupeSeconds)}`;
|
|
325
|
+
const rule = f.method === 'HEAD' ? 'head' : f.asn !== null && s.scannerAsns.includes(f.asn) ? 'asn' : null;
|
|
326
|
+
const detail: Record<string, unknown> = {
|
|
327
|
+
url: link.url, linkIndex: link.index,
|
|
328
|
+
...(rule ? { suspect: 'scanner', scannerRule: rule } : {}),
|
|
329
|
+
...(f.asn !== null ? { asn: f.asn } : {}), ...(f.ua ? { ua: f.ua } : {}),
|
|
330
|
+
};
|
|
331
|
+
const inserted = await insertEvent(deps, claim, 'click', id, detail, now);
|
|
332
|
+
if (!inserted) return;
|
|
333
|
+
await markBurst(deps, claim, now);
|
|
334
|
+
if (!rule) {
|
|
335
|
+
// 被判成掃描器的點擊不更新「最後點擊」。
|
|
336
|
+
const me = await deps.db.prepare("SELECT json_extract(detail, '$.suspect') AS s FROM events WHERE provider_event_id = ?").bind(id).first<{ s: string | null }>();
|
|
337
|
+
if (!me?.s) await touchMember(deps, claim, 'last_click_at', now);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** 寄出後的短時間內同一封信被點了好幾個不同連結:用 detectScannerClicks 的規則把這幾筆都標上 suspect='scanner'。 */
|
|
342
|
+
async function markBurst(deps: TrackDeps, claim: TrackClaim, now: Date): Promise<void> {
|
|
343
|
+
const s = deps.settings;
|
|
344
|
+
const msg = await deps.db.prepare('SELECT sent_at FROM messages WHERE site = ? AND dedupe_key = ?').bind(s.site, `c:${claim.campaign}:${claim.contact}`).first<{ sent_at: string | null }>();
|
|
345
|
+
const sentAt = msg?.sent_at ? Date.parse(msg.sent_at) : NaN;
|
|
346
|
+
if (Number.isNaN(sentAt) || now.getTime() - sentAt > s.scannerWindowMs) return;
|
|
347
|
+
const rows = (await deps.db
|
|
348
|
+
.prepare("SELECT id, at, json_extract(detail, '$.linkIndex') AS li FROM events WHERE campaign_id = ? AND contact_id = ? AND type = 'click' AND provider = 'self'")
|
|
349
|
+
.bind(claim.campaign, claim.contact)
|
|
350
|
+
.all<{ id: number; at: string; li: number | null }>()).results;
|
|
351
|
+
const clicks: ClickEvent[] = rows.filter((r) => r.li !== null).map((r) => ({ id: String(r.id), messageId: 'm', linkIndex: Number(r.li), at: Date.parse(r.at) }));
|
|
352
|
+
const flagged = detectScannerClicks(clicks, { m: sentAt }, { windowMs: s.scannerWindowMs, minDistinctLinks: s.scannerMinLinks });
|
|
353
|
+
for (const id of flagged) {
|
|
354
|
+
await deps.db
|
|
355
|
+
.prepare("UPDATE events SET detail = json_set(COALESCE(detail, '{}'), '$.suspect', 'scanner', '$.scannerRule', COALESCE(json_extract(detail, '$.scannerRule'), 'burst')) WHERE id = ? AND json_extract(detail, '$.suspect') IS NULL")
|
|
356
|
+
.bind(Number(id))
|
|
357
|
+
.run();
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// ---------- 設定 ----------
|
|
362
|
+
|
|
363
|
+
function nums(v: unknown, fallback: number[]): number[] {
|
|
364
|
+
return Array.isArray(v) && v.every((x) => Number.isInteger(x) && x > 0 && x < 2 ** 32) ? (v as number[]) : fallback;
|
|
365
|
+
}
|
|
366
|
+
function strs(v: unknown, fallback: string[]): string[] {
|
|
367
|
+
return Array.isArray(v) && v.every((x) => typeof x === 'string' && x.length > 0 && x.length <= 100) ? (v as string[]) : fallback;
|
|
368
|
+
}
|
|
369
|
+
function int(v: unknown, fallback: number, min: number, max: number): number {
|
|
370
|
+
return Number.isInteger(v) && (v as number) >= min && (v as number) <= max ? (v as number) : fallback;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** 部署端的 TRACK_CONFIG(JSON,只寫想改的欄位)+群發設定的 site。讀不懂的欄位用預設值。 */
|
|
374
|
+
export function resolveTrackSettings(raw: unknown, site?: string): TrackSettings {
|
|
375
|
+
let o: Record<string, unknown> = {};
|
|
376
|
+
if (raw && typeof raw === 'object' && !Array.isArray(raw)) o = raw as Record<string, unknown>;
|
|
377
|
+
else if (typeof raw === 'string' && raw.trim()) {
|
|
378
|
+
try {
|
|
379
|
+
const p = JSON.parse(raw);
|
|
380
|
+
if (p && typeof p === 'object' && !Array.isArray(p)) o = p;
|
|
381
|
+
else console.error('TRACK_CONFIG is not an object, using defaults');
|
|
382
|
+
} catch {
|
|
383
|
+
console.error('TRACK_CONFIG unreadable, using defaults');
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
const d = DEFAULT_TRACK_SETTINGS;
|
|
387
|
+
return {
|
|
388
|
+
scannerWindowMs: int(o.scannerWindowMs, d.scannerWindowMs, 1000, 3_600_000),
|
|
389
|
+
scannerMinLinks: int(o.scannerMinLinks, d.scannerMinLinks, 2, 50),
|
|
390
|
+
scannerAsns: nums(o.scannerAsns, d.scannerAsns),
|
|
391
|
+
prefetchAsns: nums(o.prefetchAsns, d.prefetchAsns),
|
|
392
|
+
prefetchUserAgents: strs(o.prefetchUserAgents, d.prefetchUserAgents),
|
|
393
|
+
clickDedupeSeconds: int(o.clickDedupeSeconds, d.clickDedupeSeconds, 1, 86_400),
|
|
394
|
+
openDedupeSeconds: int(o.openDedupeSeconds, d.openDedupeSeconds, 1, 86_400 * 7),
|
|
395
|
+
site: typeof site === 'string' && site ? site : d.site,
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** TRACK_BASE_URL → host(小寫);不是 https 根網址=null(追蹤關閉)。 */
|
|
400
|
+
export function trackHost(base: string | undefined): string | null {
|
|
401
|
+
if (!base) return null;
|
|
402
|
+
try {
|
|
403
|
+
const u = new URL(base);
|
|
404
|
+
if (u.protocol !== 'https:' || (u.pathname !== '/' && u.pathname !== '') || u.search || u.hash || u.username || u.password) return null;
|
|
405
|
+
return u.hostname.toLowerCase();
|
|
406
|
+
} catch {
|
|
407
|
+
return null;
|
|
408
|
+
}
|
|
409
|
+
}
|
package/src/welcome.ts
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
// 歡迎信:讀者「第一次」加入某份名單時,郵務室寄一封歡迎信。走電子報那一路(電子報郵差、電子報寄件網域、退訂兩個標頭、帳本)。
|
|
2
|
+
//
|
|
3
|
+
// 什麼時候會寄(全部都要成立):
|
|
4
|
+
// 1. 群發總開關開著(MARKETING_DOMAIN+NEWSLETTER_POSTMAN+BROADCAST Queue 都有,郵差設得起來)。關著=一封都不寄,也不排。
|
|
5
|
+
// 2. 這份名單有歡迎信、而且明確打開(welcome_mails.enabled = 1)。預設關。
|
|
6
|
+
// 3. 這次加入是讀者本人的加入動作(listSubscribe),而且他以前從來不是這份名單的成員(firstTime)。
|
|
7
|
+
// 退訂後再訂回、搬家匯入、分群寫入都不寄。
|
|
8
|
+
// 4. 寄的當下他還訂閱中、不在拒收名單、寄件網域沒有停寄、郵差健康、今天額度還有。
|
|
9
|
+
// 5. 帳本去重鍵 welcome:{名單}:{聯絡人} 沒寄過(同一人最多一封,兩個加入同時進來也只寄一封)。
|
|
10
|
+
//
|
|
11
|
+
// 內容是設定:在 Worker 外面用 compose 產好(品牌樣板在自己的設定裡),用管理入口存進 welcome_mails。引擎只附範例(docs/welcome.md)。
|
|
12
|
+
|
|
13
|
+
import { parseAddress, suppressedReason, type Db } from './core.ts';
|
|
14
|
+
import { scanPlaceholders, personalize } from './compose/personalize.ts';
|
|
15
|
+
import { unsubscribeLinks } from './unsub.ts';
|
|
16
|
+
import type { Postman, PostmanOutcome } from './broadcast/postman.ts';
|
|
17
|
+
import { localDay } from './core.ts';
|
|
18
|
+
import { subscribeMember, type ListDb, type SubscribeInput, type SubscribeResult } from './lists.ts';
|
|
19
|
+
|
|
20
|
+
export interface WelcomeInput {
|
|
21
|
+
subject: string;
|
|
22
|
+
from: string;
|
|
23
|
+
replyTo?: string;
|
|
24
|
+
html: string;
|
|
25
|
+
text: string;
|
|
26
|
+
/** {{web_url}} 的值(https),例如電子報的過刊頁。 */
|
|
27
|
+
webUrl: string;
|
|
28
|
+
/** 一定要明講:true=開始對新訂閱者寄、false=存著但不寄。 */
|
|
29
|
+
enabled: boolean;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface WelcomeRow {
|
|
33
|
+
list_id: string; subject: string; from_addr: string; reply_to: string | null; html: string; text: string;
|
|
34
|
+
web_url: string; content_hash: string; enabled: number; updated_at: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export type WelcomeMessage = { kind: 'welcome'; list: string; contact: number; queuedAt: string };
|
|
38
|
+
|
|
39
|
+
const LIST_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
|
40
|
+
const ctl = (s: string) => /[\u0000-\u001f\u007f]/.test(s);
|
|
41
|
+
/** 寄的當下暫時寄不了(網域停寄、郵差不健康、額度用完)最多等多久,過了就放棄(不補寄很舊的歡迎信)。 */
|
|
42
|
+
export const WELCOME_MAX_AGE_MS = 48 * 3600_000;
|
|
43
|
+
/** 暫時寄不了時多久後再試。 */
|
|
44
|
+
export const WELCOME_RETRY_SECONDS = 900;
|
|
45
|
+
|
|
46
|
+
async function sha256(s: string): Promise<string> {
|
|
47
|
+
const d = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s));
|
|
48
|
+
return [...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 檢查歡迎信內容。回錯誤代碼或 null。 */
|
|
52
|
+
export function checkWelcome(input: WelcomeInput, marketingDomain: string): string | null {
|
|
53
|
+
if (!input || typeof input !== 'object') return 'bad_request';
|
|
54
|
+
if (typeof input.enabled !== 'boolean') return 'enabled_required';
|
|
55
|
+
if (typeof input.subject !== 'string' || !input.subject.trim() || Array.from(input.subject).length > 80 || ctl(input.subject)) return 'bad_subject';
|
|
56
|
+
const from = parseAddress(String(input.from ?? ''));
|
|
57
|
+
if (!from || !marketingDomain || !from.addr.endsWith(`@${marketingDomain.toLowerCase()}`)) return 'bad_from';
|
|
58
|
+
if (input.replyTo !== undefined && !parseAddress(input.replyTo)) return 'bad_reply_to';
|
|
59
|
+
if (typeof input.html !== 'string' || !input.html || input.html.length > 200_000) return 'bad_html';
|
|
60
|
+
if (typeof input.text !== 'string' || !input.text || input.text.length > 100_000) return 'bad_text';
|
|
61
|
+
if (typeof input.webUrl !== 'string' || input.webUrl.length > 2000 || !/^https:\/\/[^\s<>"]+$/i.test(input.webUrl)) return 'bad_web_url';
|
|
62
|
+
for (const s of [input.html, input.text]) {
|
|
63
|
+
const p = scanPlaceholders(s);
|
|
64
|
+
if (p.unknown.length || p.unbalanced.length) return 'unknown_placeholder';
|
|
65
|
+
// 歡迎信不追蹤(沒有期別的連結表):compose 時不要給 trackBase。
|
|
66
|
+
if (p.used.has('c') || p.used.has('o')) return 'tracking_not_supported';
|
|
67
|
+
if (!p.used.has('unsubscribe_url')) return 'unsubscribe_link_missing';
|
|
68
|
+
if (p.used.has('unsubscribe_mailto')) return 'unknown_placeholder';
|
|
69
|
+
}
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 存(或改)一份名單的歡迎信。enabled 每次都要明講。 */
|
|
74
|
+
export async function saveWelcome(db: Db, list: string, input: WelcomeInput, opts: { marketingDomain: string; now?: () => Date }): Promise<{ ok: true; enabled: boolean; changed: boolean } | { ok: false; reason: string }> {
|
|
75
|
+
if (typeof list !== 'string' || !LIST_ID.test(list)) return { ok: false, reason: 'bad_list' };
|
|
76
|
+
const bad = checkWelcome(input, opts.marketingDomain);
|
|
77
|
+
if (bad) return { ok: false, reason: bad };
|
|
78
|
+
if (!(await db.prepare('SELECT id FROM lists WHERE id = ?').bind(list).first())) return { ok: false, reason: 'unknown_list' };
|
|
79
|
+
const hash = await sha256(JSON.stringify([input.subject, input.from, input.replyTo ?? '', input.html, input.text, input.webUrl]));
|
|
80
|
+
const before = await db.prepare('SELECT content_hash, enabled FROM welcome_mails WHERE list_id = ?').bind(list).first<{ content_hash: string; enabled: number }>();
|
|
81
|
+
const t = (opts.now ?? (() => new Date()))().toISOString();
|
|
82
|
+
await db
|
|
83
|
+
.prepare(
|
|
84
|
+
`INSERT INTO welcome_mails (list_id, subject, from_addr, reply_to, html, text, web_url, content_hash, enabled, updated_at)
|
|
85
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
86
|
+
ON CONFLICT (list_id) DO UPDATE SET subject = excluded.subject, from_addr = excluded.from_addr, reply_to = excluded.reply_to, html = excluded.html,
|
|
87
|
+
text = excluded.text, web_url = excluded.web_url, content_hash = excluded.content_hash, enabled = excluded.enabled, updated_at = excluded.updated_at`,
|
|
88
|
+
)
|
|
89
|
+
.bind(list, input.subject, input.from, input.replyTo ?? null, input.html, input.text, input.webUrl, hash, input.enabled ? 1 : 0, t)
|
|
90
|
+
.run();
|
|
91
|
+
return { ok: true, enabled: input.enabled, changed: !before || before.content_hash !== hash || Boolean(before.enabled) !== input.enabled };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function getWelcome(db: Db, list: string): Promise<WelcomeRow | null> {
|
|
95
|
+
if (typeof list !== 'string' || !LIST_ID.test(list)) return null;
|
|
96
|
+
return db.prepare('SELECT * FROM welcome_mails WHERE list_id = ?').bind(list).first<WelcomeRow>();
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ---------- 排信(加入時)----------
|
|
100
|
+
|
|
101
|
+
export interface WelcomeQueue { send(body: WelcomeMessage, opts?: { delaySeconds?: number }): Promise<unknown> }
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 加入成功、而且是第一次加入時呼叫。只排進 Queue(不在讀者的加入請求裡寄信);任何失敗都只記 log,不影響加入結果。
|
|
105
|
+
* @param enabled 群發總開關(呼叫端判斷);false=什麼都不做。
|
|
106
|
+
*/
|
|
107
|
+
export async function queueWelcome(db: Db, queue: WelcomeQueue | undefined, enabled: boolean, list: string, contact: number, now = new Date()): Promise<'queued' | 'off' | 'no_welcome' | 'error'> {
|
|
108
|
+
if (!enabled || !queue) return 'off';
|
|
109
|
+
try {
|
|
110
|
+
const w = await db.prepare('SELECT enabled FROM welcome_mails WHERE list_id = ?').bind(list).first<{ enabled: number }>();
|
|
111
|
+
if (!w || !w.enabled) return 'no_welcome';
|
|
112
|
+
await queue.send({ kind: 'welcome', list, contact, queuedAt: now.toISOString() }, { delaySeconds: 5 });
|
|
113
|
+
return 'queued';
|
|
114
|
+
} catch (e) {
|
|
115
|
+
console.error('welcome queue failed', e instanceof Error ? e.message.slice(0, 200) : 'unknown');
|
|
116
|
+
return 'error';
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* 內線 listSubscribe 的實作:加入名單;第一次加入時照上面的條件排歡迎信。回給呼叫端的只有加入結果(不含聯絡人編號)。
|
|
122
|
+
* @param switchOn 群發總開關(呼叫端判斷)。
|
|
123
|
+
*/
|
|
124
|
+
export async function subscribeWithWelcome(db: ListDb, input: SubscribeInput, opts: { queue?: WelcomeQueue; switchOn: boolean; now?: () => Date }): Promise<SubscribeResult> {
|
|
125
|
+
const r = await subscribeMember(db, input, opts.now);
|
|
126
|
+
if (r.status !== 'subscribed') return r;
|
|
127
|
+
if ('contactId' in r && r.firstTime) {
|
|
128
|
+
const outcome = await queueWelcome(db as unknown as Db, opts.queue, opts.switchOn, input.list, r.contactId, (opts.now ?? (() => new Date()))());
|
|
129
|
+
if (outcome === 'error') console.warn('welcome not queued', input.list);
|
|
130
|
+
}
|
|
131
|
+
return { status: 'subscribed', firstTime: r.firstTime };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// ---------- 寄信(Queue 消化時)----------
|
|
135
|
+
|
|
136
|
+
export interface WelcomeDeps {
|
|
137
|
+
db: ListDb;
|
|
138
|
+
postman: Postman;
|
|
139
|
+
/** 電子報寄件網域(小寫)。 */
|
|
140
|
+
domain: string;
|
|
141
|
+
/** 帳本站名(群發設定的 site)。 */
|
|
142
|
+
site: string;
|
|
143
|
+
utcOffsetHours: number;
|
|
144
|
+
unsub: { secrets: readonly string[]; baseUrl?: string; mailto?: string };
|
|
145
|
+
now?: () => Date;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export type WelcomeResult = { action: 'ack'; outcome: string } | { action: 'retry'; delaySeconds: number; outcome: string };
|
|
149
|
+
const ack = (outcome: string): WelcomeResult => ({ action: 'ack', outcome });
|
|
150
|
+
|
|
151
|
+
function fmt(a: { name: string | null; addr: string }): string {
|
|
152
|
+
return a.name ? `${a.name} <${a.addr}>` : a.addr;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* 名字是加入的人自己填的;歡迎信是加入一發生就寄出的自動信,名字欄可以被拿來夾帶網址或網域(「請到 evil.example 領獎」)。
|
|
157
|
+
* 名字只收允許清單裡的字元(見下);其他一律當作沒有名字(整段問候拿掉)。
|
|
158
|
+
*/
|
|
159
|
+
export function safeName(name: string | null): string | null {
|
|
160
|
+
if (typeof name !== 'string') return null;
|
|
161
|
+
// 允許清單(先 NFKC,全形句點等會變成「.」):字母、組合記號、空白、撇號、連字號;句點只准跟在單一字母後面(縮寫 J. R.)。最多 40 字。
|
|
162
|
+
const n = name.normalize('NFKC').trim();
|
|
163
|
+
if (!n || Array.from(n).length > 40) return null;
|
|
164
|
+
if (!/^[\p{L}\p{M}\s'\u2019.-]+$/u.test(n)) return null;
|
|
165
|
+
if (/(?:^|[^\p{L}])\.|\p{L}{2}\.|\.(?!\s|$)/u.test(n)) return null;
|
|
166
|
+
return n;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export async function consumeWelcome(deps: WelcomeDeps, msg: WelcomeMessage): Promise<WelcomeResult> {
|
|
170
|
+
const { db } = deps;
|
|
171
|
+
const now = (deps.now ?? (() => new Date()))();
|
|
172
|
+
if (!msg || typeof msg.list !== 'string' || !LIST_ID.test(msg.list) || !Number.isInteger(msg.contact) || msg.contact < 1) return ack('welcome_bad_message');
|
|
173
|
+
const queuedAt = Date.parse(String(msg.queuedAt));
|
|
174
|
+
const tooOld = Number.isNaN(queuedAt) || now.getTime() - queuedAt > WELCOME_MAX_AGE_MS;
|
|
175
|
+
const later = (outcome: string): WelcomeResult => (tooOld ? ack(`welcome_expired:${outcome}`) : { action: 'retry', delaySeconds: WELCOME_RETRY_SECONDS, outcome });
|
|
176
|
+
|
|
177
|
+
const w = await getWelcome(db as unknown as Db, msg.list);
|
|
178
|
+
if (!w || !w.enabled) return ack('welcome_disabled');
|
|
179
|
+
const member = await db
|
|
180
|
+
.prepare('SELECT m.status AS status, c.email AS email, c.name AS name FROM list_members m JOIN contacts c ON c.id = m.contact_id WHERE m.list_id = ? AND m.contact_id = ?')
|
|
181
|
+
.bind(msg.list, msg.contact)
|
|
182
|
+
.first<{ status: string; email: string; name: string | null }>();
|
|
183
|
+
if (!member || member.status !== 'subscribed') return ack('welcome_not_subscribed');
|
|
184
|
+
if (await suppressedReason(db as unknown as Db, member.email, 'marketing')) return ack('welcome_suppressed');
|
|
185
|
+
const key = `welcome:${msg.list}:${msg.contact}`;
|
|
186
|
+
const done = await db.prepare("SELECT status FROM messages WHERE site = ? AND dedupe_key = ?").bind(deps.site, key).first<{ status: string }>();
|
|
187
|
+
if (done && done.status !== 'failed') return ack(done.status === 'sent' ? 'welcome_duplicate' : `welcome_${done.status}`);
|
|
188
|
+
const hold = await db.prepare('SELECT id FROM domain_holds WHERE domain = ? AND released_at IS NULL LIMIT 1').bind(deps.domain).first();
|
|
189
|
+
if (hold) return later('welcome_domain_hold');
|
|
190
|
+
const day = localDay(now, deps.utcOffsetHours);
|
|
191
|
+
const health = await db.prepare('SELECT enforcement FROM throttle_days WHERE domain = ? AND day = ?').bind(deps.domain, day).first<{ enforcement: string | null }>();
|
|
192
|
+
if (health?.enforcement && health.enforcement !== 'HEALTHY' && health.enforcement !== 'UNKNOWN') return later('welcome_provider_unhealthy');
|
|
193
|
+
|
|
194
|
+
const from = parseAddress(w.from_addr);
|
|
195
|
+
if (!from || !from.addr.endsWith(`@${deps.domain}`)) return ack('welcome_bad_from');
|
|
196
|
+
const replyTo = w.reply_to ? parseAddress(w.reply_to) : null;
|
|
197
|
+
|
|
198
|
+
// 內容先組好(缺退訂設定就不寄:沒有退訂連結的信一封都不出去)。
|
|
199
|
+
let content: { html: string; text: string; headers: Record<string, string> };
|
|
200
|
+
try {
|
|
201
|
+
if (!deps.unsub.secrets.length || !deps.unsub.baseUrl) throw new Error('unsubscribe not configured');
|
|
202
|
+
const links = await unsubscribeLinks(deps.unsub.secrets, { baseUrl: deps.unsub.baseUrl, mailtoAddress: deps.unsub.mailto }, { list: msg.list, contactId: msg.contact, campaign: null });
|
|
203
|
+
content = personalize(
|
|
204
|
+
{ html: w.html, text: w.text, headers: { ...links.headers } },
|
|
205
|
+
{ name: safeName(member.name), email: member.email, web_url: w.web_url, unsubscribe_url: links.url },
|
|
206
|
+
);
|
|
207
|
+
} catch (e) {
|
|
208
|
+
console.error('welcome render failed', e instanceof Error ? e.message.slice(0, 200) : 'unknown');
|
|
209
|
+
return ack('welcome_render_error');
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// 今天的額度:跟群發共用同一個寄件網域的每日上限(先佔一格,沒寄出再還)。今天的列還沒建=群發今天還沒讀過郵差上限,晚點再試。
|
|
213
|
+
const reserved = await db.prepare('UPDATE throttle_days SET sent = sent + 1 WHERE domain = ? AND day = ? AND sent < "limit" RETURNING sent').bind(deps.domain, day).first<{ sent: number }>();
|
|
214
|
+
if (!reserved) return later('welcome_no_quota');
|
|
215
|
+
const refund = () => db.prepare('UPDATE throttle_days SET sent = MAX(sent - 1, 0) WHERE domain = ? AND day = ?').bind(deps.domain, day).run();
|
|
216
|
+
|
|
217
|
+
const iso = now.toISOString();
|
|
218
|
+
const claimed = await db
|
|
219
|
+
.prepare(
|
|
220
|
+
`INSERT INTO messages (stream, tier, site, dedupe_key, kind, to_email, from_addr, subject, status, attempts, created_at, updated_at)
|
|
221
|
+
VALUES ('marketing', 'marketing', ?, ?, 'welcome', ?, ?, ?, 'sending', 1, ?, ?)
|
|
222
|
+
ON CONFLICT (site, dedupe_key) DO UPDATE SET status = 'sending', last_error = COALESCE(messages.error, messages.last_error), error = NULL,
|
|
223
|
+
attempts = messages.attempts + 1, updated_at = excluded.updated_at
|
|
224
|
+
WHERE messages.status = 'failed'
|
|
225
|
+
RETURNING id, attempts`,
|
|
226
|
+
)
|
|
227
|
+
.bind(deps.site, key, member.email, fmt(from), w.subject, iso, iso)
|
|
228
|
+
.first<{ id: number; attempts: number }>();
|
|
229
|
+
if (!claimed) {
|
|
230
|
+
await refund();
|
|
231
|
+
return ack('welcome_duplicate');
|
|
232
|
+
}
|
|
233
|
+
let out: PostmanOutcome;
|
|
234
|
+
try {
|
|
235
|
+
out = await deps.postman.send({
|
|
236
|
+
from: fmt(from), to: member.email, subject: w.subject, html: content.html, text: content.text,
|
|
237
|
+
...(replyTo ? { replyTo: fmt(replyTo) } : {}),
|
|
238
|
+
headers: content.headers,
|
|
239
|
+
tags: { campaign: `_welcome-${msg.list}`, contact: String(msg.contact) },
|
|
240
|
+
idempotencyKey: `${deps.site}/${key}`,
|
|
241
|
+
});
|
|
242
|
+
} catch (e) {
|
|
243
|
+
// 不知道寄出沒有:帳本列留在 sending,不再自動重寄(寧可少一封也不寄兩封)。
|
|
244
|
+
console.error('welcome postman threw', e instanceof Error ? e.message.slice(0, 200) : 'unknown');
|
|
245
|
+
return ack('welcome_uncertain');
|
|
246
|
+
}
|
|
247
|
+
const t = (deps.now ?? (() => new Date()))().toISOString();
|
|
248
|
+
if (out.ok) {
|
|
249
|
+
await db.prepare("UPDATE messages SET status = 'sent', route = ?, provider_id = ?, updated_at = ?, sent_at = ? WHERE id = ?").bind(deps.postman.name, out.providerId, t, t, claimed.id).run();
|
|
250
|
+
return ack('welcome_sent');
|
|
251
|
+
}
|
|
252
|
+
await refund();
|
|
253
|
+
await db.prepare("UPDATE messages SET status = 'failed', route = ?, error = ?, updated_at = ? WHERE id = ?").bind(deps.postman.name, `${deps.postman.name} ${out.kind} ${out.error}`.slice(0, 200), t, claimed.id).run();
|
|
254
|
+
if (out.kind === 'permanent' || claimed.attempts >= 5) return ack(`welcome_failed_${out.kind}`);
|
|
255
|
+
return later(`welcome_${out.kind}`);
|
|
256
|
+
}
|
|
257
|
+
|