@aglyn/shared-util-email 1.0.0-beta.199 → 1.0.0-beta.201
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/package.json +3 -3
- package/src/index.d.ts +6 -0
- package/src/index.js +16 -0
- package/src/index.js.map +1 -1
- package/src/lib/email-deliverability.d.ts +200 -0
- package/src/lib/email-deliverability.js +461 -0
- package/src/lib/email-deliverability.js.map +1 -0
- package/src/lib/email-delivery-events.d.ts +16 -39
- package/src/lib/email-delivery-events.js +28 -12
- package/src/lib/email-delivery-events.js.map +1 -1
- package/src/lib/hosted-page-screen.d.ts +60 -0
- package/src/lib/hosted-page-screen.js +314 -0
- package/src/lib/hosted-page-screen.js.map +1 -0
- package/src/lib/mail-bounce.d.ts +42 -0
- package/src/lib/mail-bounce.js +108 -0
- package/src/lib/mail-bounce.js.map +1 -0
- package/src/lib/mail-gateway.d.ts +161 -0
- package/src/lib/mail-gateway.js +330 -0
- package/src/lib/mail-gateway.js.map +1 -0
- package/src/lib/outbound-phishing-screen.d.ts +220 -0
- package/src/lib/outbound-phishing-screen.js +719 -0
- package/src/lib/outbound-phishing-screen.js.map +1 -0
- package/src/lib/outbound-screen-gate.d.ts +95 -0
- package/src/lib/outbound-screen-gate.js +109 -0
- package/src/lib/outbound-screen-gate.js.map +1 -0
- package/src/lib/send-email.d.ts +79 -1
- package/src/lib/send-email.js +153 -10
- package/src/lib/send-email.js.map +1 -1
- package/src/lib/sending-domain.d.ts +22 -1
- package/src/lib/sending-domain.js +0 -95
- package/src/lib/sending-domain.js.map +1 -1
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ /*==========================================
|
|
17
|
+
* WILL THIS ADDRESS BOUNCE? — ANSWERED BEFORE THE SEND (AGL-3328).
|
|
18
|
+
*
|
|
19
|
+
* The one engine every email path asks: the Resend sender through
|
|
20
|
+
* `sendEmail`'s preflight seam, campaigns before their review count, the
|
|
21
|
+
* CRM at capture time, and Sequences at enrollment and before each send.
|
|
22
|
+
* It answers from three free facts and nothing else:
|
|
23
|
+
*
|
|
24
|
+
* 1. **The address itself** — its syntax, a typo'd provider domain
|
|
25
|
+
* (`gmial.com`, which is SUGGESTED, never corrected), a disposable
|
|
26
|
+
* domain, a role address (`info@`), which warns for bulk and cold mail
|
|
27
|
+
* only.
|
|
28
|
+
* 2. **The domain's MX** — no MX at all, RFC 7505's null MX (`.`), or no MX
|
|
29
|
+
* but an address record, which RFC 5321 §5.1 still delivers to and so
|
|
30
|
+
* only warns.
|
|
31
|
+
* 3. **The gateway's history with the sending domain** — see
|
|
32
|
+
* `mail-gateway.ts`: a gateway that refused this sender twice lately
|
|
33
|
+
* holds the next BULK send into it.
|
|
34
|
+
*
|
|
35
|
+
* Never an SMTP `RCPT TO` probe. A probe is a connection to the recipient's
|
|
36
|
+
* server that sends nothing, which is exactly what a directory-harvest
|
|
37
|
+
* attack looks like, and gateways list the probing IP for it. Nor a paid
|
|
38
|
+
* verification API: the free checks are the whole of this module.
|
|
39
|
+
*
|
|
40
|
+
* ## The two severities that stop mail, and who they may stop
|
|
41
|
+
*
|
|
42
|
+
* - **refuse** — the domain takes no mail. Every purpose, transactional
|
|
43
|
+
* included: a password reset to a domain with no MX is a hard bounce
|
|
44
|
+
* charged to the sending domain, and nobody receives it either way.
|
|
45
|
+
* - **hold** — the gateway refused this sender twice. BULK and COLD mail
|
|
46
|
+
* only. Mail the recipient asked for (a password reset, a receipt, a
|
|
47
|
+
* booking confirmation) is never held for a gateway: the person is
|
|
48
|
+
* waiting for it, and one more refusal costs less than their not getting
|
|
49
|
+
* it.
|
|
50
|
+
*
|
|
51
|
+
* A public mailbox provider is never refused for its MX. `gmail.com` has MX
|
|
52
|
+
* records; a resolver that says otherwise is having a bad minute, and a
|
|
53
|
+
* refusal there would suppress real people.
|
|
54
|
+
*
|
|
55
|
+
* ## Pure
|
|
56
|
+
*
|
|
57
|
+
* DNS is handed in as a {@link MailDnsResolver}. This library's barrel
|
|
58
|
+
* reaches the browser, so `node:dns` belongs to the server layer that
|
|
59
|
+
* installs the preflight — `@aglyn/tenant-data-admin`.
|
|
60
|
+
*==========================================*/ import { classifyMailGateway, MAIL_DOMAIN_INTEL_TTL_MS, MAIL_DOMAIN_NEGATIVE_TTL_MS, mailGatewayHolds, mailGatewayHoldSentence, normalizeMailHost } from "./mail-gateway.js";
|
|
61
|
+
/*==========================================
|
|
62
|
+
* THE ADDRESS
|
|
63
|
+
*==========================================*/ /** RFC 1035's ceiling on a name, which no real domain reaches. */ const DOMAIN_MAX = 253;
|
|
64
|
+
/** A label: letters, digits and hyphens, not starting or ending on a hyphen. */ const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
65
|
+
/** The local part a mailbox provider accepts in practice: RFC 5322's dot-atom. */ const LOCAL_PART = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*$/;
|
|
66
|
+
/** An address as the checks read it: trimmed and lowercased, or `null` when it is not one. */ export function normalizeDeliverabilityEmail(value) {
|
|
67
|
+
const address = String(value != null ? value : '').trim().toLowerCase();
|
|
68
|
+
const at = address.lastIndexOf('@');
|
|
69
|
+
if (at < 1 || at === address.length - 1 || address.length > 254) return null;
|
|
70
|
+
const local = address.slice(0, at);
|
|
71
|
+
const domain = address.slice(at + 1);
|
|
72
|
+
if (local.length > 64 || !LOCAL_PART.test(local)) return null;
|
|
73
|
+
if (!isDeliverabilityDomain(domain)) return null;
|
|
74
|
+
return address;
|
|
75
|
+
}
|
|
76
|
+
/** Whether a value is a domain with at least two labels and a non-numeric top level. */ export function isDeliverabilityDomain(value) {
|
|
77
|
+
const domain = String(value != null ? value : '');
|
|
78
|
+
if (!domain || domain.length > DOMAIN_MAX) return false;
|
|
79
|
+
const labels = domain.split('.');
|
|
80
|
+
if (labels.length < 2 || !labels.every((label)=>LABEL.test(label))) return false;
|
|
81
|
+
return !/^\d+$/.test(labels[labels.length - 1]);
|
|
82
|
+
}
|
|
83
|
+
/** The domain of an address, lowercased, or `null` for a value that is not one. */ export function emailAddressDomain(email) {
|
|
84
|
+
const address = normalizeDeliverabilityEmail(email);
|
|
85
|
+
return address ? address.slice(address.lastIndexOf('@') + 1) : null;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The mailboxes a company's shared inbox answers as rather than a person.
|
|
89
|
+
* Legal to mail and often read, but a cold email or a campaign sent there
|
|
90
|
+
* reaches nobody who asked for it, and a spam report from a shared inbox is
|
|
91
|
+
* a report from the whole company.
|
|
92
|
+
*/ const ROLE_LOCAL_PARTS = new Set(// A word list rather than quoted strings: `marketing` is also a plugin's
|
|
93
|
+
// id, and `check:plugin-domain-in-core` reads a quoted one as a plugin's
|
|
94
|
+
// domain leaking into shared code — which a mailbox name is not.
|
|
95
|
+
('abuse accounts admin administrator billing careers contact enquiries ' + 'help hello hr info inquiries jobs mail marketing media news no-reply ' + 'noreply office postmaster press privacy sales security service support ' + 'team webmaster').split(' '));
|
|
96
|
+
/** Whether an address is a role mailbox (`info@`, `sales@`), read before any `+tag`. */ export function isRoleEmailAddress(email) {
|
|
97
|
+
const address = normalizeDeliverabilityEmail(email);
|
|
98
|
+
if (!address) return false;
|
|
99
|
+
const local = address.slice(0, address.lastIndexOf('@')).split('+')[0];
|
|
100
|
+
return ROLE_LOCAL_PARTS.has(local);
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Domains that hand out a mailbox that expires. Not a complete list — no
|
|
104
|
+
* list is — but the ones a signup form actually meets.
|
|
105
|
+
*/ const DISPOSABLE_DOMAINS = new Set([
|
|
106
|
+
'10minutemail.com',
|
|
107
|
+
'20minutemail.com',
|
|
108
|
+
'burnermail.io',
|
|
109
|
+
'discard.email',
|
|
110
|
+
'dispostable.com',
|
|
111
|
+
'emailondeck.com',
|
|
112
|
+
'fakeinbox.com',
|
|
113
|
+
'getairmail.com',
|
|
114
|
+
'getnada.com',
|
|
115
|
+
'guerrillamail.com',
|
|
116
|
+
'guerrillamail.net',
|
|
117
|
+
'guerrillamail.org',
|
|
118
|
+
'guerrillamailblock.com',
|
|
119
|
+
'maildrop.cc',
|
|
120
|
+
'mailinator.com',
|
|
121
|
+
'mailinator.net',
|
|
122
|
+
'mailnesia.com',
|
|
123
|
+
'mintemail.com',
|
|
124
|
+
'mohmal.com',
|
|
125
|
+
'mytemp.email',
|
|
126
|
+
'sharklasers.com',
|
|
127
|
+
'spamgourmet.com',
|
|
128
|
+
'temp-mail.org',
|
|
129
|
+
'tempail.com',
|
|
130
|
+
'tempmail.com',
|
|
131
|
+
'tempmailo.com',
|
|
132
|
+
'tempr.email',
|
|
133
|
+
'throwawaymail.com',
|
|
134
|
+
'trashmail.com',
|
|
135
|
+
'trashmail.de',
|
|
136
|
+
'yopmail.com',
|
|
137
|
+
'yopmail.net'
|
|
138
|
+
]);
|
|
139
|
+
/** Whether a domain is a disposable-mailbox provider. */ export function isDisposableEmailDomain(domain) {
|
|
140
|
+
return DISPOSABLE_DOMAINS.has(normalizeMailHost(domain));
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* The providers a mistyped domain is compared against. Long labels only: a
|
|
144
|
+
* three-letter label (`aol`, `msn`) is one keystroke from dozens of real
|
|
145
|
+
* domains, and a suggestion there would be noise.
|
|
146
|
+
*/ const TYPO_TARGETS = [
|
|
147
|
+
'gmail.com',
|
|
148
|
+
'googlemail.com',
|
|
149
|
+
'yahoo.com',
|
|
150
|
+
'hotmail.com',
|
|
151
|
+
'outlook.com',
|
|
152
|
+
'icloud.com',
|
|
153
|
+
'comcast.net',
|
|
154
|
+
'protonmail.com',
|
|
155
|
+
'verizon.net',
|
|
156
|
+
'sbcglobal.net',
|
|
157
|
+
'bellsouth.net'
|
|
158
|
+
];
|
|
159
|
+
/** Real providers one keystroke from a target, which must never be "corrected". */ const TYPO_EXEMPT = new Set([
|
|
160
|
+
'mail.com',
|
|
161
|
+
'gmx.com',
|
|
162
|
+
'ymail.com',
|
|
163
|
+
'email.com',
|
|
164
|
+
'hotmail.co.uk',
|
|
165
|
+
'yahoo.co.uk',
|
|
166
|
+
'outlook.fr'
|
|
167
|
+
]);
|
|
168
|
+
/** Top-level domains that are a slip of `com` or `net`. */ const TLD_SLIPS = {
|
|
169
|
+
co: 'com',
|
|
170
|
+
con: 'com',
|
|
171
|
+
cm: 'com',
|
|
172
|
+
om: 'com',
|
|
173
|
+
comm: 'com',
|
|
174
|
+
cmo: 'com',
|
|
175
|
+
ocm: 'com',
|
|
176
|
+
vom: 'com',
|
|
177
|
+
xom: 'com',
|
|
178
|
+
cpm: 'com',
|
|
179
|
+
coom: 'com',
|
|
180
|
+
ne: 'net',
|
|
181
|
+
nte: 'net',
|
|
182
|
+
ner: 'net',
|
|
183
|
+
nett: 'net'
|
|
184
|
+
};
|
|
185
|
+
/** Damerau–Levenshtein distance, stopping early above 1: only "one slip" matters here. */ function withinOneEdit(a, b) {
|
|
186
|
+
if (a === b) return true;
|
|
187
|
+
if (Math.abs(a.length - b.length) > 1) return false;
|
|
188
|
+
if (a.length === b.length) {
|
|
189
|
+
const diffs = [];
|
|
190
|
+
for(let index = 0; index < a.length; index += 1){
|
|
191
|
+
if (a[index] !== b[index]) diffs.push(index);
|
|
192
|
+
if (diffs.length > 2) return false;
|
|
193
|
+
}
|
|
194
|
+
if (diffs.length === 1) return true;
|
|
195
|
+
// One transposition of neighbors: `gmial` for `gmail`.
|
|
196
|
+
return diffs.length === 2 && diffs[1] === diffs[0] + 1 && a[diffs[0]] === b[diffs[1]] && a[diffs[1]] === b[diffs[0]];
|
|
197
|
+
}
|
|
198
|
+
const [longer, shorter] = a.length > b.length ? [
|
|
199
|
+
a,
|
|
200
|
+
b
|
|
201
|
+
] : [
|
|
202
|
+
b,
|
|
203
|
+
a
|
|
204
|
+
];
|
|
205
|
+
for(let index = 0; index < longer.length; index += 1){
|
|
206
|
+
if (longer.slice(0, index) + longer.slice(index + 1) === shorter) return true;
|
|
207
|
+
}
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* The provider a domain most likely meant, or `null` — a SUGGESTION a
|
|
212
|
+
* surface may offer, never a correction applied: `gmial.com` may be a real
|
|
213
|
+
* domain somebody owns, and changing an address a person typed is sending
|
|
214
|
+
* their mail to someone else.
|
|
215
|
+
*/ export function suggestEmailDomain(domain) {
|
|
216
|
+
const name = normalizeMailHost(domain);
|
|
217
|
+
if (!name || TYPO_EXEMPT.has(name) || TYPO_TARGETS.includes(name)) return null;
|
|
218
|
+
const dot = name.lastIndexOf('.');
|
|
219
|
+
if (dot < 1) return null;
|
|
220
|
+
const label = name.slice(0, dot);
|
|
221
|
+
const tld = name.slice(dot + 1);
|
|
222
|
+
for (const target of TYPO_TARGETS){
|
|
223
|
+
const targetDot = target.lastIndexOf('.');
|
|
224
|
+
const targetLabel = target.slice(0, targetDot);
|
|
225
|
+
const targetTld = target.slice(targetDot + 1);
|
|
226
|
+
if (label === targetLabel && TLD_SLIPS[tld] === targetTld) return target;
|
|
227
|
+
if (tld === targetTld && label.length >= 4 && withinOneEdit(label, targetLabel)) return target;
|
|
228
|
+
}
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
export const MAIL_DOMAIN_STATUSES = [
|
|
232
|
+
'mx',
|
|
233
|
+
'implicit_mx',
|
|
234
|
+
'null_mx',
|
|
235
|
+
'no_mx'
|
|
236
|
+
];
|
|
237
|
+
/** Whether a status means the domain takes no mail. */ export function mailDomainRefusesMail(status) {
|
|
238
|
+
return status === 'no_mx' || status === 'null_mx';
|
|
239
|
+
}
|
|
240
|
+
/** How long an answer is trusted: a week for a domain that takes mail, a day for one that does not. */ export function mailDomainIntelTtlMs(status) {
|
|
241
|
+
return mailDomainRefusesMail(status) ? MAIL_DOMAIN_NEGATIVE_TTL_MS : MAIL_DOMAIN_INTEL_TTL_MS;
|
|
242
|
+
}
|
|
243
|
+
/** Whether a cached answer is still trusted at `nowMs`. */ export function isMailDomainIntelFresh(intel, nowMs) {
|
|
244
|
+
return Boolean(intel) && intel.resolvedAtMs + mailDomainIntelTtlMs(intel.status) > nowMs;
|
|
245
|
+
}
|
|
246
|
+
/** The resolver's codes that mean "this domain has no such record", as opposed to "I could not ask". */ const NO_RECORD_CODES = new Set([
|
|
247
|
+
'ENOTFOUND',
|
|
248
|
+
'ENODATA',
|
|
249
|
+
'NXDOMAIN',
|
|
250
|
+
'NOTFOUND'
|
|
251
|
+
]);
|
|
252
|
+
/** Whether a resolver rejection is an answer ("no such record") rather than a failure to get one. */ export function isNoRecordDnsError(error) {
|
|
253
|
+
var _ref;
|
|
254
|
+
return NO_RECORD_CODES.has(String((_ref = error == null ? void 0 : error.code) != null ? _ref : '').toUpperCase());
|
|
255
|
+
}
|
|
256
|
+
/** A stored answer in its model shape, or `null` for no document or an unreadable one. */ export function readStoredMailDomainIntel(id, data) {
|
|
257
|
+
if (!data) return null;
|
|
258
|
+
const status = MAIL_DOMAIN_STATUSES.includes(data['status']) ? data['status'] : null;
|
|
259
|
+
if (!status) return null;
|
|
260
|
+
const mx = Array.isArray(data['mx']) ? data['mx'].filter((entry)=>typeof entry === 'string') : [];
|
|
261
|
+
const resolvedAtMs = typeof data['resolvedAtMs'] === 'number' && Number.isFinite(data['resolvedAtMs']) ? data['resolvedAtMs'] : 0;
|
|
262
|
+
return {
|
|
263
|
+
domain: typeof data['domain'] === 'string' && data['domain'] ? data['domain'] : id,
|
|
264
|
+
status,
|
|
265
|
+
mx,
|
|
266
|
+
gateway: status === 'mx' ? classifyMailGateway(mx) : status === 'implicit_mx' ? 'other' : 'none',
|
|
267
|
+
resolvedAtMs
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* A domain's mail setup, looked up — see {@link MailDomainStatus}. Rejects
|
|
272
|
+
* when the resolver could not answer, and the caller decides what a missing
|
|
273
|
+
* answer means; every path here reads it as "unknown" and sends.
|
|
274
|
+
*/ export async function resolveMailDomain(resolver, domain, nowMs) {
|
|
275
|
+
let records;
|
|
276
|
+
try {
|
|
277
|
+
records = await resolver.resolveMx(domain);
|
|
278
|
+
} catch (error) {
|
|
279
|
+
if (!isNoRecordDnsError(error)) throw error;
|
|
280
|
+
records = [];
|
|
281
|
+
}
|
|
282
|
+
const exchanges = [
|
|
283
|
+
...records != null ? records : []
|
|
284
|
+
].filter((record)=>record && typeof record.exchange === 'string').sort((a, b)=>(Number(a.priority) || 0) - (Number(b.priority) || 0)).map((record)=>normalizeMailHost(record.exchange));
|
|
285
|
+
const real = exchanges.filter((exchange)=>exchange && exchange !== '.');
|
|
286
|
+
if (real.length) {
|
|
287
|
+
return {
|
|
288
|
+
domain,
|
|
289
|
+
status: 'mx',
|
|
290
|
+
mx: real,
|
|
291
|
+
gateway: classifyMailGateway(real),
|
|
292
|
+
resolvedAtMs: nowMs
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
// Records that are all "." (or empty, as Node reports a null MX) are RFC
|
|
296
|
+
// 7505's null MX: the domain says it takes no mail, whatever its A says.
|
|
297
|
+
if (exchanges.length) return {
|
|
298
|
+
domain,
|
|
299
|
+
status: 'null_mx',
|
|
300
|
+
mx: [],
|
|
301
|
+
gateway: 'none',
|
|
302
|
+
resolvedAtMs: nowMs
|
|
303
|
+
};
|
|
304
|
+
if (resolver.resolveAddress) {
|
|
305
|
+
let addressed;
|
|
306
|
+
try {
|
|
307
|
+
addressed = await resolver.resolveAddress(domain);
|
|
308
|
+
} catch (error) {
|
|
309
|
+
if (!isNoRecordDnsError(error)) throw error;
|
|
310
|
+
addressed = false;
|
|
311
|
+
}
|
|
312
|
+
if (addressed) return {
|
|
313
|
+
domain,
|
|
314
|
+
status: 'implicit_mx',
|
|
315
|
+
mx: [],
|
|
316
|
+
gateway: 'other',
|
|
317
|
+
resolvedAtMs: nowMs
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
return {
|
|
321
|
+
domain,
|
|
322
|
+
status: 'no_mx',
|
|
323
|
+
mx: [],
|
|
324
|
+
gateway: 'none',
|
|
325
|
+
resolvedAtMs: nowMs
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
const SEVERITY_RANK = {
|
|
329
|
+
refuse: 0,
|
|
330
|
+
hold: 1,
|
|
331
|
+
warn: 2
|
|
332
|
+
};
|
|
333
|
+
/** The whole verdict for one address — see the module note. */ export function assessEmailDeliverability(input) {
|
|
334
|
+
var _input_intel, _input_gateway;
|
|
335
|
+
const email = normalizeDeliverabilityEmail(input.email);
|
|
336
|
+
if (!email) {
|
|
337
|
+
var _input_email;
|
|
338
|
+
return {
|
|
339
|
+
email: null,
|
|
340
|
+
domain: null,
|
|
341
|
+
outcome: 'refused',
|
|
342
|
+
findings: [
|
|
343
|
+
{
|
|
344
|
+
code: 'invalid_syntax',
|
|
345
|
+
severity: 'refuse',
|
|
346
|
+
message: `${String((_input_email = input.email) != null ? _input_email : '').trim() || 'This'} is not an email address.`
|
|
347
|
+
}
|
|
348
|
+
],
|
|
349
|
+
intel: null,
|
|
350
|
+
gateway: null
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
const domain = email.slice(email.lastIndexOf('@') + 1);
|
|
354
|
+
const findings = [];
|
|
355
|
+
const bulk = input.purpose !== 'transactional';
|
|
356
|
+
const intel = (_input_intel = input.intel) != null ? _input_intel : null;
|
|
357
|
+
if (intel && !input.publicMailbox) {
|
|
358
|
+
if (intel.status === 'no_mx') {
|
|
359
|
+
findings.push({
|
|
360
|
+
code: 'no_mx',
|
|
361
|
+
severity: 'refuse',
|
|
362
|
+
message: `${domain} has no mail server, so ${email} would bounce.`
|
|
363
|
+
});
|
|
364
|
+
} else if (intel.status === 'null_mx') {
|
|
365
|
+
findings.push({
|
|
366
|
+
code: 'null_mx',
|
|
367
|
+
severity: 'refuse',
|
|
368
|
+
message: `${domain} publishes a null MX record: it says it accepts no email, so ${email} would bounce.`
|
|
369
|
+
});
|
|
370
|
+
} else if (intel.status === 'implicit_mx') {
|
|
371
|
+
findings.push({
|
|
372
|
+
code: 'implicit_mx',
|
|
373
|
+
severity: 'warn',
|
|
374
|
+
message: `${domain} has no MX record. Mail may still reach its web server's address, but most domains like this never set up email.`
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
const suggestion = suggestEmailDomain(domain);
|
|
379
|
+
if (suggestion) {
|
|
380
|
+
const local = email.slice(0, email.lastIndexOf('@'));
|
|
381
|
+
findings.push({
|
|
382
|
+
code: 'typo_domain',
|
|
383
|
+
severity: 'warn',
|
|
384
|
+
message: `Did you mean ${local}@${suggestion}? ${domain} looks like a typo.`,
|
|
385
|
+
suggestion: `${local}@${suggestion}`
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
if (isDisposableEmailDomain(domain)) {
|
|
389
|
+
findings.push({
|
|
390
|
+
code: 'disposable_domain',
|
|
391
|
+
severity: 'warn',
|
|
392
|
+
message: `${domain} hands out mailboxes that expire, so this address may stop working soon.`
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
if (bulk && isRoleEmailAddress(email)) {
|
|
396
|
+
findings.push({
|
|
397
|
+
code: 'role_address',
|
|
398
|
+
severity: 'warn',
|
|
399
|
+
message: `${email} is a shared role inbox rather than a person, which marketing and cold mail should avoid.`
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
const gateway = (_input_gateway = input.gateway) != null ? _input_gateway : null;
|
|
403
|
+
if (bulk && gateway && input.holdReleased !== true && mailGatewayHolds(gateway)) {
|
|
404
|
+
findings.push({
|
|
405
|
+
code: 'gateway_held',
|
|
406
|
+
severity: 'hold',
|
|
407
|
+
message: `${mailGatewayHoldSentence(gateway.gateway, gateway.blocked30)}, so bulk mail to ${domain} is held.`
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
findings.sort((a, b)=>SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity]);
|
|
411
|
+
const outcome = findings.some((finding)=>finding.severity === 'refuse') ? 'refused' : findings.some((finding)=>finding.severity === 'hold') ? 'held' : intel ? 'deliverable' : 'unchecked';
|
|
412
|
+
return {
|
|
413
|
+
email,
|
|
414
|
+
domain,
|
|
415
|
+
outcome,
|
|
416
|
+
findings,
|
|
417
|
+
intel,
|
|
418
|
+
gateway
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
/** The finding that decided a refusal or a hold, or `null` when nothing stops the address. */ export function decidingDeliverabilityFinding(verdict) {
|
|
422
|
+
var _verdict_findings_find;
|
|
423
|
+
return (_verdict_findings_find = verdict.findings.find((finding)=>finding.severity !== 'warn')) != null ? _verdict_findings_find : null;
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* What a bulk send's review says about the addresses the checks took out,
|
|
427
|
+
* or `null` when they took out nobody: "3 recipients excluded: no mail
|
|
428
|
+
* server · 2 behind a gateway that refused this sender".
|
|
429
|
+
*/ export function deliverabilityExclusionSummary(counts) {
|
|
430
|
+
const noMailServer = Math.max(0, Math.floor(Number(counts == null ? void 0 : counts.noMailServer) || 0));
|
|
431
|
+
const gatewayHeld = Math.max(0, Math.floor(Number(counts == null ? void 0 : counts.gatewayHeld) || 0));
|
|
432
|
+
const total = noMailServer + gatewayHeld;
|
|
433
|
+
if (!total) return null;
|
|
434
|
+
const parts = [
|
|
435
|
+
...noMailServer ? [
|
|
436
|
+
`${noMailServer.toLocaleString('en-US')} no mail server`
|
|
437
|
+
] : [],
|
|
438
|
+
...gatewayHeld ? [
|
|
439
|
+
`${gatewayHeld.toLocaleString('en-US')} behind a gateway that refused this sender`
|
|
440
|
+
] : []
|
|
441
|
+
];
|
|
442
|
+
return `${total.toLocaleString('en-US')} ${total === 1 ? 'recipient' : 'recipients'} excluded: ${parts.join(' · ')}`;
|
|
443
|
+
}
|
|
444
|
+
let installedPreflight = null;
|
|
445
|
+
/** Installs the durable preflight. Called once, from `@aglyn/tenant-data-admin`. */ export function setEmailDeliverabilityPreflight(preflight) {
|
|
446
|
+
installedPreflight = preflight;
|
|
447
|
+
}
|
|
448
|
+
/** The installed preflight, or `null` when nothing has been installed. */ export function getEmailDeliverabilityPreflight() {
|
|
449
|
+
return installedPreflight;
|
|
450
|
+
}
|
|
451
|
+
/** Test seam: forget any installed preflight. */ export function resetEmailDeliverabilityPreflightForTests() {
|
|
452
|
+
installedPreflight = null;
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* How long `sendEmail` waits for the preflight before sending anyway. A
|
|
456
|
+
* cold lookup is one DNS round trip and one document read; a preflight
|
|
457
|
+
* slower than this is an outage on the control, and a control outage must
|
|
458
|
+
* not become a mail outage.
|
|
459
|
+
*/ export const EMAIL_DELIVERABILITY_PREFLIGHT_TIMEOUT_MS = 2500;
|
|
460
|
+
|
|
461
|
+
//# sourceMappingURL=email-deliverability.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/shared/util/email/src/lib/email-deliverability.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * WILL THIS ADDRESS BOUNCE? — ANSWERED BEFORE THE SEND (AGL-3328).\n *\n * The one engine every email path asks: the Resend sender through\n * `sendEmail`'s preflight seam, campaigns before their review count, the\n * CRM at capture time, and Sequences at enrollment and before each send.\n * It answers from three free facts and nothing else:\n *\n * 1. **The address itself** — its syntax, a typo'd provider domain\n * (`gmial.com`, which is SUGGESTED, never corrected), a disposable\n * domain, a role address (`info@`), which warns for bulk and cold mail\n * only.\n * 2. **The domain's MX** — no MX at all, RFC 7505's null MX (`.`), or no MX\n * but an address record, which RFC 5321 §5.1 still delivers to and so\n * only warns.\n * 3. **The gateway's history with the sending domain** — see\n * `mail-gateway.ts`: a gateway that refused this sender twice lately\n * holds the next BULK send into it.\n *\n * Never an SMTP `RCPT TO` probe. A probe is a connection to the recipient's\n * server that sends nothing, which is exactly what a directory-harvest\n * attack looks like, and gateways list the probing IP for it. Nor a paid\n * verification API: the free checks are the whole of this module.\n *\n * ## The two severities that stop mail, and who they may stop\n *\n * - **refuse** — the domain takes no mail. Every purpose, transactional\n * included: a password reset to a domain with no MX is a hard bounce\n * charged to the sending domain, and nobody receives it either way.\n * - **hold** — the gateway refused this sender twice. BULK and COLD mail\n * only. Mail the recipient asked for (a password reset, a receipt, a\n * booking confirmation) is never held for a gateway: the person is\n * waiting for it, and one more refusal costs less than their not getting\n * it.\n *\n * A public mailbox provider is never refused for its MX. `gmail.com` has MX\n * records; a resolver that says otherwise is having a bad minute, and a\n * refusal there would suppress real people.\n *\n * ## Pure\n *\n * DNS is handed in as a {@link MailDnsResolver}. This library's barrel\n * reaches the browser, so `node:dns` belongs to the server layer that\n * installs the preflight — `@aglyn/tenant-data-admin`.\n *==========================================*/\n\nimport {\n classifyMailGateway,\n MAIL_DOMAIN_INTEL_TTL_MS,\n MAIL_DOMAIN_NEGATIVE_TTL_MS,\n type MailGateway,\n type MailGatewayStanding,\n mailGatewayHolds,\n mailGatewayHoldSentence,\n normalizeMailHost,\n} from './mail-gateway'\n\n/*==========================================\n * THE ADDRESS\n *==========================================*/\n\n/** RFC 1035's ceiling on a name, which no real domain reaches. */\nconst DOMAIN_MAX = 253\n\n/** A label: letters, digits and hyphens, not starting or ending on a hyphen. */\nconst LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/\n\n/** The local part a mailbox provider accepts in practice: RFC 5322's dot-atom. */\nconst LOCAL_PART = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*$/\n\n/** An address as the checks read it: trimmed and lowercased, or `null` when it is not one. */\nexport function normalizeDeliverabilityEmail(value: unknown): string | null {\n const address = String(value ?? '')\n .trim()\n .toLowerCase()\n const at = address.lastIndexOf('@')\n if (at < 1 || at === address.length - 1 || address.length > 254) return null\n const local = address.slice(0, at)\n const domain = address.slice(at + 1)\n if (local.length > 64 || !LOCAL_PART.test(local)) return null\n if (!isDeliverabilityDomain(domain)) return null\n return address\n}\n\n/** Whether a value is a domain with at least two labels and a non-numeric top level. */\nexport function isDeliverabilityDomain(value: unknown): boolean {\n const domain = String(value ?? '')\n if (!domain || domain.length > DOMAIN_MAX) return false\n const labels = domain.split('.')\n if (labels.length < 2 || !labels.every((label) => LABEL.test(label))) return false\n return !/^\\d+$/.test(labels[labels.length - 1])\n}\n\n/** The domain of an address, lowercased, or `null` for a value that is not one. */\nexport function emailAddressDomain(email: unknown): string | null {\n const address = normalizeDeliverabilityEmail(email)\n return address ? address.slice(address.lastIndexOf('@') + 1) : null\n}\n\n/**\n * The mailboxes a company's shared inbox answers as rather than a person.\n * Legal to mail and often read, but a cold email or a campaign sent there\n * reaches nobody who asked for it, and a spam report from a shared inbox is\n * a report from the whole company.\n */\nconst ROLE_LOCAL_PARTS: ReadonlySet<string> = new Set(\n // A word list rather than quoted strings: `marketing` is also a plugin's\n // id, and `check:plugin-domain-in-core` reads a quoted one as a plugin's\n // domain leaking into shared code — which a mailbox name is not.\n (\n 'abuse accounts admin administrator billing careers contact enquiries ' +\n 'help hello hr info inquiries jobs mail marketing media news no-reply ' +\n 'noreply office postmaster press privacy sales security service support ' +\n 'team webmaster'\n ).split(' '),\n)\n\n/** Whether an address is a role mailbox (`info@`, `sales@`), read before any `+tag`. */\nexport function isRoleEmailAddress(email: unknown): boolean {\n const address = normalizeDeliverabilityEmail(email)\n if (!address) return false\n const local = address.slice(0, address.lastIndexOf('@')).split('+')[0]\n return ROLE_LOCAL_PARTS.has(local)\n}\n\n/**\n * Domains that hand out a mailbox that expires. Not a complete list — no\n * list is — but the ones a signup form actually meets.\n */\nconst DISPOSABLE_DOMAINS: ReadonlySet<string> = new Set([\n '10minutemail.com',\n '20minutemail.com',\n 'burnermail.io',\n 'discard.email',\n 'dispostable.com',\n 'emailondeck.com',\n 'fakeinbox.com',\n 'getairmail.com',\n 'getnada.com',\n 'guerrillamail.com',\n 'guerrillamail.net',\n 'guerrillamail.org',\n 'guerrillamailblock.com',\n 'maildrop.cc',\n 'mailinator.com',\n 'mailinator.net',\n 'mailnesia.com',\n 'mintemail.com',\n 'mohmal.com',\n 'mytemp.email',\n 'sharklasers.com',\n 'spamgourmet.com',\n 'temp-mail.org',\n 'tempail.com',\n 'tempmail.com',\n 'tempmailo.com',\n 'tempr.email',\n 'throwawaymail.com',\n 'trashmail.com',\n 'trashmail.de',\n 'yopmail.com',\n 'yopmail.net',\n])\n\n/** Whether a domain is a disposable-mailbox provider. */\nexport function isDisposableEmailDomain(domain: unknown): boolean {\n return DISPOSABLE_DOMAINS.has(normalizeMailHost(domain))\n}\n\n/**\n * The providers a mistyped domain is compared against. Long labels only: a\n * three-letter label (`aol`, `msn`) is one keystroke from dozens of real\n * domains, and a suggestion there would be noise.\n */\nconst TYPO_TARGETS: readonly string[] = [\n 'gmail.com',\n 'googlemail.com',\n 'yahoo.com',\n 'hotmail.com',\n 'outlook.com',\n 'icloud.com',\n 'comcast.net',\n 'protonmail.com',\n 'verizon.net',\n 'sbcglobal.net',\n 'bellsouth.net',\n]\n\n/** Real providers one keystroke from a target, which must never be \"corrected\". */\nconst TYPO_EXEMPT: ReadonlySet<string> = new Set([\n 'mail.com',\n 'gmx.com',\n 'ymail.com',\n 'email.com',\n 'hotmail.co.uk',\n 'yahoo.co.uk',\n 'outlook.fr',\n])\n\n/** Top-level domains that are a slip of `com` or `net`. */\nconst TLD_SLIPS: Readonly<Record<string, string>> = {\n co: 'com',\n con: 'com',\n cm: 'com',\n om: 'com',\n comm: 'com',\n cmo: 'com',\n ocm: 'com',\n vom: 'com',\n xom: 'com',\n cpm: 'com',\n coom: 'com',\n ne: 'net',\n nte: 'net',\n ner: 'net',\n nett: 'net',\n}\n\n/** Damerau–Levenshtein distance, stopping early above 1: only \"one slip\" matters here. */\nfunction withinOneEdit(a: string, b: string): boolean {\n if (a === b) return true\n if (Math.abs(a.length - b.length) > 1) return false\n if (a.length === b.length) {\n const diffs: number[] = []\n for (let index = 0; index < a.length; index += 1) {\n if (a[index] !== b[index]) diffs.push(index)\n if (diffs.length > 2) return false\n }\n if (diffs.length === 1) return true\n // One transposition of neighbors: `gmial` for `gmail`.\n return (\n diffs.length === 2 &&\n diffs[1] === diffs[0] + 1 &&\n a[diffs[0]] === b[diffs[1]] &&\n a[diffs[1]] === b[diffs[0]]\n )\n }\n const [longer, shorter] = a.length > b.length ? [a, b] : [b, a]\n for (let index = 0; index < longer.length; index += 1) {\n if (longer.slice(0, index) + longer.slice(index + 1) === shorter) return true\n }\n return false\n}\n\n/**\n * The provider a domain most likely meant, or `null` — a SUGGESTION a\n * surface may offer, never a correction applied: `gmial.com` may be a real\n * domain somebody owns, and changing an address a person typed is sending\n * their mail to someone else.\n */\nexport function suggestEmailDomain(domain: unknown): string | null {\n const name = normalizeMailHost(domain)\n if (!name || TYPO_EXEMPT.has(name) || TYPO_TARGETS.includes(name)) return null\n const dot = name.lastIndexOf('.')\n if (dot < 1) return null\n const label = name.slice(0, dot)\n const tld = name.slice(dot + 1)\n for (const target of TYPO_TARGETS) {\n const targetDot = target.lastIndexOf('.')\n const targetLabel = target.slice(0, targetDot)\n const targetTld = target.slice(targetDot + 1)\n if (label === targetLabel && TLD_SLIPS[tld] === targetTld) return target\n if (tld === targetTld && label.length >= 4 && withinOneEdit(label, targetLabel)) return target\n }\n return null\n}\n\n/*==========================================\n * THE DOMAIN'S MX\n *==========================================*/\n\n/** One MX record as a resolver answers it. */\nexport interface MailMxRecord {\n exchange: string\n priority: number\n}\n\n/**\n * The DNS the checks read, handed in by the server layer.\n *\n * `resolveMx` resolves the domain's MX records. A domain that publishes\n * none resolves `[]` or rejects with a `code` of `ENOTFOUND`, `ENODATA` or\n * `NXDOMAIN` — Node's own convention — and any other rejection is a\n * resolver that could not answer, which the checks read as \"unknown\" and\n * never as \"no MX\".\n *\n * `resolveAddress`, when given, answers whether the domain has an address\n * record (A or AAAA): the implicit MX a domain with no MX is still\n * delivered to. Omitted, a domain with no MX reads as `no_mx`.\n */\nexport interface MailDnsResolver {\n resolveMx(domain: string): Promise<ReadonlyArray<MailMxRecord>>\n resolveAddress?(domain: string): Promise<boolean>\n}\n\n/**\n * What a domain's DNS says about receiving mail.\n *\n * - `mx` — it publishes MX records.\n * - `implicit_mx` — no MX, but an address record, which RFC 5321 §5.1 still\n * delivers to. Deliverable; warned, because it is usually a domain whose\n * mail was never set up.\n * - `null_mx` — RFC 7505's `MX 0 .`: the domain says outright it takes no mail.\n * - `no_mx` — no MX and no address record: nothing to deliver to.\n */\nexport type MailDomainStatus = 'mx' | 'implicit_mx' | 'null_mx' | 'no_mx'\n\n/** One domain's answer, as the platform cache stores it. */\nexport interface MailDomainIntel {\n domain: string\n status: MailDomainStatus\n /** The MX exchanges, lowest preference first; empty for every status but `mx`. */\n mx: string[]\n gateway: MailGateway\n /** When the domain was looked up; trusted for {@link mailDomainIntelTtlMs}. */\n resolvedAtMs: number\n}\n\nexport const MAIL_DOMAIN_STATUSES: readonly MailDomainStatus[] = ['mx', 'implicit_mx', 'null_mx', 'no_mx']\n\n/** Whether a status means the domain takes no mail. */\nexport function mailDomainRefusesMail(status: MailDomainStatus | null | undefined): boolean {\n return status === 'no_mx' || status === 'null_mx'\n}\n\n/** How long an answer is trusted: a week for a domain that takes mail, a day for one that does not. */\nexport function mailDomainIntelTtlMs(status: MailDomainStatus): number {\n return mailDomainRefusesMail(status) ? MAIL_DOMAIN_NEGATIVE_TTL_MS : MAIL_DOMAIN_INTEL_TTL_MS\n}\n\n/** Whether a cached answer is still trusted at `nowMs`. */\nexport function isMailDomainIntelFresh(intel: MailDomainIntel | null | undefined, nowMs: number): boolean {\n return Boolean(intel) && intel.resolvedAtMs + mailDomainIntelTtlMs(intel.status) > nowMs\n}\n\n/** The resolver's codes that mean \"this domain has no such record\", as opposed to \"I could not ask\". */\nconst NO_RECORD_CODES = new Set(['ENOTFOUND', 'ENODATA', 'NXDOMAIN', 'NOTFOUND'])\n\n/** Whether a resolver rejection is an answer (\"no such record\") rather than a failure to get one. */\nexport function isNoRecordDnsError(error: unknown): boolean {\n return NO_RECORD_CODES.has(String((error as { code?: unknown })?.code ?? '').toUpperCase())\n}\n\n/** A stored answer in its model shape, or `null` for no document or an unreadable one. */\nexport function readStoredMailDomainIntel(\n id: string,\n data: Record<string, unknown> | null | undefined,\n): MailDomainIntel | null {\n if (!data) return null\n const status = (MAIL_DOMAIN_STATUSES as readonly unknown[]).includes(data['status'])\n ? (data['status'] as MailDomainStatus)\n : null\n if (!status) return null\n const mx = Array.isArray(data['mx']) ? data['mx'].filter((entry): entry is string => typeof entry === 'string') : []\n const resolvedAtMs = typeof data['resolvedAtMs'] === 'number' && Number.isFinite(data['resolvedAtMs']) ? data['resolvedAtMs'] : 0\n return {\n domain: typeof data['domain'] === 'string' && data['domain'] ? data['domain'] : id,\n status,\n mx,\n gateway: status === 'mx' ? classifyMailGateway(mx) : status === 'implicit_mx' ? 'other' : 'none',\n resolvedAtMs,\n }\n}\n\n/**\n * A domain's mail setup, looked up — see {@link MailDomainStatus}. Rejects\n * when the resolver could not answer, and the caller decides what a missing\n * answer means; every path here reads it as \"unknown\" and sends.\n */\nexport async function resolveMailDomain(\n resolver: MailDnsResolver,\n domain: string,\n nowMs: number,\n): Promise<MailDomainIntel> {\n let records: ReadonlyArray<MailMxRecord>\n try {\n records = await resolver.resolveMx(domain)\n } catch (error) {\n if (!isNoRecordDnsError(error)) throw error\n records = []\n }\n const exchanges = [...(records ?? [])]\n .filter((record) => record && typeof record.exchange === 'string')\n .sort((a, b) => (Number(a.priority) || 0) - (Number(b.priority) || 0))\n .map((record) => normalizeMailHost(record.exchange))\n const real = exchanges.filter((exchange) => exchange && exchange !== '.')\n if (real.length) {\n return { domain, status: 'mx', mx: real, gateway: classifyMailGateway(real), resolvedAtMs: nowMs }\n }\n // Records that are all \".\" (or empty, as Node reports a null MX) are RFC\n // 7505's null MX: the domain says it takes no mail, whatever its A says.\n if (exchanges.length) return { domain, status: 'null_mx', mx: [], gateway: 'none', resolvedAtMs: nowMs }\n if (resolver.resolveAddress) {\n let addressed: boolean\n try {\n addressed = await resolver.resolveAddress(domain)\n } catch (error) {\n if (!isNoRecordDnsError(error)) throw error\n addressed = false\n }\n if (addressed) return { domain, status: 'implicit_mx', mx: [], gateway: 'other', resolvedAtMs: nowMs }\n }\n return { domain, status: 'no_mx', mx: [], gateway: 'none', resolvedAtMs: nowMs }\n}\n\n/*==========================================\n * THE VERDICT\n *==========================================*/\n\n/**\n * Who a message is for, which decides what may stop it — see the module\n * note. `transactional` is mail the recipient asked for; `bulk` is a\n * campaign, a workflow's marketing step, a sweep; `cold` is a sequence to\n * somebody who has not written to the sender.\n */\nexport type EmailSendPurpose = 'transactional' | 'bulk' | 'cold'\n\nexport type EmailDeliverabilityCode =\n | 'invalid_syntax'\n | 'no_mx'\n | 'null_mx'\n | 'implicit_mx'\n | 'typo_domain'\n | 'disposable_domain'\n | 'role_address'\n | 'gateway_held'\n\nexport type EmailDeliverabilitySeverity = 'refuse' | 'hold' | 'warn'\n\nexport interface EmailDeliverabilityFinding {\n code: EmailDeliverabilityCode\n severity: EmailDeliverabilitySeverity\n /** A sentence a surface shows as is. */\n message: string\n /** `typo_domain` only: the address with the suggested domain. Never applied for the person. */\n suggestion?: string\n}\n\n/**\n * What the checks conclude, worst first: `refused` (never sent), `held`\n * (bulk and cold mail wait for a person), `deliverable` (nothing stops it,\n * warnings or not), `unchecked` (the MX could not be read, so nothing is\n * known — and nothing is stopped).\n */\nexport type EmailDeliverabilityOutcome = 'refused' | 'held' | 'deliverable' | 'unchecked'\n\nexport interface EmailDeliverabilityVerdict {\n /** The address, normalized, or `null` when it is not one. */\n email: string | null\n domain: string | null\n outcome: EmailDeliverabilityOutcome\n findings: EmailDeliverabilityFinding[]\n intel: MailDomainIntel | null\n gateway: MailGatewayStanding | null\n}\n\nexport interface EmailDeliverabilityInput {\n email: unknown\n purpose: EmailSendPurpose\n /** The domain's MX answer; `null` or absent when it could not be read. */\n intel?: MailDomainIntel | null\n /** The gateway's standing with the sending domain, when the caller read the ledger. */\n gateway?: MailGatewayStanding | null\n /**\n * The domain is a public mailbox provider (`gmail.com`), which is never\n * refused for its MX. The list lives with the CRM's, so the caller asks.\n */\n publicMailbox?: boolean\n /** A person already released the gateway hold for this address. */\n holdReleased?: boolean\n}\n\nconst SEVERITY_RANK: Record<EmailDeliverabilitySeverity, number> = { refuse: 0, hold: 1, warn: 2 }\n\n/** The whole verdict for one address — see the module note. */\nexport function assessEmailDeliverability(input: EmailDeliverabilityInput): EmailDeliverabilityVerdict {\n const email = normalizeDeliverabilityEmail(input.email)\n if (!email) {\n return {\n email: null,\n domain: null,\n outcome: 'refused',\n findings: [\n {\n code: 'invalid_syntax',\n severity: 'refuse',\n message: `${String(input.email ?? '').trim() || 'This'} is not an email address.`,\n },\n ],\n intel: null,\n gateway: null,\n }\n }\n const domain = email.slice(email.lastIndexOf('@') + 1)\n const findings: EmailDeliverabilityFinding[] = []\n const bulk = input.purpose !== 'transactional'\n const intel = input.intel ?? null\n\n if (intel && !input.publicMailbox) {\n if (intel.status === 'no_mx') {\n findings.push({\n code: 'no_mx',\n severity: 'refuse',\n message: `${domain} has no mail server, so ${email} would bounce.`,\n })\n } else if (intel.status === 'null_mx') {\n findings.push({\n code: 'null_mx',\n severity: 'refuse',\n message: `${domain} publishes a null MX record: it says it accepts no email, so ${email} would bounce.`,\n })\n } else if (intel.status === 'implicit_mx') {\n findings.push({\n code: 'implicit_mx',\n severity: 'warn',\n message: `${domain} has no MX record. Mail may still reach its web server's address, but most domains like this never set up email.`,\n })\n }\n }\n\n const suggestion = suggestEmailDomain(domain)\n if (suggestion) {\n const local = email.slice(0, email.lastIndexOf('@'))\n findings.push({\n code: 'typo_domain',\n severity: 'warn',\n message: `Did you mean ${local}@${suggestion}? ${domain} looks like a typo.`,\n suggestion: `${local}@${suggestion}`,\n })\n }\n if (isDisposableEmailDomain(domain)) {\n findings.push({\n code: 'disposable_domain',\n severity: 'warn',\n message: `${domain} hands out mailboxes that expire, so this address may stop working soon.`,\n })\n }\n if (bulk && isRoleEmailAddress(email)) {\n findings.push({\n code: 'role_address',\n severity: 'warn',\n message: `${email} is a shared role inbox rather than a person, which marketing and cold mail should avoid.`,\n })\n }\n\n const gateway = input.gateway ?? null\n if (bulk && gateway && input.holdReleased !== true && mailGatewayHolds(gateway)) {\n findings.push({\n code: 'gateway_held',\n severity: 'hold',\n message: `${mailGatewayHoldSentence(gateway.gateway, gateway.blocked30)}, so bulk mail to ${domain} is held.`,\n })\n }\n\n findings.sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity])\n const outcome: EmailDeliverabilityOutcome = findings.some((finding) => finding.severity === 'refuse')\n ? 'refused'\n : findings.some((finding) => finding.severity === 'hold')\n ? 'held'\n : intel\n ? 'deliverable'\n : 'unchecked'\n return { email, domain, outcome, findings, intel, gateway }\n}\n\n/** The finding that decided a refusal or a hold, or `null` when nothing stops the address. */\nexport function decidingDeliverabilityFinding(verdict: EmailDeliverabilityVerdict): EmailDeliverabilityFinding | null {\n return verdict.findings.find((finding) => finding.severity !== 'warn') ?? null\n}\n\n/**\n * What a bulk send's review says about the addresses the checks took out,\n * or `null` when they took out nobody: \"3 recipients excluded: no mail\n * server · 2 behind a gateway that refused this sender\".\n */\nexport function deliverabilityExclusionSummary(counts: {\n noMailServer?: number | null\n gatewayHeld?: number | null\n}): string | null {\n const noMailServer = Math.max(0, Math.floor(Number(counts?.noMailServer) || 0))\n const gatewayHeld = Math.max(0, Math.floor(Number(counts?.gatewayHeld) || 0))\n const total = noMailServer + gatewayHeld\n if (!total) return null\n const parts = [\n ...(noMailServer ? [`${noMailServer.toLocaleString('en-US')} no mail server`] : []),\n ...(gatewayHeld ? [`${gatewayHeld.toLocaleString('en-US')} behind a gateway that refused this sender`] : []),\n ]\n return `${total.toLocaleString('en-US')} ${total === 1 ? 'recipient' : 'recipients'} excluded: ${parts.join(' · ')}`\n}\n\n/*==========================================\n * THE SEAM ON `sendEmail`\n *\n * `sendEmail` lives in this library and the store it would need lives in\n * `@aglyn/tenant-data-admin`, which imports this one — so the durable half\n * reaches the send by injection, the way the send-rate governor and the\n * marketing gate do. Nothing installed is nothing checked: a deployment\n * without the server layer sends as it always did.\n *==========================================*/\n\n/** What `sendEmail` asks before a message leaves. */\nexport interface EmailDeliverabilityPreflightRequest {\n /** The recipients, normalized and lowercased. */\n recipients: string[]\n purpose: EmailSendPurpose\n /** The domain the message leaves from, or `null` when it could not be read. */\n sendingDomain: string | null\n /**\n * Whose reputation the sending domain is: a site's own verified domain\n * (`custom`), the pooled tenant identity (`shared`), or Aglyn's own\n * (`platform`). The last two are learned at platform level, where a block\n * hurts every tenant.\n */\n sendingSource: 'custom' | 'shared' | 'platform'\n context?: string\n hostId?: string | null\n}\n\nexport interface EmailDeliverabilityPreflightVerdict {\n /** Recipients whose domain takes no mail. Never sent, whatever the purpose. */\n refused: Array<{ email: string; code: EmailDeliverabilityCode; reason: string }>\n /** Recipients behind a gateway that refused this sender twice. Bulk and cold mail only. */\n held: Array<{ email: string; gateway: MailGateway; reason: string }>\n}\n\nexport type EmailDeliverabilityPreflight = (\n request: EmailDeliverabilityPreflightRequest,\n) => Promise<EmailDeliverabilityPreflightVerdict>\n\nlet installedPreflight: EmailDeliverabilityPreflight | null = null\n\n/** Installs the durable preflight. Called once, from `@aglyn/tenant-data-admin`. */\nexport function setEmailDeliverabilityPreflight(preflight: EmailDeliverabilityPreflight | null): void {\n installedPreflight = preflight\n}\n\n/** The installed preflight, or `null` when nothing has been installed. */\nexport function getEmailDeliverabilityPreflight(): EmailDeliverabilityPreflight | null {\n return installedPreflight\n}\n\n/** Test seam: forget any installed preflight. */\nexport function resetEmailDeliverabilityPreflightForTests(): void {\n installedPreflight = null\n}\n\n/**\n * How long `sendEmail` waits for the preflight before sending anyway. A\n * cold lookup is one DNS round trip and one document read; a preflight\n * slower than this is an outage on the control, and a control outage must\n * not become a mail outage.\n */\nexport const EMAIL_DELIVERABILITY_PREFLIGHT_TIMEOUT_MS = 2_500\n"],"names":["classifyMailGateway","MAIL_DOMAIN_INTEL_TTL_MS","MAIL_DOMAIN_NEGATIVE_TTL_MS","mailGatewayHolds","mailGatewayHoldSentence","normalizeMailHost","DOMAIN_MAX","LABEL","LOCAL_PART","normalizeDeliverabilityEmail","value","address","String","trim","toLowerCase","at","lastIndexOf","length","local","slice","domain","test","isDeliverabilityDomain","labels","split","every","label","emailAddressDomain","email","ROLE_LOCAL_PARTS","Set","isRoleEmailAddress","has","DISPOSABLE_DOMAINS","isDisposableEmailDomain","TYPO_TARGETS","TYPO_EXEMPT","TLD_SLIPS","co","con","cm","om","comm","cmo","ocm","vom","xom","cpm","coom","ne","nte","ner","nett","withinOneEdit","a","b","Math","abs","diffs","index","push","longer","shorter","suggestEmailDomain","name","includes","dot","tld","target","targetDot","targetLabel","targetTld","MAIL_DOMAIN_STATUSES","mailDomainRefusesMail","status","mailDomainIntelTtlMs","isMailDomainIntelFresh","intel","nowMs","Boolean","resolvedAtMs","NO_RECORD_CODES","isNoRecordDnsError","error","code","toUpperCase","readStoredMailDomainIntel","id","data","mx","Array","isArray","filter","entry","Number","isFinite","gateway","resolveMailDomain","resolver","records","resolveMx","exchanges","record","exchange","sort","priority","map","real","resolveAddress","addressed","SEVERITY_RANK","refuse","hold","warn","assessEmailDeliverability","input","outcome","findings","severity","message","bulk","purpose","publicMailbox","suggestion","holdReleased","blocked30","some","finding","decidingDeliverabilityFinding","verdict","find","deliverabilityExclusionSummary","counts","noMailServer","max","floor","gatewayHeld","total","parts","toLocaleString","join","installedPreflight","setEmailDeliverabilityPreflight","preflight","getEmailDeliverabilityPreflight","resetEmailDeliverabilityPreflightForTests","EMAIL_DELIVERABILITY_PREFLIGHT_TIMEOUT_MS"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4CA4C4C,GAE5C,SACEA,mBAAmB,EACnBC,wBAAwB,EACxBC,2BAA2B,EAG3BC,gBAAgB,EAChBC,uBAAuB,EACvBC,iBAAiB,QACZ,oBAAgB;AAEvB;;4CAE4C,GAE5C,gEAAgE,GAChE,MAAMC,aAAa;AAEnB,8EAA8E,GAC9E,MAAMC,QAAQ;AAEd,gFAAgF,GAChF,MAAMC,aAAa;AAEnB,4FAA4F,GAC5F,OAAO,SAASC,6BAA6BC,KAAc;IACzD,MAAMC,UAAUC,OAAOF,gBAAAA,QAAS,IAC7BG,IAAI,GACJC,WAAW;IACd,MAAMC,KAAKJ,QAAQK,WAAW,CAAC;IAC/B,IAAID,KAAK,KAAKA,OAAOJ,QAAQM,MAAM,GAAG,KAAKN,QAAQM,MAAM,GAAG,KAAK,OAAO;IACxE,MAAMC,QAAQP,QAAQQ,KAAK,CAAC,GAAGJ;IAC/B,MAAMK,SAAST,QAAQQ,KAAK,CAACJ,KAAK;IAClC,IAAIG,MAAMD,MAAM,GAAG,MAAM,CAACT,WAAWa,IAAI,CAACH,QAAQ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EjD;QAAOR;QAAQgG;QAASC;QAAUxC;QAAOmB;IAAQ;AAC5D;AAEA,4FAA4F,GAC5F,OAAO,SAASgC,8BAA8BC,OAAmC;QACxEA;IAAP,QAAOA,yBAAAA,QAAQZ,QAAQ,CAACa,IAAI,CAAC,CAACH,UAAYA,QAAQT,QAAQ,KAAK,mBAAxDW,yBAAmE;AAC5E;AAEA;;;;CAIC,GACD,OAAO,SAASE,+BAA+BC,MAG9C;IACC,MAAMC,eAAe7E,KAAK8E,GAAG,CAAC,GAAG9E,KAAK+E,KAAK,CAACzC,OAAOsC,0BAAAA,OAAQC,YAAY,KAAK;IAC5E,MAAMG,cAAchF,KAAK8E,GAAG,CAAC,GAAG9E,KAAK+E,KAAK,CAACzC,OAAOsC,0BAAAA,OAAQI,WAAW,KAAK;IAC1E,MAAMC,QAAQJ,eAAeG;IAC7B,IAAI,CAACC,OAAO,OAAO;IACnB,MAAMC,QAAQ;WACRL,eAAe;YAAC,GAAGA,aAAaM,cAAc,CAAC,SAAS,eAAe,CAAC;SAAC,GAAG,EAAE;WAC9EH,cAAc;YAAC,GAAGA,YAAYG,cAAc,CAAC,SAAS,0CAA0C,CAAC;SAAC,GAAG,EAAE;KAC5G;IACD,OAAO,GAAGF,MAAME,cAAc,CAAC,SAAS,CAAC,EAAEF,UAAU,IAAI,cAAc,aAAa,WAAW,EAAEC,MAAME,IAAI,CAAC,QAAQ;AACtH;AAyCA,IAAIC,qBAA0D;AAE9D,kFAAkF,GAClF,OAAO,SAASC,gCAAgCC,SAA8C;IAC5FF,qBAAqBE;AACvB;AAEA,wEAAwE,GACxE,OAAO,SAASC;IACd,OAAOH;AACT;AAEA,+CAA+C,GAC/C,OAAO,SAASI;IACdJ,qBAAqB;AACvB;AAEA;;;;;CAKC,GACD,OAAO,MAAMK,4CAA4C,KAAK"}
|
|
@@ -14,45 +14,6 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
/**
|
|
18
|
-
* WHAT HAPPENED TO A MESSAGE, IN OUR OWN VOCABULARY.
|
|
19
|
-
*
|
|
20
|
-
* ## The seam
|
|
21
|
-
*
|
|
22
|
-
* A staff answer to "did they get the invite, and did they open it?" must not
|
|
23
|
-
* be a question about Resend. Two things follow from that, and this module is
|
|
24
|
-
* both of them:
|
|
25
|
-
*
|
|
26
|
-
* 1. **The stored shape is ours.** Nothing downstream — the delivery log, the
|
|
27
|
-
* staff card, a future export — reads a provider's field names or its event
|
|
28
|
-
* strings. Swapping the sender changes exactly one function in this file
|
|
29
|
-
* and nothing else in the tree.
|
|
30
|
-
* 2. **The history is ours.** The log is written into our own Firestore and
|
|
31
|
-
* read from there, never from the provider on render. A provider's list
|
|
32
|
-
* endpoint is a different shape per vendor, has its own retention window,
|
|
33
|
-
* and disappears entirely with the account; a record we keep survives the
|
|
34
|
-
* migration that the seam exists to make possible.
|
|
35
|
-
*
|
|
36
|
-
* That is a rule about the READ PATH, not a rule against ever reading the
|
|
37
|
-
* provider. The event feed only knows mail sent after it was connected, so
|
|
38
|
-
* a log fed by events alone is empty for all existing history — which is
|
|
39
|
-
* precisely the mail a support question is about. The second half of this
|
|
40
|
-
* module (see THE READ SIDE OF THE SEAM below) imports that history
|
|
41
|
-
* through the same neutral vocabulary, once, into the same store.
|
|
42
|
-
*
|
|
43
|
-
* ## Pure on purpose
|
|
44
|
-
*
|
|
45
|
-
* No Firestore and no admin SDK. `system-email-catalog` is imported by console
|
|
46
|
-
* CLIENT components through this library's barrel, so anything reachable from
|
|
47
|
-
* it that touched `firebase-admin` would drag the admin SDK into a browser
|
|
48
|
-
* bundle. Normalisation is a pure function of a payload; the writing lives in
|
|
49
|
-
* `@aglyn/tenant-data-admin/server/email-delivery-log`.
|
|
50
|
-
*
|
|
51
|
-
* The one `fetch` is `resendDeliveryHistorySource`, which is a function that
|
|
52
|
-
* must be CALLED with a key to do anything — it holds no module state and is
|
|
53
|
-
* unreachable from a client component, unlike an admin-SDK import, which
|
|
54
|
-
* executes on load.
|
|
55
|
-
*/
|
|
56
17
|
/**
|
|
57
18
|
* The lifecycle of one message, in the order it normally happens.
|
|
58
19
|
*
|
|
@@ -98,7 +59,23 @@ export interface EmailDeliveryEvent {
|
|
|
98
59
|
bounceType: 'permanent' | 'transient' | 'undetermined' | null;
|
|
99
60
|
/** Provider-supplied explanation, for the states that carry one. */
|
|
100
61
|
detail: string | null;
|
|
62
|
+
/**
|
|
63
|
+
* The bare sender address, lowercased: the domain it names is the sending
|
|
64
|
+
* domain a gateway's verdict is filed against (AGL-3328). Absent from
|
|
65
|
+
* events normalized before it existed, and `null` when the provider sent
|
|
66
|
+
* none.
|
|
67
|
+
*/
|
|
68
|
+
from?: string | null;
|
|
69
|
+
/**
|
|
70
|
+
* `bounced` only: the enhanced status code (`5.7.1`) and the receiving
|
|
71
|
+
* server the provider's bounce message names, read by `readBounceText` —
|
|
72
|
+
* what a Gmail DSN hands over as `Status` and `Remote-MTA` (AGL-3328).
|
|
73
|
+
*/
|
|
74
|
+
bounceStatus?: string | null;
|
|
75
|
+
remoteMta?: string | null;
|
|
101
76
|
}
|
|
77
|
+
/** The bare address of a `From:` value (`"Acme" <hi@acme.com>` → `hi@acme.com`), lowercased. */
|
|
78
|
+
export declare function bareSenderAddress(value: unknown): string | null;
|
|
102
79
|
/** The later of two statuses on the lifecycle, worst winning a tie. */
|
|
103
80
|
export declare function worstDeliveryStatus(current: EmailDeliveryEventType | null | undefined, next: EmailDeliveryEventType): EmailDeliveryEventType;
|
|
104
81
|
/** Tags arrive as an array of `{name, value}` or a plain map — accept both. */
|