@softure-ai/mailing 0.1.6 → 0.1.8
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/CHANGELOG.md +34 -0
- package/README.md +108 -25
- package/dist/cli/run.d.ts +3 -1
- package/dist/cli/run.d.ts.map +1 -1
- package/dist/cli/run.js +141 -25
- package/dist/cli/run.js.map +1 -1
- package/dist/contract.d.ts +48 -8
- package/dist/contract.d.ts.map +1 -1
- package/dist/contract.js +2 -0
- package/dist/contract.js.map +1 -1
- package/dist/index.d.ts +12 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/messages/en.d.ts +2 -0
- package/dist/messages/en.d.ts.map +1 -1
- package/dist/messages/en.js +2 -0
- package/dist/messages/en.js.map +1 -1
- package/dist/messages/index.d.ts +4 -0
- package/dist/messages/index.d.ts.map +1 -1
- package/dist/messages/pl.d.ts.map +1 -1
- package/dist/messages/pl.js +2 -0
- package/dist/messages/pl.js.map +1 -1
- package/dist/next/actions.d.ts.map +1 -1
- package/dist/next/actions.js +6 -6
- package/dist/next/actions.js.map +1 -1
- package/dist/next/pages.d.ts.map +1 -1
- package/dist/next/pages.js +8 -6
- package/dist/next/pages.js.map +1 -1
- package/dist/next/route.d.ts +2 -1
- package/dist/next/route.d.ts.map +1 -1
- package/dist/next/route.js +6 -4
- package/dist/next/route.js.map +1 -1
- package/dist/options.d.ts +15 -1
- package/dist/options.d.ts.map +1 -1
- package/dist/options.js +32 -1
- package/dist/options.js.map +1 -1
- package/dist/providers/resend.d.ts.map +1 -1
- package/dist/providers/resend.js +12 -6
- package/dist/providers/resend.js.map +1 -1
- package/dist/schema.d.ts +17 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +2 -0
- package/dist/schema.js.map +1 -1
- package/dist/server/campaigns.d.ts +30 -4
- package/dist/server/campaigns.d.ts.map +1 -1
- package/dist/server/campaigns.js +67 -12
- package/dist/server/campaigns.js.map +1 -1
- package/dist/server/deliveries.d.ts +30 -2
- package/dist/server/deliveries.d.ts.map +1 -1
- package/dist/server/deliveries.js +58 -23
- package/dist/server/deliveries.js.map +1 -1
- package/dist/server/dns.d.ts +48 -1
- package/dist/server/dns.d.ts.map +1 -1
- package/dist/server/dns.js +124 -15
- package/dist/server/dns.js.map +1 -1
- package/dist/server/index.d.ts +4 -4
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +3 -3
- package/dist/server/index.js.map +1 -1
- package/dist/server/send-mail.d.ts +3 -1
- package/dist/server/send-mail.d.ts.map +1 -1
- package/dist/server/send-mail.js +18 -6
- package/dist/server/send-mail.js.map +1 -1
- package/dist/server/suppressions.d.ts +8 -6
- package/dist/server/suppressions.d.ts.map +1 -1
- package/dist/server/suppressions.js +23 -7
- package/dist/server/suppressions.js.map +1 -1
- package/dist/server/unsubscribe-link.d.ts +23 -0
- package/dist/server/unsubscribe-link.d.ts.map +1 -1
- package/dist/server/unsubscribe-link.js +30 -1
- package/dist/server/unsubscribe-link.js.map +1 -1
- package/migrations/0003_add_delivery_provider_status.sql +13 -0
- package/module.json +1 -1
- package/package.json +1 -1
- package/src/cli/run.ts +164 -29
- package/src/contract.ts +49 -6
- package/src/index.ts +8 -3
- package/src/messages/en.ts +2 -0
- package/src/messages/pl.ts +2 -0
- package/src/next/actions.ts +5 -6
- package/src/next/pages.tsx +10 -7
- package/src/next/route.ts +6 -4
- package/src/options.ts +36 -2
- package/src/providers/resend.ts +11 -7
- package/src/schema.ts +2 -0
- package/src/server/campaigns.ts +95 -17
- package/src/server/deliveries.ts +89 -29
- package/src/server/dns.ts +174 -16
- package/src/server/index.ts +17 -0
- package/src/server/send-mail.ts +30 -6
- package/src/server/suppressions.ts +23 -8
- package/src/server/unsubscribe-link.ts +41 -1
package/src/server/dns.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
// The sender domain's DNS, as receivers check it: SPF (RFC 7208), DKIM (RFC 6376) and DMARC
|
|
2
|
-
// (RFC 7489). Without all three, list mail lands in spam or is refused outright.
|
|
3
|
-
//
|
|
4
|
-
|
|
2
|
+
// (RFC 7489). Without all three, list mail lands in spam or is refused outright. On request it also
|
|
3
|
+
// holds DMARC to a required minimum, checks that the reply-to domain accepts mail (MX) and that the
|
|
4
|
+
// provider's return-path hosts resolve. The check only reads public records; it cannot see whether
|
|
5
|
+
// the provider signs with the published key.
|
|
6
|
+
import { resolveCname as resolveCnameRecords, resolveMx as resolveMxRecords, resolveTxt as resolveTxtRecords } from "node:dns/promises";
|
|
5
7
|
|
|
6
8
|
export type DnsCheckStatus = "pass" | "warn" | "fail";
|
|
7
9
|
|
|
@@ -13,6 +15,9 @@ export type DnsFinding =
|
|
|
13
15
|
| "revoked"
|
|
14
16
|
| "monitor-only"
|
|
15
17
|
| "inherited"
|
|
18
|
+
| "weak"
|
|
19
|
+
| "null-mx"
|
|
20
|
+
| "unexpected-target"
|
|
16
21
|
| "lookup-failed";
|
|
17
22
|
|
|
18
23
|
export interface DnsCheck {
|
|
@@ -29,9 +34,41 @@ export interface SenderDnsReport {
|
|
|
29
34
|
readonly spf: DnsCheck;
|
|
30
35
|
readonly dkim: DnsCheck;
|
|
31
36
|
readonly dmarc: DnsCheck;
|
|
37
|
+
/** The reply-to domain's MX, when `replyTo` was given. */
|
|
38
|
+
readonly replyTo: DnsCheck | null;
|
|
39
|
+
/** One check per `returnPath` host, in the order given. */
|
|
40
|
+
readonly returnPath: readonly DnsCheck[];
|
|
32
41
|
}
|
|
33
42
|
|
|
34
43
|
export type ResolveTxt = (hostname: string) => Promise<string[][]>;
|
|
44
|
+
export interface MxRecord {
|
|
45
|
+
readonly exchange: string;
|
|
46
|
+
readonly priority: number;
|
|
47
|
+
}
|
|
48
|
+
export type ResolveMx = (hostname: string) => Promise<MxRecord[]>;
|
|
49
|
+
export type ResolveCname = (hostname: string) => Promise<string[]>;
|
|
50
|
+
|
|
51
|
+
export type DmarcPolicy = "quarantine" | "reject";
|
|
52
|
+
export type DmarcAlignment = "r" | "s";
|
|
53
|
+
|
|
54
|
+
/** The least a DMARC record must carry; a weaker one fails as `weak`. Absent tags count as their defaults. */
|
|
55
|
+
export interface DmarcExpectation {
|
|
56
|
+
/** The policy for the checked domain: `p`, or `sp ?? p` of a parent's record. Also requires `pct` 100. */
|
|
57
|
+
readonly policy?: DmarcPolicy;
|
|
58
|
+
/** The policy for subdomains: `sp ?? p`. */
|
|
59
|
+
readonly subdomainPolicy?: DmarcPolicy;
|
|
60
|
+
/** `adkim`; absent means relaxed (`r`). */
|
|
61
|
+
readonly adkim?: DmarcAlignment;
|
|
62
|
+
/** `aspf`; absent means relaxed (`r`). */
|
|
63
|
+
readonly aspf?: DmarcAlignment;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A host the provider uses for MAIL FROM or bounces. */
|
|
67
|
+
export interface ReturnPathHost {
|
|
68
|
+
readonly host: string;
|
|
69
|
+
/** When set, a CNAME must point at this domain or under it (`rmta.net` accepts `send.forge.rmta.net`). */
|
|
70
|
+
readonly targetDomain?: string;
|
|
71
|
+
}
|
|
35
72
|
|
|
36
73
|
export interface CheckSenderDnsOptions {
|
|
37
74
|
/** DKIM selectors to look up under `_domainkey`. Default `["resend"]`, the Resend selector. */
|
|
@@ -41,22 +78,52 @@ export interface CheckSenderDnsOptions {
|
|
|
41
78
|
* return path); DMARC accepts that in relaxed alignment.
|
|
42
79
|
*/
|
|
43
80
|
readonly spfHosts?: readonly string[];
|
|
81
|
+
/** Turns a DMARC record weaker than this into a `fail` (e.g. `{ policy: "reject", adkim: "s", aspf: "s" }`). */
|
|
82
|
+
readonly expectDmarc?: DmarcExpectation;
|
|
83
|
+
/**
|
|
84
|
+
* Where replies go (an address, `Name <address>` or a domain): its domain must have MX records and at most one
|
|
85
|
+
* SPF record, or replies bounce while the sender checks pass.
|
|
86
|
+
*/
|
|
87
|
+
readonly replyTo?: string;
|
|
88
|
+
/** Hosts that must resolve as a CNAME or with MX records; `resendReturnPath(domain)` gives Resend's. */
|
|
89
|
+
readonly returnPath?: readonly ReturnPathHost[];
|
|
44
90
|
readonly resolveTxt?: ResolveTxt;
|
|
91
|
+
readonly resolveMx?: ResolveMx;
|
|
92
|
+
readonly resolveCname?: ResolveCname;
|
|
45
93
|
}
|
|
46
94
|
|
|
47
95
|
export const DEFAULT_DKIM_SELECTORS: readonly string[] = ["resend"];
|
|
48
96
|
|
|
97
|
+
/** Domain of the CNAME targets Resend publishes for its return-path hosts. */
|
|
98
|
+
export const RESEND_RETURN_PATH_DOMAIN = "rmta.net";
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Resend's return-path hosts: `send.<domain>` (MAIL FROM) and `rsend.<domain>`, CNAMEs to `*.rmta.net`. Domains
|
|
102
|
+
* set up before Resend published `rsend` have MX records on `send` and no `rsend`: check `send` alone there.
|
|
103
|
+
*/
|
|
104
|
+
export function resendReturnPath(domain: string): ReturnPathHost[] {
|
|
105
|
+
const name = normalizeHost(domain);
|
|
106
|
+
return [
|
|
107
|
+
{ host: `send.${name}`, targetDomain: RESEND_RETURN_PATH_DOMAIN },
|
|
108
|
+
{ host: `rsend.${name}`, targetDomain: RESEND_RETURN_PATH_DOMAIN },
|
|
109
|
+
];
|
|
110
|
+
}
|
|
111
|
+
|
|
49
112
|
/** Reads the SPF, DKIM and DMARC records of `domain`. Never throws: a failed lookup is a finding. */
|
|
50
113
|
export async function checkSenderDns(domain: string, options: CheckSenderDnsOptions = {}): Promise<SenderDnsReport> {
|
|
51
|
-
const name = domain
|
|
114
|
+
const name = normalizeHost(domain);
|
|
52
115
|
const resolveTxt = options.resolveTxt ?? resolveTxtRecords;
|
|
53
116
|
const lookup = (host: string) => lookupTxt(resolveTxt, host);
|
|
54
|
-
const
|
|
117
|
+
const lookupMx = (host: string) => lookupRecords(options.resolveMx ?? resolveMxRecords, host);
|
|
118
|
+
const lookupCname = (host: string) => lookupRecords(options.resolveCname ?? resolveCnameRecords, host);
|
|
119
|
+
const [spf, dkim, dmarc, replyTo, returnPath] = await Promise.all([
|
|
55
120
|
checkSpf(lookup, options.spfHosts ?? [name]),
|
|
56
121
|
checkDkim(lookup, (options.dkimSelectors ?? DEFAULT_DKIM_SELECTORS).map((selector) => `${selector}._domainkey.${name}`)),
|
|
57
|
-
checkDmarc(lookup, name),
|
|
122
|
+
checkDmarc(lookup, name, options.expectDmarc),
|
|
123
|
+
options.replyTo === undefined ? null : checkReplyPath(lookup, lookupMx, normalizeHost(getSenderDomain(options.replyTo))),
|
|
124
|
+
Promise.all((options.returnPath ?? []).map((path) => checkReturnPath(lookupCname, lookupMx, path))),
|
|
58
125
|
]);
|
|
59
|
-
return { domain: name, spf, dkim, dmarc };
|
|
126
|
+
return { domain: name, spf, dkim, dmarc, replyTo, returnPath };
|
|
60
127
|
}
|
|
61
128
|
|
|
62
129
|
/** The domain part of a sender (`Plan <hello@mail.example.com>` gives `mail.example.com`). */
|
|
@@ -69,15 +136,21 @@ export function getSenderDomain(from: string): string {
|
|
|
69
136
|
return address.slice(address.lastIndexOf("@") + 1).trim().toLowerCase();
|
|
70
137
|
}
|
|
71
138
|
|
|
139
|
+
function normalizeHost(host: string): string {
|
|
140
|
+
return host.trim().toLowerCase().replace(/\.$/, "");
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
type Answer<T> = { readonly kind: "records"; readonly records: T[] } | { readonly kind: "none" } | { readonly kind: "error" };
|
|
144
|
+
type TxtAnswer = Answer<string>;
|
|
72
145
|
type Lookup = (host: string) => Promise<TxtAnswer>;
|
|
73
|
-
type
|
|
146
|
+
type MxLookup = (host: string) => Promise<Answer<MxRecord>>;
|
|
147
|
+
type CnameLookup = (host: string) => Promise<Answer<string>>;
|
|
74
148
|
|
|
75
149
|
const NO_RECORD_CODES = new Set(["ENOTFOUND", "ENODATA", "NXDOMAIN"]);
|
|
76
150
|
|
|
77
|
-
async function
|
|
151
|
+
async function lookupRecords<T>(resolve: (host: string) => Promise<T[]>, host: string): Promise<Answer<T>> {
|
|
78
152
|
try {
|
|
79
|
-
|
|
80
|
-
const records = (await resolveTxt(host)).map((chunks) => chunks.join(""));
|
|
153
|
+
const records = await resolve(host);
|
|
81
154
|
return records.length === 0 ? { kind: "none" } : { kind: "records", records };
|
|
82
155
|
} catch (error) {
|
|
83
156
|
const code = (error as { code?: unknown } | null)?.code;
|
|
@@ -85,6 +158,15 @@ async function lookupTxt(resolveTxt: ResolveTxt, host: string): Promise<TxtAnswe
|
|
|
85
158
|
}
|
|
86
159
|
}
|
|
87
160
|
|
|
161
|
+
async function lookupTxt(resolveTxt: ResolveTxt, host: string): Promise<TxtAnswer> {
|
|
162
|
+
// A TXT record may arrive in 255-byte chunks; they form one string.
|
|
163
|
+
return lookupRecords(async (name) => (await resolveTxt(name)).map((chunks) => chunks.join("")), host);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function isSpfRecord(record: string): boolean {
|
|
167
|
+
return /^v=spf1(\s|$)/i.test(record.trim());
|
|
168
|
+
}
|
|
169
|
+
|
|
88
170
|
function startsWithTag(record: string, tag: string): boolean {
|
|
89
171
|
return record.trim().toLowerCase().startsWith(tag);
|
|
90
172
|
}
|
|
@@ -98,7 +180,7 @@ async function checkSpf(lookup: Lookup, hosts: readonly string[]): Promise<DnsCh
|
|
|
98
180
|
lookupFailed ??= host;
|
|
99
181
|
continue;
|
|
100
182
|
}
|
|
101
|
-
const records = answer.kind === "records" ? answer.records.filter(
|
|
183
|
+
const records = answer.kind === "records" ? answer.records.filter(isSpfRecord) : [];
|
|
102
184
|
if (records.length > 1) return { status: "fail", finding: "multiple", host, record: null };
|
|
103
185
|
const record = records[0];
|
|
104
186
|
if (record === undefined) continue;
|
|
@@ -129,9 +211,10 @@ async function checkDkim(lookup: Lookup, hosts: readonly string[]): Promise<DnsC
|
|
|
129
211
|
|
|
130
212
|
/**
|
|
131
213
|
* `_dmarc.<domain>`, or the nearest parent's record (the organisational domain's policy, with
|
|
132
|
-
* `sp=` for subdomains when it is set). `p=none` only reports; it protects nothing.
|
|
214
|
+
* `sp=` for subdomains when it is set). `p=none` only reports; it protects nothing. With an
|
|
215
|
+
* expectation, a record weaker than it fails as `weak`.
|
|
133
216
|
*/
|
|
134
|
-
async function checkDmarc(lookup: Lookup, domain: string): Promise<DnsCheck> {
|
|
217
|
+
async function checkDmarc(lookup: Lookup, domain: string, expected: DmarcExpectation | undefined): Promise<DnsCheck> {
|
|
135
218
|
const labels = domain.split(".");
|
|
136
219
|
const first = `_dmarc.${domain}`;
|
|
137
220
|
for (let index = 0; index <= labels.length - 2; index += 1) {
|
|
@@ -144,10 +227,85 @@ async function checkDmarc(lookup: Lookup, domain: string): Promise<DnsCheck> {
|
|
|
144
227
|
const record = records[0];
|
|
145
228
|
if (record === undefined) continue;
|
|
146
229
|
const inherited = host !== first;
|
|
147
|
-
const
|
|
148
|
-
const policy = (inherited ? (
|
|
230
|
+
const tags = readDmarcTags(record);
|
|
231
|
+
const policy = (inherited ? (tags.get("sp") ?? tags.get("p")) : tags.get("p")) ?? "none";
|
|
232
|
+
if (expected !== undefined && !meetsDmarcExpectation(tags, policy, expected)) return { status: "fail", finding: "weak", host, record };
|
|
149
233
|
if (policy === "none") return { status: "warn", finding: "monitor-only", host, record };
|
|
150
234
|
return inherited ? { status: "pass", finding: "inherited", host, record } : { status: "pass", finding: "found", host, record };
|
|
151
235
|
}
|
|
152
236
|
return { status: "fail", finding: "missing", host: first, record: null };
|
|
153
237
|
}
|
|
238
|
+
|
|
239
|
+
/** `tag=value` pairs of a DMARC record, names and values lower-cased; the first occurrence wins. */
|
|
240
|
+
function readDmarcTags(record: string): Map<string, string> {
|
|
241
|
+
const tags = new Map<string, string>();
|
|
242
|
+
for (const part of record.split(";")) {
|
|
243
|
+
const separator = part.indexOf("=");
|
|
244
|
+
if (separator === -1) continue;
|
|
245
|
+
const name = part.slice(0, separator).trim().toLowerCase();
|
|
246
|
+
if (!tags.has(name)) tags.set(name, part.slice(separator + 1).trim().toLowerCase());
|
|
247
|
+
}
|
|
248
|
+
return tags;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const POLICY_RANK: Readonly<Record<string, number>> = { none: 0, quarantine: 1, reject: 2 };
|
|
252
|
+
|
|
253
|
+
/** An unknown policy value counts as `none`, as receivers treat an invalid `p=`. */
|
|
254
|
+
function rankPolicy(policy: string | undefined): number {
|
|
255
|
+
return (policy === undefined ? undefined : POLICY_RANK[policy]) ?? 0;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function meetsAlignment(actual: string | undefined, expected: DmarcAlignment | undefined): boolean {
|
|
259
|
+
return expected !== "s" || actual === "s";
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function meetsDmarcExpectation(tags: ReadonlyMap<string, string>, policy: string, expected: DmarcExpectation): boolean {
|
|
263
|
+
if (expected.policy !== undefined) {
|
|
264
|
+
if (rankPolicy(policy) < rankPolicy(expected.policy)) return false;
|
|
265
|
+
const percent = tags.get("pct");
|
|
266
|
+
if (percent !== undefined && Number(percent) !== 100) return false;
|
|
267
|
+
}
|
|
268
|
+
if (expected.subdomainPolicy !== undefined && rankPolicy(tags.get("sp") ?? tags.get("p")) < rankPolicy(expected.subdomainPolicy)) return false;
|
|
269
|
+
return meetsAlignment(tags.get("adkim"), expected.adkim) && meetsAlignment(tags.get("aspf"), expected.aspf);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function formatMx(records: readonly MxRecord[]): string {
|
|
273
|
+
return [...records]
|
|
274
|
+
.sort((left, right) => left.priority - right.priority)
|
|
275
|
+
.map((record) => `${String(record.priority)} ${normalizeHost(record.exchange) || "."}`)
|
|
276
|
+
.join(", ");
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** A null MX (RFC 7505: one record, exchange `.`) says the domain accepts no mail. Node reports it as `""`. */
|
|
280
|
+
function isNullMx(records: readonly MxRecord[]): boolean {
|
|
281
|
+
return records.length === 1 && normalizeHost(records[0]?.exchange ?? "") === "";
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** The reply-to domain must accept mail (MX, not a null MX) and publish at most one SPF record. */
|
|
285
|
+
async function checkReplyPath(lookup: Lookup, lookupMx: MxLookup, host: string): Promise<DnsCheck> {
|
|
286
|
+
const mx = await lookupMx(host);
|
|
287
|
+
if (mx.kind === "error") return { status: "fail", finding: "lookup-failed", host, record: null };
|
|
288
|
+
if (mx.kind === "none") return { status: "fail", finding: "missing", host, record: null };
|
|
289
|
+
if (isNullMx(mx.records)) return { status: "fail", finding: "null-mx", host, record: formatMx(mx.records) };
|
|
290
|
+
const txt = await lookup(host);
|
|
291
|
+
if (txt.kind === "error") return { status: "fail", finding: "lookup-failed", host, record: null };
|
|
292
|
+
if (txt.kind === "records" && txt.records.filter(isSpfRecord).length > 1) return { status: "fail", finding: "multiple", host, record: null };
|
|
293
|
+
return { status: "pass", finding: "found", host, record: formatMx(mx.records) };
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** A CNAME (to `targetDomain` or under it, when set), else MX records. Strings, not patterns: the domain is input. */
|
|
297
|
+
async function checkReturnPath(lookupCname: CnameLookup, lookupMx: MxLookup, path: ReturnPathHost): Promise<DnsCheck> {
|
|
298
|
+
const host = normalizeHost(path.host);
|
|
299
|
+
const cname = await lookupCname(host);
|
|
300
|
+
if (cname.kind === "error") return { status: "fail", finding: "lookup-failed", host, record: null };
|
|
301
|
+
if (cname.kind === "records") {
|
|
302
|
+
const target = normalizeHost(cname.records[0] ?? "");
|
|
303
|
+
const expected = path.targetDomain === undefined ? null : normalizeHost(path.targetDomain);
|
|
304
|
+
const matches = expected === null || target === expected || target.endsWith(`.${expected}`);
|
|
305
|
+
return matches ? { status: "pass", finding: "found", host, record: target } : { status: "fail", finding: "unexpected-target", host, record: target };
|
|
306
|
+
}
|
|
307
|
+
const mx = await lookupMx(host);
|
|
308
|
+
if (mx.kind === "error") return { status: "fail", finding: "lookup-failed", host, record: null };
|
|
309
|
+
if (mx.kind === "none" || isNullMx(mx.records)) return { status: "fail", finding: "missing", host, record: null };
|
|
310
|
+
return { status: "pass", finding: "found", host, record: formatMx(mx.records) };
|
|
311
|
+
}
|
package/src/server/index.ts
CHANGED
|
@@ -7,6 +7,7 @@ export {
|
|
|
7
7
|
registerCampaign,
|
|
8
8
|
sendCampaign,
|
|
9
9
|
type CampaignErrorCode,
|
|
10
|
+
type CampaignHalt,
|
|
10
11
|
type CampaignPlan,
|
|
11
12
|
type CampaignSummary,
|
|
12
13
|
type SendCampaignOptions,
|
|
@@ -14,21 +15,32 @@ export {
|
|
|
14
15
|
export {
|
|
15
16
|
DEFAULT_MAX_ATTEMPTS,
|
|
16
17
|
DEFAULT_STALE_CLAIM_MS,
|
|
18
|
+
DEFAULT_UNCERTAIN_CLAIM_MS,
|
|
17
19
|
deliverOnce,
|
|
18
20
|
type DeliverOptions,
|
|
19
21
|
type Delivery,
|
|
20
22
|
type DeliveryContext,
|
|
21
23
|
type DeliveryOutcome,
|
|
24
|
+
type HaltingErrorCode,
|
|
22
25
|
} from "./deliveries.js";
|
|
23
26
|
export {
|
|
24
27
|
checkSenderDns,
|
|
25
28
|
DEFAULT_DKIM_SELECTORS,
|
|
26
29
|
getSenderDomain,
|
|
30
|
+
RESEND_RETURN_PATH_DOMAIN,
|
|
31
|
+
resendReturnPath,
|
|
27
32
|
type CheckSenderDnsOptions,
|
|
33
|
+
type DmarcAlignment,
|
|
34
|
+
type DmarcExpectation,
|
|
35
|
+
type DmarcPolicy,
|
|
28
36
|
type DnsCheck,
|
|
29
37
|
type DnsCheckStatus,
|
|
30
38
|
type DnsFinding,
|
|
39
|
+
type MxRecord,
|
|
40
|
+
type ResolveCname,
|
|
41
|
+
type ResolveMx,
|
|
31
42
|
type ResolveTxt,
|
|
43
|
+
type ReturnPathHost,
|
|
32
44
|
type SenderDnsReport,
|
|
33
45
|
} from "./dns.js";
|
|
34
46
|
export { checkMailingTables } from "./health.js";
|
|
@@ -39,6 +51,9 @@ export { isSuppressed, liftSuppression, suppressRecipient, unsubscribe, type Sup
|
|
|
39
51
|
export {
|
|
40
52
|
buildUnsubscribeLinks,
|
|
41
53
|
getRecipientKey,
|
|
54
|
+
getUnsubscribeLinkParams,
|
|
55
|
+
MAX_LEGACY_VALUE_LENGTH,
|
|
56
|
+
readUnsubscribeLink,
|
|
42
57
|
MIN_UNSUBSCRIBE_SECRET_LENGTH,
|
|
43
58
|
readUnsubscribeSecrets,
|
|
44
59
|
readUnsubscribeToken,
|
|
@@ -49,6 +64,8 @@ export {
|
|
|
49
64
|
UNSUBSCRIBE_SECRET_ENV,
|
|
50
65
|
verifyUnsubscribeToken,
|
|
51
66
|
type Env,
|
|
67
|
+
type LinkParams,
|
|
68
|
+
type UnsubscribeLink,
|
|
52
69
|
type UnsubscribeLinks,
|
|
53
70
|
type UnsubscribeSecrets,
|
|
54
71
|
type UnsubscribeToken,
|
package/src/server/send-mail.ts
CHANGED
|
@@ -5,7 +5,17 @@
|
|
|
5
5
|
// link in a footer and the RFC 8058 headers, and is refused for a recipient who unsubscribed.
|
|
6
6
|
import { err, ok, type SoftureConfig } from "@softure-ai/core";
|
|
7
7
|
import type { Queryable } from "@softure-ai/db";
|
|
8
|
-
import {
|
|
8
|
+
import {
|
|
9
|
+
TRANSACTIONAL_KIND,
|
|
10
|
+
type MailingErrorCode,
|
|
11
|
+
type MailProvider,
|
|
12
|
+
type OutgoingMail,
|
|
13
|
+
type ProviderFailureStatus,
|
|
14
|
+
type ProviderMessage,
|
|
15
|
+
type ProviderOutcome,
|
|
16
|
+
type SendMailOptions,
|
|
17
|
+
type SendMailResult,
|
|
18
|
+
} from "../contract.js";
|
|
9
19
|
import type { MailingMessages } from "../messages/index.js";
|
|
10
20
|
import { addHtmlFooter, addTextFooter, getListUnsubscribeHeaders } from "./list-mail.js";
|
|
11
21
|
import { getMailingModule, getMailingOptions } from "./options.js";
|
|
@@ -27,7 +37,9 @@ type MailContent = Omit<ProviderMessage, "from" | "replyTo" | "idempotencyKey">;
|
|
|
27
37
|
/**
|
|
28
38
|
* Sends `mail` and resolves with the provider's message id or a `mailing.*` code:
|
|
29
39
|
* `invalid_input` (fix the input), `rejected` (do not retry), `unavailable` (retry later with the
|
|
30
|
-
* same `idempotencyKey`), `suppressed` (a list mail to someone who unsubscribed; do not retry)
|
|
40
|
+
* same `idempotencyKey`), `suppressed` (a list mail to someone who unsubscribed; do not retry),
|
|
41
|
+
* `provider_refused` / `quota_exceeded` (the account cannot send: stop, fix or wait, then retry). A
|
|
42
|
+
* failure the provider answered with an HTTP status carries it as `httpStatus`.
|
|
31
43
|
* Throws only when the module is not enabled, or for list mail without `context.db`.
|
|
32
44
|
*/
|
|
33
45
|
export async function sendMail(context: MailContext, mail: OutgoingMail, options: SendMailOptions = {}): Promise<SendMailResult> {
|
|
@@ -54,11 +66,18 @@ export async function sendMail(context: MailContext, mail: OutgoingMail, options
|
|
|
54
66
|
if (outcome.status === "sent") {
|
|
55
67
|
return ok({ id: outcome.id, provider: provider.name });
|
|
56
68
|
}
|
|
57
|
-
const code
|
|
69
|
+
const code = FAILURE_CODES[outcome.status];
|
|
58
70
|
logFailure(provider, code, { status: outcome.httpStatus });
|
|
59
|
-
return err(code);
|
|
71
|
+
return outcome.httpStatus === undefined ? err(code) : { ...err(code), httpStatus: outcome.httpStatus };
|
|
60
72
|
}
|
|
61
73
|
|
|
74
|
+
const FAILURE_CODES: Readonly<Record<ProviderFailureStatus, MailingErrorCode>> = {
|
|
75
|
+
rejected: "mailing.rejected",
|
|
76
|
+
unavailable: "mailing.unavailable",
|
|
77
|
+
refused: "mailing.provider_refused",
|
|
78
|
+
quota_exceeded: "mailing.quota_exceeded",
|
|
79
|
+
};
|
|
80
|
+
|
|
62
81
|
type ListMailResult =
|
|
63
82
|
| { readonly ok: true; readonly value: MailContent }
|
|
64
83
|
| { readonly ok: false; readonly error: "mailing.suppressed" | "mailing.unavailable"; readonly cause: string };
|
|
@@ -130,12 +149,17 @@ function readOutcome(outcome: unknown): ProviderOutcome {
|
|
|
130
149
|
if (status === "sent") {
|
|
131
150
|
return typeof id === "string" && id !== "" ? { status, id } : { status: "unavailable" };
|
|
132
151
|
}
|
|
133
|
-
if (status === "
|
|
134
|
-
|
|
152
|
+
if (typeof status === "string" && Object.hasOwn(FAILURE_CODES, status)) {
|
|
153
|
+
const failure = status as ProviderFailureStatus;
|
|
154
|
+
return isHttpStatus(httpStatus) ? { status: failure, httpStatus } : { status: failure };
|
|
135
155
|
}
|
|
136
156
|
return { status: "unavailable" };
|
|
137
157
|
}
|
|
138
158
|
|
|
159
|
+
function isHttpStatus(value: unknown): value is number {
|
|
160
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 599;
|
|
161
|
+
}
|
|
162
|
+
|
|
139
163
|
/**
|
|
140
164
|
* The module's only log line. Deliberately takes nothing but the provider, the code, a status,
|
|
141
165
|
* field names and a fixed cause: anything added "for diagnosis" is where an address leaks first.
|
|
@@ -9,7 +9,7 @@ import { and, eq, inArray } from "drizzle-orm";
|
|
|
9
9
|
import type { SuppressionSource, UnsubscribeErrorCode } from "../contract.js";
|
|
10
10
|
import { suppressions } from "../schema.js";
|
|
11
11
|
import { getMailingOptions } from "./options.js";
|
|
12
|
-
import { getRecipientKey, readUnsubscribeSecrets, verifyUnsubscribeToken, type Env, type UnsubscribeToken } from "./unsubscribe-link.js";
|
|
12
|
+
import { getRecipientKey, readUnsubscribeSecrets, verifyUnsubscribeToken, type Env, type UnsubscribeLink, type UnsubscribeToken } from "./unsubscribe-link.js";
|
|
13
13
|
|
|
14
14
|
export type SuppressionContext = ModuleContext<Queryable>;
|
|
15
15
|
|
|
@@ -54,20 +54,22 @@ export async function liftSuppression(ctx: Pick<SuppressionContext, "db">, addre
|
|
|
54
54
|
}
|
|
55
55
|
|
|
56
56
|
/**
|
|
57
|
-
* Unsubscribes the recipient of a
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
57
|
+
* Unsubscribes the recipient of a link and runs `onUnsubscribed` in the same transaction, also when
|
|
58
|
+
* the recipient had already unsubscribed (a retried one-click heals a missed hook). A signed link
|
|
59
|
+
* (or a bare token) is checked against the secrets before the database is touched; a legacy link
|
|
60
|
+
* goes to the app's `legacyUnsubscribe.verify`, which names the address. A link that does not
|
|
61
|
+
* verify is `mailing.invalid_link`. Throws on a database failure, or when `verify` or the hook
|
|
62
|
+
* throws (nothing is stored).
|
|
61
63
|
*/
|
|
62
64
|
export async function unsubscribe(
|
|
63
65
|
ctx: SuppressionContext,
|
|
64
|
-
|
|
66
|
+
link: UnsubscribeLink | UnsubscribeToken | null,
|
|
65
67
|
source: Exclude<SuppressionSource, "operator">,
|
|
66
68
|
env: Env = process.env,
|
|
67
69
|
): Promise<Result<undefined, UnsubscribeErrorCode>> {
|
|
68
|
-
|
|
70
|
+
const recipientKey = await verifyLink(ctx, link, env);
|
|
71
|
+
if (recipientKey === null) return err("mailing.invalid_link");
|
|
69
72
|
const { onUnsubscribed } = getMailingOptions(ctx.config);
|
|
70
|
-
const { recipientKey } = token;
|
|
71
73
|
await ctx.db.transaction(async (tx) => {
|
|
72
74
|
const txCtx: SuppressionContext = { ...ctx, db: tx };
|
|
73
75
|
await recordSuppression(txCtx, recipientKey, source);
|
|
@@ -75,3 +77,16 @@ export async function unsubscribe(
|
|
|
75
77
|
});
|
|
76
78
|
return ok();
|
|
77
79
|
}
|
|
80
|
+
|
|
81
|
+
/** The recipient key a link proves, or `null` when it proves none. */
|
|
82
|
+
async function verifyLink(ctx: SuppressionContext, link: UnsubscribeLink | UnsubscribeToken | null, env: Env): Promise<string | null> {
|
|
83
|
+
if (link === null) return null;
|
|
84
|
+
if (!("scheme" in link) || link.scheme === "signed") {
|
|
85
|
+
const token = "scheme" in link ? link.token : link;
|
|
86
|
+
return verifyUnsubscribeToken(token, readUnsubscribeSecrets(env)) ? token.recipientKey : null;
|
|
87
|
+
}
|
|
88
|
+
const legacy = getMailingOptions(ctx.config).legacyUnsubscribe;
|
|
89
|
+
if (legacy === undefined) return null;
|
|
90
|
+
const address: unknown = await legacy.verify(link.values, ctx);
|
|
91
|
+
return typeof address === "string" && address.trim() !== "" ? getRecipientKey(address) : null;
|
|
92
|
+
}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// so it never reaches a log, an error or a result.
|
|
6
6
|
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
|
|
7
7
|
import type { SoftureConfig } from "@softure-ai/core";
|
|
8
|
-
import { getMailingRoutes } from "./options.js";
|
|
8
|
+
import { getMailingOptions, getMailingRoutes } from "./options.js";
|
|
9
9
|
|
|
10
10
|
/** Signs every new link and verifies. */
|
|
11
11
|
export const UNSUBSCRIBE_SECRET_ENV = "MAILING_UNSUBSCRIBE_SECRET";
|
|
@@ -101,6 +101,46 @@ export function buildUnsubscribeLinks(config: SoftureConfig, address: string, se
|
|
|
101
101
|
};
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
+
/** A legacy link's value longer than this makes the link invalid before the app's `verify` sees it. */
|
|
105
|
+
export const MAX_LEGACY_VALUE_LENGTH = 512;
|
|
106
|
+
|
|
107
|
+
/** The link a person followed: the module's signed one, or one the app sent before it adopted the module. */
|
|
108
|
+
export type UnsubscribeLink =
|
|
109
|
+
| { readonly scheme: "signed"; readonly token: UnsubscribeToken }
|
|
110
|
+
| { readonly scheme: "legacy"; readonly values: Readonly<Record<string, string>> };
|
|
111
|
+
|
|
112
|
+
/** Reads one query or form value; `URLSearchParams` and `FormData` both fit. */
|
|
113
|
+
export interface LinkParams {
|
|
114
|
+
get(name: string): unknown;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The link in a query or a form. A link with the recipient parameter (`r`) is a signed link, whatever else it
|
|
119
|
+
* carries, so a crafted URL cannot route a signed link to the app's legacy check. Without it, and with
|
|
120
|
+
* `mailing({ legacyUnsubscribe })`, a link that has every legacy parameter (non-empty, at most 512 characters) is
|
|
121
|
+
* a legacy link. Anything else is `null`. Checks no signature: `unsubscribe` does.
|
|
122
|
+
*/
|
|
123
|
+
export function readUnsubscribeLink(params: LinkParams, config: SoftureConfig): UnsubscribeLink | null {
|
|
124
|
+
if (params.get(RECIPIENT_PARAM) !== null && params.get(RECIPIENT_PARAM) !== undefined) {
|
|
125
|
+
const token = readUnsubscribeToken(params);
|
|
126
|
+
return token === null ? null : { scheme: "signed", token };
|
|
127
|
+
}
|
|
128
|
+
const legacy = getMailingOptions(config).legacyUnsubscribe;
|
|
129
|
+
if (legacy === undefined) return null;
|
|
130
|
+
const values: Record<string, string> = {};
|
|
131
|
+
for (const name of legacy.params) {
|
|
132
|
+
const value = params.get(name);
|
|
133
|
+
if (typeof value !== "string" || value === "" || value.length > MAX_LEGACY_VALUE_LENGTH) return null;
|
|
134
|
+
values[name] = value;
|
|
135
|
+
}
|
|
136
|
+
return { scheme: "legacy", values };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** The query (or form) parameters that carry `link`, to send it back to the page. */
|
|
140
|
+
export function getUnsubscribeLinkParams(link: UnsubscribeLink): Record<string, string> {
|
|
141
|
+
return link.scheme === "signed" ? { [RECIPIENT_PARAM]: link.token.recipientKey, [SIGNATURE_PARAM]: link.token.signature } : { ...link.values };
|
|
142
|
+
}
|
|
143
|
+
|
|
104
144
|
/** The token in a link's query (or a form), when both parameters are present once. */
|
|
105
145
|
export function readUnsubscribeToken(params: { get(name: string): unknown }): UnsubscribeToken | null {
|
|
106
146
|
const recipientKey = params.get(RECIPIENT_PARAM);
|