@simplycubed/email-guard 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +249 -2
- package/dist/address.d.ts +6 -0
- package/dist/address.d.ts.map +1 -0
- package/dist/address.js +86 -0
- package/dist/address.js.map +1 -0
- package/dist/consent.d.ts +3 -0
- package/dist/consent.d.ts.map +1 -0
- package/dist/consent.js +36 -0
- package/dist/consent.js.map +1 -0
- package/dist/disposable-domains.d.ts +4 -0
- package/dist/disposable-domains.d.ts.map +1 -0
- package/dist/disposable-domains.js +92 -0
- package/dist/disposable-domains.js.map +1 -0
- package/dist/doh.d.ts +16 -0
- package/dist/doh.d.ts.map +1 -0
- package/dist/doh.js +78 -0
- package/dist/doh.js.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/normalize.d.ts +7 -0
- package/dist/normalize.d.ts.map +1 -0
- package/dist/normalize.js +22 -0
- package/dist/normalize.js.map +1 -0
- package/dist/suppression.d.ts +10 -0
- package/dist/suppression.d.ts.map +1 -0
- package/dist/suppression.js +21 -0
- package/dist/suppression.js.map +1 -0
- package/dist/testing/fake-resolver.d.ts +6 -0
- package/dist/testing/fake-resolver.d.ts.map +1 -0
- package/dist/testing/fake-resolver.js +11 -0
- package/dist/testing/fake-resolver.js.map +1 -0
- package/dist/testing/index.d.ts +6 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +4 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/memory-suppression-store.d.ts +6 -0
- package/dist/testing/memory-suppression-store.d.ts.map +1 -0
- package/dist/testing/memory-suppression-store.js +17 -0
- package/dist/testing/memory-suppression-store.js.map +1 -0
- package/dist/testing/memory-throttle-store.d.ts +3 -0
- package/dist/testing/memory-throttle-store.d.ts.map +1 -0
- package/dist/testing/memory-throttle-store.js +28 -0
- package/dist/testing/memory-throttle-store.js.map +1 -0
- package/dist/throttle.d.ts +6 -0
- package/dist/throttle.d.ts.map +1 -0
- package/dist/throttle.js +66 -0
- package/dist/throttle.js.map +1 -0
- package/dist/token.d.ts +4 -0
- package/dist/token.d.ts.map +1 -0
- package/dist/token.js +140 -0
- package/dist/token.js.map +1 -0
- package/dist/types.d.ts +103 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/package.json +67 -3
- package/src/address.ts +117 -0
- package/src/consent.ts +60 -0
- package/src/disposable-domains.ts +101 -0
- package/src/doh.ts +115 -0
- package/src/index.ts +11 -0
- package/src/normalize.ts +62 -0
- package/src/suppression.ts +41 -0
- package/src/testing/fake-resolver.ts +21 -0
- package/src/testing/index.ts +9 -0
- package/src/testing/memory-suppression-store.ts +23 -0
- package/src/testing/memory-throttle-store.ts +31 -0
- package/src/throttle.ts +114 -0
- package/src/token.ts +180 -0
- package/src/types.ts +164 -0
package/package.json
CHANGED
|
@@ -1,6 +1,70 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@simplycubed/email-guard",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Never email someone who did not ask for it. Address checks, double opt-in tokens, throttling and suppression for Workers-style runtimes, with storage and mail sending left to the consumer.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"sideEffects": false,
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./testing": {
|
|
14
|
+
"types": "./dist/testing/index.d.ts",
|
|
15
|
+
"default": "./dist/testing/index.js"
|
|
16
|
+
},
|
|
17
|
+
"./package.json": "./package.json"
|
|
18
|
+
},
|
|
19
|
+
"main": "./dist/index.js",
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"typesVersions": {
|
|
22
|
+
"*": {
|
|
23
|
+
"testing": [
|
|
24
|
+
"./dist/testing/index.d.ts"
|
|
25
|
+
]
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"dist",
|
|
30
|
+
"src"
|
|
31
|
+
],
|
|
32
|
+
"engines": {
|
|
33
|
+
"node": ">=24"
|
|
34
|
+
},
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"repository": {
|
|
39
|
+
"type": "git",
|
|
40
|
+
"url": "git+https://github.com/simplycubed/email-guard.git"
|
|
41
|
+
},
|
|
42
|
+
"dependencies": {},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@cloudflare/workers-types": "^4.20260529.1",
|
|
45
|
+
"@eslint/js": "^9.39.4",
|
|
46
|
+
"@types/node": "^25.9.1",
|
|
47
|
+
"@vitest/coverage-v8": "4.1.12",
|
|
48
|
+
"eslint": "^9.39.4",
|
|
49
|
+
"globals": "^17.6.0",
|
|
50
|
+
"prettier": "^3.8.3",
|
|
51
|
+
"typescript": "^5.8.3",
|
|
52
|
+
"typescript-eslint": "^8.73.0",
|
|
53
|
+
"vitest": "4.1.12"
|
|
54
|
+
},
|
|
55
|
+
"scripts": {
|
|
56
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
57
|
+
"clean": "rm -rf dist coverage test-results",
|
|
58
|
+
"typecheck": "tsc --noEmit",
|
|
59
|
+
"lint": "eslint . && prettier --check .",
|
|
60
|
+
"lint:eslint": "eslint .",
|
|
61
|
+
"lint:fix": "eslint . --fix && prettier --write .",
|
|
62
|
+
"format": "prettier --write .",
|
|
63
|
+
"format:check": "prettier --check .",
|
|
64
|
+
"test": "vitest run",
|
|
65
|
+
"test:coverage": "vitest run --coverage",
|
|
66
|
+
"no-leaks": "node scripts/no-leaks.mjs",
|
|
67
|
+
"assert-tag-version": "node scripts/assert-tag-version.mjs",
|
|
68
|
+
"check": "pnpm lint && pnpm typecheck && pnpm test:coverage && pnpm build && pnpm no-leaks"
|
|
69
|
+
}
|
|
6
70
|
}
|
package/src/address.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { DISPOSABLE_DOMAINS, ROLE_LOCAL_PARTS, TYPO_DOMAINS } from "./disposable-domains.js";
|
|
2
|
+
import { createDohResolver } from "./doh.js";
|
|
3
|
+
import { normalizeAddress, splitAddress } from "./normalize.js";
|
|
4
|
+
import type { AddressCheck, AddressReason, CheckAddressOptions } from "./types.js";
|
|
5
|
+
|
|
6
|
+
const LOCAL_PATTERN = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*$/;
|
|
7
|
+
const LABEL_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
|
|
8
|
+
const TLD_PATTERN = /^(?:[a-z]{2,63}|xn--[a-z0-9-]{1,59})$/;
|
|
9
|
+
|
|
10
|
+
const DISPOSABLE_SEED = new Set(DISPOSABLE_DOMAINS);
|
|
11
|
+
const ROLE_SET = new Set(ROLE_LOCAL_PARTS);
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Practical syntax check: one `@`, an ASCII dot-atom local part up to 64 characters, and a
|
|
15
|
+
* multi-label domain with a letter-only (or punycode) TLD, up to 254 characters in all.
|
|
16
|
+
* Internationalized domains must be supplied as punycode. Quoted local parts and IP
|
|
17
|
+
* literals are rejected on purpose: nobody signs up for a newsletter with one.
|
|
18
|
+
*/
|
|
19
|
+
export function isValidSyntax(email: string): boolean {
|
|
20
|
+
const normalized = normalizeAddress(email);
|
|
21
|
+
if (normalized.length > 254) return false;
|
|
22
|
+
const parts = splitAddress(normalized);
|
|
23
|
+
if (parts === null || parts.local.length > 64 || !LOCAL_PATTERN.test(parts.local)) return false;
|
|
24
|
+
if (parts.domain.length > 253) return false;
|
|
25
|
+
const labels = parts.domain.split(".");
|
|
26
|
+
if (labels.length < 2) return false;
|
|
27
|
+
if (!labels.every((label) => label.length <= 63 && LABEL_PATTERN.test(label))) return false;
|
|
28
|
+
return TLD_PATTERN.test(labels[labels.length - 1] as string);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** True when `domain`, or any parent domain of it, is a known throwaway provider. */
|
|
32
|
+
export function isDisposableDomain(domain: string, extra?: Iterable<string>): boolean {
|
|
33
|
+
// A name over 253 characters cannot be a registered domain, and the suffix walk below is
|
|
34
|
+
// quadratic in the label count, so unbounded input would be a CPU sink.
|
|
35
|
+
if (domain.length > 253) return false;
|
|
36
|
+
const extras = extra ? new Set([...extra].map((d) => d.trim().toLowerCase())) : null;
|
|
37
|
+
const labels = domain.trim().toLowerCase().split(".");
|
|
38
|
+
for (let i = 0; i < labels.length - 1; i++) {
|
|
39
|
+
const candidate = labels.slice(i).join(".");
|
|
40
|
+
if (DISPOSABLE_SEED.has(candidate) || extras?.has(candidate)) return true;
|
|
41
|
+
}
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A corrected domain for a likely typo, or null. */
|
|
46
|
+
export function suggestDomain(domain: string): string | null {
|
|
47
|
+
const lower = domain.trim().toLowerCase();
|
|
48
|
+
const known = TYPO_DOMAINS[lower];
|
|
49
|
+
if (known !== undefined) return known;
|
|
50
|
+
// `.con`, `.cmo`, `.ocm` and `.vom` are not real TLDs and are near-certain typos of `.com`.
|
|
51
|
+
const match = /^(.+)\.(?:con|cmo|ocm|vom)$/.exec(lower);
|
|
52
|
+
return match ? `${match[1]}.com` : null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Layered address check, cheapest layer first:
|
|
57
|
+
* 1. syntax (invalid_syntax)
|
|
58
|
+
* 2. typo suggestion (typo_domain, risky)
|
|
59
|
+
* 3. disposable domain (disposable_domain, invalid by default)
|
|
60
|
+
* 4. role address (role_address, risky)
|
|
61
|
+
* 5. MX lookup (domain_not_found, no_mx, null_mx: invalid; mx_lookup_failed: risky)
|
|
62
|
+
*
|
|
63
|
+
* Verdict: any invalid reason gives `invalid`, else any reason gives `risky`, else
|
|
64
|
+
* `valid`. A valid verdict proves the address can receive mail, NOT that its owner asked
|
|
65
|
+
* for it: that proof is a clicked confirm link (see `signToken`). There is no SMTP
|
|
66
|
+
* mailbox probing here, by design: big providers answer every probe the same way, the
|
|
67
|
+
* answers that do differ are unreliable, and probing from a sending network can get that
|
|
68
|
+
* network flagged.
|
|
69
|
+
*/
|
|
70
|
+
export async function checkAddress(
|
|
71
|
+
email: string,
|
|
72
|
+
options: CheckAddressOptions = {},
|
|
73
|
+
): Promise<AddressCheck> {
|
|
74
|
+
const address = normalizeAddress(email);
|
|
75
|
+
if (!isValidSyntax(address)) {
|
|
76
|
+
return { verdict: "invalid", reasons: ["invalid_syntax"], address };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const { local, domain } = splitAddress(address) as { local: string; domain: string };
|
|
80
|
+
const invalid: AddressReason[] = [];
|
|
81
|
+
const risky: AddressReason[] = [];
|
|
82
|
+
let suggestion: string | undefined;
|
|
83
|
+
|
|
84
|
+
const corrected = suggestDomain(domain);
|
|
85
|
+
if (corrected !== null) {
|
|
86
|
+
risky.push("typo_domain");
|
|
87
|
+
suggestion = `${local}@${corrected}`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (isDisposableDomain(domain, options.extraDisposableDomains)) {
|
|
91
|
+
(options.disposablePolicy === "risky" ? risky : invalid).push("disposable_domain");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (ROLE_SET.has(local)) risky.push("role_address");
|
|
95
|
+
|
|
96
|
+
// No point asking DNS about a domain already known to be a throwaway or a typo.
|
|
97
|
+
if (!options.skipMx && invalid.length === 0 && corrected === null) {
|
|
98
|
+
const resolver = options.resolver ?? createDohResolver();
|
|
99
|
+
const lookup = await resolver.resolveMx(domain);
|
|
100
|
+
if (lookup.kind === "nxdomain") {
|
|
101
|
+
invalid.push("domain_not_found");
|
|
102
|
+
} else if (lookup.kind === "error") {
|
|
103
|
+
risky.push("mx_lookup_failed");
|
|
104
|
+
} else if (lookup.exchanges.length === 0) {
|
|
105
|
+
invalid.push("no_mx");
|
|
106
|
+
} else if (lookup.exchanges.length === 1 && lookup.exchanges[0] === ".") {
|
|
107
|
+
// RFC 7505 null MX: the domain states it accepts no mail.
|
|
108
|
+
invalid.push("null_mx");
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const reasons = [...invalid, ...risky];
|
|
113
|
+
const verdict = invalid.length > 0 ? "invalid" : risky.length > 0 ? "risky" : "valid";
|
|
114
|
+
return suggestion === undefined
|
|
115
|
+
? { verdict, reasons, address }
|
|
116
|
+
: { verdict, reasons, address, suggestion };
|
|
117
|
+
}
|
package/src/consent.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { MarketingCaps, MarketingDecision, MarketingState } from "./types.js";
|
|
2
|
+
|
|
3
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
4
|
+
const MONTH_MS = 30 * DAY_MS;
|
|
5
|
+
|
|
6
|
+
function cap(name: string, value: number | undefined, fallback: number): number {
|
|
7
|
+
if (value === undefined) return fallback;
|
|
8
|
+
if (!Number.isInteger(value) || value < 1) {
|
|
9
|
+
throw new Error(`email-guard: caps.${name} must be an integer of at least 1`);
|
|
10
|
+
}
|
|
11
|
+
return value;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The pure "may we send marketing to this address right now" decision. It reads only the
|
|
16
|
+
* facts the caller supplies, so it is trivially testable and has no hidden storage.
|
|
17
|
+
*
|
|
18
|
+
* Policy, in order:
|
|
19
|
+
* 1. never when the address is suppressed, or when `suppressed` is not an explicit `false`;
|
|
20
|
+
* 2. never when the account is closed;
|
|
21
|
+
* 3. require a basis: a confirmed double opt-in (a lead), OR a verified account that is
|
|
22
|
+
* not closed. Anything else, including an unverified signup, is `not_confirmed`;
|
|
23
|
+
* 4. global caps over the sends already made: 1 per rolling 24 hours and 12 per rolling
|
|
24
|
+
* 30 days by default. Timestamps in the future count as inside the window, which is
|
|
25
|
+
* the conservative reading of a bad clock.
|
|
26
|
+
*
|
|
27
|
+
* This governs marketing and lifecycle nurture mail. Transactional mail a person asked
|
|
28
|
+
* for (a confirm link, a receipt) does not go through it.
|
|
29
|
+
*/
|
|
30
|
+
export function canSendMarketing(
|
|
31
|
+
state: MarketingState,
|
|
32
|
+
caps: MarketingCaps = {},
|
|
33
|
+
): MarketingDecision {
|
|
34
|
+
if (!Number.isFinite(state.now)) throw new Error("email-guard: state.now must be a number");
|
|
35
|
+
const perDay = cap("perDay", caps.perDay, 1);
|
|
36
|
+
const perMonth = cap("perMonth", caps.perMonth, 12);
|
|
37
|
+
|
|
38
|
+
// Anything but an explicit `false` denies: a caller that forgot to look the address up on
|
|
39
|
+
// the suppression list must not be told it may send.
|
|
40
|
+
if (state.suppressed !== false) return { allow: false, reason: "suppressed" };
|
|
41
|
+
if (state.accountClosed === true) return { allow: false, reason: "account_closed" };
|
|
42
|
+
if (state.confirmed !== true && state.accountVerified !== true) {
|
|
43
|
+
return { allow: false, reason: "not_confirmed" };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// A history entry that is not a finite number is treated as "sent just now": when in doubt,
|
|
47
|
+
// count it against the caps rather than silently dropping it.
|
|
48
|
+
const sent = state.lastMarketingSentAt.map((t) => (Number.isFinite(t) ? t : state.now));
|
|
49
|
+
const inDay = sent.filter((t) => t > state.now - DAY_MS).sort((a, b) => a - b);
|
|
50
|
+
if (inDay.length >= perDay) {
|
|
51
|
+
const pivot = inDay[inDay.length - perDay] as number;
|
|
52
|
+
return { allow: false, reason: "daily_cap", retryAt: pivot + DAY_MS };
|
|
53
|
+
}
|
|
54
|
+
const inMonth = sent.filter((t) => t > state.now - MONTH_MS).sort((a, b) => a - b);
|
|
55
|
+
if (inMonth.length >= perMonth) {
|
|
56
|
+
const pivot = inMonth[inMonth.length - perMonth] as number;
|
|
57
|
+
return { allow: false, reason: "monthly_cap", retryAt: pivot + MONTH_MS };
|
|
58
|
+
}
|
|
59
|
+
return { allow: true, reason: "ok" };
|
|
60
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SEED list of throwaway-mailbox providers. Deliberately small: it is a starting point,
|
|
3
|
+
* not a feed. To update it, add lowercase registrable domains in alphabetical order,
|
|
4
|
+
* run `pnpm check`, and release a new version. A consumer that needs a domain blocked
|
|
5
|
+
* today passes it as `extraDisposableDomains` without waiting for a release.
|
|
6
|
+
*/
|
|
7
|
+
export const DISPOSABLE_DOMAINS: readonly string[] = [
|
|
8
|
+
"10minutemail.com",
|
|
9
|
+
"10minutemail.net",
|
|
10
|
+
"20minutemail.com",
|
|
11
|
+
"dispostable.com",
|
|
12
|
+
"dropmail.me",
|
|
13
|
+
"emailondeck.com",
|
|
14
|
+
"fakeinbox.com",
|
|
15
|
+
"getairmail.com",
|
|
16
|
+
"getnada.com",
|
|
17
|
+
"guerrillamail.biz",
|
|
18
|
+
"guerrillamail.com",
|
|
19
|
+
"guerrillamail.de",
|
|
20
|
+
"guerrillamail.net",
|
|
21
|
+
"guerrillamail.org",
|
|
22
|
+
"harakirimail.com",
|
|
23
|
+
"inboxbear.com",
|
|
24
|
+
"maildrop.cc",
|
|
25
|
+
"mailinator.com",
|
|
26
|
+
"mailinator.net",
|
|
27
|
+
"mailnesia.com",
|
|
28
|
+
"mailtemp.net",
|
|
29
|
+
"mintemail.com",
|
|
30
|
+
"moakt.com",
|
|
31
|
+
"mohmal.com",
|
|
32
|
+
"mytemp.email",
|
|
33
|
+
"sharklasers.com",
|
|
34
|
+
"spam4.me",
|
|
35
|
+
"spamgourmet.com",
|
|
36
|
+
"temp-mail.io",
|
|
37
|
+
"temp-mail.org",
|
|
38
|
+
"tempail.com",
|
|
39
|
+
"tempinbox.com",
|
|
40
|
+
"tempmail.com",
|
|
41
|
+
"tempmailo.com",
|
|
42
|
+
"throwawaymail.com",
|
|
43
|
+
"trashmail.com",
|
|
44
|
+
"trashmail.net",
|
|
45
|
+
"yopmail.com",
|
|
46
|
+
"yopmail.fr",
|
|
47
|
+
"yopmail.net",
|
|
48
|
+
];
|
|
49
|
+
|
|
50
|
+
/** Common role mailboxes. Not disposable, but rarely a person who chose to sign up. */
|
|
51
|
+
export const ROLE_LOCAL_PARTS: readonly string[] = [
|
|
52
|
+
"abuse",
|
|
53
|
+
"admin",
|
|
54
|
+
"administrator",
|
|
55
|
+
"billing",
|
|
56
|
+
"contact",
|
|
57
|
+
"do-not-reply",
|
|
58
|
+
"donotreply",
|
|
59
|
+
"enquiries",
|
|
60
|
+
"help",
|
|
61
|
+
"hostmaster",
|
|
62
|
+
"hello",
|
|
63
|
+
"info",
|
|
64
|
+
"mail",
|
|
65
|
+
"marketing",
|
|
66
|
+
"no-reply",
|
|
67
|
+
"noreply",
|
|
68
|
+
"office",
|
|
69
|
+
"postmaster",
|
|
70
|
+
"root",
|
|
71
|
+
"sales",
|
|
72
|
+
"security",
|
|
73
|
+
"support",
|
|
74
|
+
"team",
|
|
75
|
+
"webmaster",
|
|
76
|
+
];
|
|
77
|
+
|
|
78
|
+
/** Domains people commonly mistype, mapped to the domain they almost certainly meant. */
|
|
79
|
+
export const TYPO_DOMAINS: Readonly<Record<string, string>> = {
|
|
80
|
+
"gamil.com": "gmail.com",
|
|
81
|
+
"gmai.com": "gmail.com",
|
|
82
|
+
"gmail.co": "gmail.com",
|
|
83
|
+
"gmail.con": "gmail.com",
|
|
84
|
+
"gmal.com": "gmail.com",
|
|
85
|
+
"gmial.com": "gmail.com",
|
|
86
|
+
"gnail.com": "gmail.com",
|
|
87
|
+
"googlemail.con": "googlemail.com",
|
|
88
|
+
"hotmai.com": "hotmail.com",
|
|
89
|
+
"hotmial.com": "hotmail.com",
|
|
90
|
+
"hotnail.com": "hotmail.com",
|
|
91
|
+
"hotmail.co": "hotmail.com",
|
|
92
|
+
"icloud.con": "icloud.com",
|
|
93
|
+
"iclod.com": "icloud.com",
|
|
94
|
+
"outlok.com": "outlook.com",
|
|
95
|
+
"outlook.co": "outlook.com",
|
|
96
|
+
"protonmail.con": "protonmail.com",
|
|
97
|
+
"yaho.com": "yahoo.com",
|
|
98
|
+
"yahoo.con": "yahoo.com",
|
|
99
|
+
"yahooo.com": "yahoo.com",
|
|
100
|
+
"yhoo.com": "yahoo.com",
|
|
101
|
+
};
|
package/src/doh.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { DnsResolver, MxLookup } from "./types.js";
|
|
2
|
+
|
|
3
|
+
/** The slice of `fetch` the resolver needs. Structural, so Workers and Node both fit. */
|
|
4
|
+
export type DohFetch = (
|
|
5
|
+
url: string,
|
|
6
|
+
init: { headers: Record<string, string>; signal: AbortSignal },
|
|
7
|
+
) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>;
|
|
8
|
+
|
|
9
|
+
export interface DohResolverOptions {
|
|
10
|
+
/**
|
|
11
|
+
* A DNS-over-HTTPS JSON endpoint, https only (anything else throws). Must be a fixed value
|
|
12
|
+
* from your own config, never derived from user input.
|
|
13
|
+
*/
|
|
14
|
+
endpoint?: string;
|
|
15
|
+
/** Defaults to the platform `fetch`. Inject a fake in tests. */
|
|
16
|
+
fetch?: DohFetch;
|
|
17
|
+
/** Per-query timeout in milliseconds. Default 3000. */
|
|
18
|
+
timeoutMs?: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const DEFAULT_ENDPOINT = "https://cloudflare-dns.com/dns-query";
|
|
22
|
+
const TYPE_A = 1;
|
|
23
|
+
const TYPE_AAAA = 28;
|
|
24
|
+
const TYPE_MX = 15;
|
|
25
|
+
const RCODE_NOERROR = 0;
|
|
26
|
+
const RCODE_NXDOMAIN = 3;
|
|
27
|
+
// Hostile or broken resolvers: never process an unbounded answer set or hostname.
|
|
28
|
+
const MAX_ANSWERS = 64;
|
|
29
|
+
const MAX_HOST_LENGTH = 255;
|
|
30
|
+
|
|
31
|
+
interface DohAnswer {
|
|
32
|
+
type: number;
|
|
33
|
+
data: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface DohReply {
|
|
37
|
+
rcode: number;
|
|
38
|
+
answers: DohAnswer[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function parseReply(body: unknown): DohReply | null {
|
|
42
|
+
if (typeof body !== "object" || body === null) return null;
|
|
43
|
+
const record = body as { Status?: unknown; Answer?: unknown };
|
|
44
|
+
if (typeof record.Status !== "number") return null;
|
|
45
|
+
const answers: DohAnswer[] = [];
|
|
46
|
+
if (Array.isArray(record.Answer)) {
|
|
47
|
+
for (const item of record.Answer.slice(0, MAX_ANSWERS)) {
|
|
48
|
+
if (typeof item !== "object" || item === null) continue;
|
|
49
|
+
const { type, data } = item as { type?: unknown; data?: unknown };
|
|
50
|
+
if (typeof type === "number" && typeof data === "string") answers.push({ type, data });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return { rcode: record.Status, answers };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* MX lookups over DNS-over-HTTPS using only `fetch`, so it runs on Workers as is.
|
|
58
|
+
*
|
|
59
|
+
* A domain with no MX record but an address record is treated as accepting mail at
|
|
60
|
+
* itself, which is the implicit-MX fallback in RFC 5321. A network failure, timeout or
|
|
61
|
+
* unexpected reply is reported as `error`, never as `nxdomain`: a DNS hiccup must not
|
|
62
|
+
* look like a nonexistent domain.
|
|
63
|
+
*/
|
|
64
|
+
export function createDohResolver(options: DohResolverOptions = {}): DnsResolver {
|
|
65
|
+
const endpoint = new URL(options.endpoint ?? DEFAULT_ENDPOINT);
|
|
66
|
+
if (endpoint.protocol !== "https:") {
|
|
67
|
+
throw new Error("email-guard: the DNS-over-HTTPS endpoint must be an https URL");
|
|
68
|
+
}
|
|
69
|
+
const timeoutMs = options.timeoutMs ?? 3000;
|
|
70
|
+
const doFetch: DohFetch = options.fetch ?? ((url, init) => fetch(url, init));
|
|
71
|
+
|
|
72
|
+
async function query(name: string, type: number): Promise<DohReply> {
|
|
73
|
+
const target = new URL(endpoint);
|
|
74
|
+
target.searchParams.set("name", name);
|
|
75
|
+
target.searchParams.set("type", String(type));
|
|
76
|
+
const response = await doFetch(target.toString(), {
|
|
77
|
+
headers: { accept: "application/dns-json" },
|
|
78
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
79
|
+
});
|
|
80
|
+
if (!response.ok) throw new Error(`DNS-over-HTTPS endpoint returned HTTP ${response.status}`);
|
|
81
|
+
const reply = parseReply(await response.json());
|
|
82
|
+
if (reply === null) throw new Error("DNS-over-HTTPS endpoint returned an unreadable reply");
|
|
83
|
+
return reply;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return {
|
|
87
|
+
async resolveMx(domain: string): Promise<MxLookup> {
|
|
88
|
+
try {
|
|
89
|
+
const mx = await query(domain, TYPE_MX);
|
|
90
|
+
if (mx.rcode === RCODE_NXDOMAIN) return { kind: "nxdomain" };
|
|
91
|
+
if (mx.rcode !== RCODE_NOERROR) return { kind: "error", message: `DNS rcode ${mx.rcode}` };
|
|
92
|
+
|
|
93
|
+
const exchanges = mx.answers
|
|
94
|
+
.filter((a) => a.type === TYPE_MX)
|
|
95
|
+
.map((a) => a.data.trim().split(/\s+/)[1])
|
|
96
|
+
.filter(
|
|
97
|
+
(host): host is string =>
|
|
98
|
+
typeof host === "string" && host.length > 0 && host.length <= MAX_HOST_LENGTH,
|
|
99
|
+
)
|
|
100
|
+
.map((host) => (host === "." ? host : host.replace(/\.$/, "").toLowerCase()));
|
|
101
|
+
if (exchanges.length > 0) return { kind: "records", exchanges };
|
|
102
|
+
|
|
103
|
+
for (const type of [TYPE_A, TYPE_AAAA]) {
|
|
104
|
+
const addr = await query(domain, type);
|
|
105
|
+
if (addr.answers.some((a) => a.type === type)) {
|
|
106
|
+
return { kind: "records", exchanges: [domain] };
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return { kind: "records", exchanges: [] };
|
|
110
|
+
} catch (err) {
|
|
111
|
+
return { kind: "error", message: err instanceof Error ? err.message : String(err) };
|
|
112
|
+
}
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { normalizeAddress, splitAddress } from "./normalize.js";
|
|
2
|
+
export { checkAddress, isValidSyntax, isDisposableDomain, suggestDomain } from "./address.js";
|
|
3
|
+
export { createDohResolver } from "./doh.js";
|
|
4
|
+
export type { DohFetch, DohResolverOptions } from "./doh.js";
|
|
5
|
+
export { signToken, verifyToken } from "./token.js";
|
|
6
|
+
export { canSendMarketing } from "./consent.js";
|
|
7
|
+
export { createThrottle } from "./throttle.js";
|
|
8
|
+
export type { ThrottleOptions } from "./throttle.js";
|
|
9
|
+
export { suppress, isSuppressed } from "./suppression.js";
|
|
10
|
+
export type { SuppressInput } from "./suppression.js";
|
|
11
|
+
export type * from "./types.js";
|
package/src/normalize.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one shared address normalizer. Every module that keys on an address (suppression,
|
|
3
|
+
* throttle keys, signed tokens) goes through this function, so two spellings of the same
|
|
4
|
+
* mailbox can never be tracked as two people.
|
|
5
|
+
*
|
|
6
|
+
* Decision: trim, lowercase, and drop trailing dots from the domain part. Nothing else.
|
|
7
|
+
* - A trailing dot on a domain (`a@example.com.`) is the DNS root label: the same host.
|
|
8
|
+
* Dropping it stops `a@example.com.` from slipping past a suppression entry.
|
|
9
|
+
* - Plus-addressing (`a+tag@example.com`) is NOT stripped.
|
|
10
|
+
* - Provider-specific dot rules (`a.b@gmail.com` equals `ab@gmail.com`) are NOT applied.
|
|
11
|
+
* Both folds are provider-specific guesses. Applying them would let an unsubscribe for one
|
|
12
|
+
* mailbox silence a different real one, and keeping the exact address is the conservative
|
|
13
|
+
* choice for a library whose job is to avoid mailing the wrong person. A consumer that
|
|
14
|
+
* wants a fold can apply it before calling in.
|
|
15
|
+
*
|
|
16
|
+
* Always mail the NORMALIZED address (`AddressCheck.address`), never the raw input: lowercasing
|
|
17
|
+
* folds a few non-ASCII characters (for example the Kelvin sign) onto ASCII letters.
|
|
18
|
+
*/
|
|
19
|
+
export function normalizeAddress(email: string): string {
|
|
20
|
+
const lowered = email.trim().toLowerCase();
|
|
21
|
+
const at = lowered.indexOf("@");
|
|
22
|
+
if (at < 0) return lowered;
|
|
23
|
+
// Scan back over the trailing dot run instead of matching /\.+$/ on the domain.
|
|
24
|
+
// That regex is polynomial: on a domain of n dots followed by any non-dot, `\.+`
|
|
25
|
+
// matches greedily from every start offset, fails `$`, and backtracks the whole
|
|
26
|
+
// run, so the work is O(n^2). Measured on the old code, `a@` + `.`*n + `x` took
|
|
27
|
+
// 28ms at n=8000 and 1.8s at n=64000. normalizeAddress is exported, takes
|
|
28
|
+
// consumer input, and caps nothing (the 254 limit in isMailboxShaped applies to
|
|
29
|
+
// its OUTPUT), so a caller passing an untrusted string could burn a Workers CPU
|
|
30
|
+
// budget on a few kilobytes. This loop is a single backward pass, and the 46 is
|
|
31
|
+
// ".". Behaviour is unchanged: a domain that is all dots still collapses to
|
|
32
|
+
// everything up to and including the "@".
|
|
33
|
+
let end = lowered.length;
|
|
34
|
+
while (end > at + 1 && lowered.charCodeAt(end - 1) === 46) end--;
|
|
35
|
+
return lowered.slice(0, end);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The two halves of a normalized address, or null when it has no single `@` to split on. */
|
|
39
|
+
export function splitAddress(email: string): { local: string; domain: string } | null {
|
|
40
|
+
const normalized = normalizeAddress(email);
|
|
41
|
+
const at = normalized.indexOf("@");
|
|
42
|
+
if (at <= 0 || at !== normalized.lastIndexOf("@") || at === normalized.length - 1) return null;
|
|
43
|
+
return { local: normalized.slice(0, at), domain: normalized.slice(at + 1) };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Whitespace, C0/C1 controls, line separators and zero-width characters. None can appear in
|
|
47
|
+
// an address that is safe to put in a header, a token or a store key.
|
|
48
|
+
// eslint-disable-next-line no-control-regex -- matching control characters is the point
|
|
49
|
+
const UNSAFE_CHARS = /[\u0000-\u0020\u007f-\u009f\u00a0\u2028\u2029\u200b-\u200f\u2060\ufeff]/;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Internal guard for `signToken` and `suppress`, which accept any address a consumer has
|
|
53
|
+
* (including ones `checkAddress` would reject): exactly one `@`, both halves non-empty,
|
|
54
|
+
* at most 254 characters, and no whitespace, control or zero-width characters (CR and LF
|
|
55
|
+
* would be a header-injection vector in any mailer that trusted the value). Not exported
|
|
56
|
+
* from the package barrel.
|
|
57
|
+
*/
|
|
58
|
+
export function isMailboxShaped(normalized: string): boolean {
|
|
59
|
+
return (
|
|
60
|
+
normalized.length <= 254 && !UNSAFE_CHARS.test(normalized) && splitAddress(normalized) !== null
|
|
61
|
+
);
|
|
62
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { isMailboxShaped, normalizeAddress } from "./normalize.js";
|
|
2
|
+
import type { SuppressionEntry, SuppressionReason, SuppressionStore } from "./types.js";
|
|
3
|
+
|
|
4
|
+
export interface SuppressInput {
|
|
5
|
+
address: string;
|
|
6
|
+
reason: SuppressionReason;
|
|
7
|
+
/** Which product or system recorded it. */
|
|
8
|
+
source: string;
|
|
9
|
+
/** Epoch milliseconds. Defaults to now. */
|
|
10
|
+
now?: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Record that an address must not be mailed. The address is normalized first (trim and
|
|
15
|
+
* lowercase only, see `normalizeAddress`), so `A@Example.com ` and `a@example.com` are one
|
|
16
|
+
* entry. Suppression is meant to be SHARED across products: an unsubscribe in one product
|
|
17
|
+
* silences all of them.
|
|
18
|
+
*/
|
|
19
|
+
export async function suppress(
|
|
20
|
+
store: SuppressionStore,
|
|
21
|
+
input: SuppressInput,
|
|
22
|
+
): Promise<SuppressionEntry> {
|
|
23
|
+
const address = normalizeAddress(input.address);
|
|
24
|
+
if (!isMailboxShaped(address)) {
|
|
25
|
+
throw new Error("email-guard: cannot suppress a value that is not an email address");
|
|
26
|
+
}
|
|
27
|
+
if (input.source.trim().length === 0) throw new Error("email-guard: suppression needs a source");
|
|
28
|
+
const entry: SuppressionEntry = {
|
|
29
|
+
address,
|
|
30
|
+
reason: input.reason,
|
|
31
|
+
source: input.source.trim(),
|
|
32
|
+
addedAt: input.now ?? Date.now(),
|
|
33
|
+
};
|
|
34
|
+
await store.add(entry);
|
|
35
|
+
return entry;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** True when the normalized address is on the list. */
|
|
39
|
+
export function isSuppressed(store: SuppressionStore, address: string): Promise<boolean> {
|
|
40
|
+
return store.has(normalizeAddress(address));
|
|
41
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { DnsResolver, MxLookup } from "../types.js";
|
|
2
|
+
|
|
3
|
+
export interface FakeResolver extends DnsResolver {
|
|
4
|
+
/** Domains looked up, in order. */
|
|
5
|
+
readonly calls: string[];
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* A `DnsResolver` answering from a fixed table. A domain missing from the table is
|
|
10
|
+
* `nxdomain`, so a test only lists the domains it wants to exist.
|
|
11
|
+
*/
|
|
12
|
+
export function createFakeResolver(table: Readonly<Record<string, MxLookup>> = {}): FakeResolver {
|
|
13
|
+
const calls: string[] = [];
|
|
14
|
+
return {
|
|
15
|
+
calls,
|
|
16
|
+
resolveMx(domain) {
|
|
17
|
+
calls.push(domain);
|
|
18
|
+
return Promise.resolve(table[domain] ?? { kind: "nxdomain" });
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The supported TEST KIT, exported from the `./testing` subpath so importing the library
|
|
3
|
+
* never pulls it into a Worker bundle.
|
|
4
|
+
*/
|
|
5
|
+
export { createMemoryThrottleStore } from "./memory-throttle-store.js";
|
|
6
|
+
export { createMemorySuppressionStore } from "./memory-suppression-store.js";
|
|
7
|
+
export type { MemorySuppressionStore } from "./memory-suppression-store.js";
|
|
8
|
+
export { createFakeResolver } from "./fake-resolver.js";
|
|
9
|
+
export type { FakeResolver } from "./fake-resolver.js";
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { SuppressionEntry, SuppressionStore } from "../types.js";
|
|
2
|
+
|
|
3
|
+
/** In-memory `SuppressionStore` for tests, with a peek at what was recorded. */
|
|
4
|
+
export interface MemorySuppressionStore extends SuppressionStore {
|
|
5
|
+
entries(): SuppressionEntry[];
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function createMemorySuppressionStore(): MemorySuppressionStore {
|
|
9
|
+
const byAddress = new Map<string, SuppressionEntry>();
|
|
10
|
+
return {
|
|
11
|
+
add(entry) {
|
|
12
|
+
// First reason wins: a later duplicate must not rewrite why the address was suppressed.
|
|
13
|
+
if (!byAddress.has(entry.address)) byAddress.set(entry.address, entry);
|
|
14
|
+
return Promise.resolve();
|
|
15
|
+
},
|
|
16
|
+
has(address) {
|
|
17
|
+
return Promise.resolve(byAddress.has(address));
|
|
18
|
+
},
|
|
19
|
+
entries() {
|
|
20
|
+
return [...byAddress.values()];
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ThrottleCounter, ThrottleStore } from "../types.js";
|
|
2
|
+
|
|
3
|
+
/** In-memory `ThrottleStore` for tests. Not shared across isolates: never use in production. */
|
|
4
|
+
export function createMemoryThrottleStore(now: () => number = Date.now): ThrottleStore {
|
|
5
|
+
const counters = new Map<string, ThrottleCounter>();
|
|
6
|
+
|
|
7
|
+
function live(key: string): ThrottleCounter | null {
|
|
8
|
+
const counter = counters.get(key);
|
|
9
|
+
if (counter === undefined) return null;
|
|
10
|
+
if (counter.expiresAt <= now()) {
|
|
11
|
+
counters.delete(key);
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
return counter;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
return {
|
|
18
|
+
get(key) {
|
|
19
|
+
const counter = live(key);
|
|
20
|
+
return Promise.resolve(counter === null ? null : { ...counter });
|
|
21
|
+
},
|
|
22
|
+
increment(key, ttlSeconds) {
|
|
23
|
+
const existing = live(key);
|
|
24
|
+
const next: ThrottleCounter = existing
|
|
25
|
+
? { count: existing.count + 1, expiresAt: existing.expiresAt }
|
|
26
|
+
: { count: 1, expiresAt: now() + ttlSeconds * 1000 };
|
|
27
|
+
counters.set(key, next);
|
|
28
|
+
return Promise.resolve({ ...next });
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|