@simplycubed/email-guard 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +249 -2
- package/package.json +69 -4
- 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 +50 -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/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SimplyCubed GK
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,250 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @simplycubed/email-guard
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Never email someone who did not ask for it.
|
|
4
|
+
|
|
5
|
+
A small TypeScript library of the checks a signup or lead form needs before it mails anybody:
|
|
6
|
+
address checks, signed double opt-in and unsubscribe tokens, rate limiting, and a shared
|
|
7
|
+
suppression list. It has **zero runtime dependencies**, uses only Web Crypto and `fetch`, and
|
|
8
|
+
runs on Cloudflare Workers and Node 24 or newer.
|
|
9
|
+
|
|
10
|
+
It owns no database and no mail provider. You hand it storage and a DNS resolver through
|
|
11
|
+
small interfaces, and you send the mail yourself.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
pnpm add @simplycubed/email-guard
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## What a valid address does and does not prove
|
|
20
|
+
|
|
21
|
+
A `valid` verdict means the address is well formed, its domain accepts mail, and the domain is
|
|
22
|
+
not a known throwaway provider. It does **not** prove the owner asked for your mail: a bot can
|
|
23
|
+
type anybody's real address into a form. The only proof of consent is the owner clicking a link
|
|
24
|
+
you mailed to that address (double opt-in), which is what the `consent` module is for.
|
|
25
|
+
|
|
26
|
+
## Modules
|
|
27
|
+
|
|
28
|
+
### Address checks
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { checkAddress } from "@simplycubed/email-guard";
|
|
32
|
+
|
|
33
|
+
const result = await checkAddress("Sam@gmial.com");
|
|
34
|
+
// { verdict: "risky", reasons: ["typo_domain"], address: "sam@gmial.com",
|
|
35
|
+
// suggestion: "sam@gmail.com" }
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Layers, cheapest first: syntax, typo suggestion, disposable domain, role address (`info@`),
|
|
39
|
+
then an MX lookup over DNS-over-HTTPS. Verdicts are `valid`, `risky` (let the user continue but
|
|
40
|
+
think twice) and `invalid` (do not send). Reasons are stable codes: `invalid_syntax`,
|
|
41
|
+
`typo_domain`, `disposable_domain`, `role_address`, `domain_not_found`, `no_mx`, `null_mx`,
|
|
42
|
+
`mx_lookup_failed`.
|
|
43
|
+
|
|
44
|
+
Options: `resolver` (inject your own `DnsResolver`), `skipMx`, `extraDisposableDomains`, and
|
|
45
|
+
`disposablePolicy` (`"invalid"` by default, or `"risky"`). A DNS failure is only ever `risky`.
|
|
46
|
+
|
|
47
|
+
There is deliberately **no SMTP mailbox probing**. Large providers answer every probe the
|
|
48
|
+
same way, the answers that do differ are unreliable, and probing from a sending network can get
|
|
49
|
+
that network flagged.
|
|
50
|
+
|
|
51
|
+
The bundled disposable list is a small seed. Add domains for yourself with
|
|
52
|
+
`extraDisposableDomains`, or send a pull request to extend the seed.
|
|
53
|
+
|
|
54
|
+
### Consent: signed tokens and the send decision
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import { signToken, verifyToken, canSendMarketing } from "@simplycubed/email-guard";
|
|
58
|
+
|
|
59
|
+
const token = await signToken(
|
|
60
|
+
{ purpose: "confirm", address: "sam@example.com", ttlSeconds: 48 * 3600 },
|
|
61
|
+
[env.TOKEN_SECRET_CURRENT, env.TOKEN_SECRET_PREVIOUS], // first signs, any verifies
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
const result = await verifyToken(token, [env.TOKEN_SECRET_CURRENT, env.TOKEN_SECRET_PREVIOUS], {
|
|
65
|
+
purpose: "confirm",
|
|
66
|
+
});
|
|
67
|
+
if (result.valid) {
|
|
68
|
+
// result.address is the normalized address that clicked.
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const decision = canSendMarketing({
|
|
72
|
+
confirmed: true,
|
|
73
|
+
suppressed: false, // from your own suppression lookup; anything but `false` denies
|
|
74
|
+
lastMarketingSentAt: [], // epoch ms of earlier marketing sends to this address
|
|
75
|
+
now: Date.now(),
|
|
76
|
+
});
|
|
77
|
+
// { allow: true, reason: "ok" }
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Tokens are stateless: `base64url(payload).base64url(HMAC-SHA256)`. They are bound to a purpose
|
|
81
|
+
(a confirm link cannot be replayed as an unsubscribe link), expire, and verify in constant time.
|
|
82
|
+
Secrets must be at least 32 characters (use 32 random bytes). Tokens are signed, not
|
|
83
|
+
encrypted, and are replayable until they expire, so make your confirm handler idempotent. `issuedAt` and `now` are epoch milliseconds, and
|
|
84
|
+
`ttlSeconds` is in seconds.
|
|
85
|
+
|
|
86
|
+
`canSendMarketing` is a pure function over facts you supply. It requires a confirmed lead or a
|
|
87
|
+
verified, open account, never allows a suppressed address, and caps sends at 1 per rolling 24
|
|
88
|
+
hours and 12 per rolling 30 days (override with the second argument).
|
|
89
|
+
|
|
90
|
+
### Throttle
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
import { createThrottle } from "@simplycubed/email-guard";
|
|
94
|
+
|
|
95
|
+
const throttle = createThrottle(myStore, {
|
|
96
|
+
address: { limit: 3, windowSeconds: 3600 },
|
|
97
|
+
ip: { limit: 20, windowSeconds: 3600 },
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
const gate = await throttle.consumeAll([
|
|
101
|
+
["address", normalizeAddress(email)],
|
|
102
|
+
["ip", request.headers.get("cf-connecting-ip") ?? "unknown"],
|
|
103
|
+
]);
|
|
104
|
+
if (!gate.allowed)
|
|
105
|
+
return new Response("Slow down", {
|
|
106
|
+
status: 429,
|
|
107
|
+
headers: { "retry-after": String(gate.retryAfterSeconds) },
|
|
108
|
+
});
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
`myStore` implements `ThrottleStore` (`get` and an atomic `increment` that sets the expiry only
|
|
112
|
+
when it creates the counter). Use a Durable Object, a SQL database or a Postgres upsert. Workers KV is not
|
|
113
|
+
atomic and is the wrong store.
|
|
114
|
+
|
|
115
|
+
### Suppression
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
import { suppress, isSuppressed } from "@simplycubed/email-guard";
|
|
119
|
+
|
|
120
|
+
await suppress(mySuppressionStore, { address, reason: "unsubscribe", source: "my-app" });
|
|
121
|
+
if (await isSuppressed(mySuppressionStore, address)) return;
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Addresses are normalized by `normalizeAddress`: trim, lowercase and drop a trailing domain dot,
|
|
125
|
+
nothing more. Mail the normalized address, never the raw input. Plus tags and
|
|
126
|
+
provider dot rules are **not** folded, because they are provider-specific guesses and folding
|
|
127
|
+
the wrong way would silence a different person.
|
|
128
|
+
|
|
129
|
+
## A Worker flow: signup form and lead form
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
import {
|
|
133
|
+
checkAddress,
|
|
134
|
+
createThrottle,
|
|
135
|
+
isSuppressed,
|
|
136
|
+
normalizeAddress,
|
|
137
|
+
signToken,
|
|
138
|
+
verifyToken,
|
|
139
|
+
canSendMarketing,
|
|
140
|
+
suppress,
|
|
141
|
+
} from "@simplycubed/email-guard";
|
|
142
|
+
|
|
143
|
+
export default {
|
|
144
|
+
async fetch(request: Request, env: Env): Promise<Response> {
|
|
145
|
+
const url = new URL(request.url);
|
|
146
|
+
const secrets = [env.TOKEN_SECRET_CURRENT, env.TOKEN_SECRET_PREVIOUS];
|
|
147
|
+
const throttle = createThrottle(env.throttleStore, {
|
|
148
|
+
address: { limit: 3, windowSeconds: 3600 },
|
|
149
|
+
ip: { limit: 20, windowSeconds: 3600 },
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
// 1. Lead form: never enroll on submit. Mail a confirm link and stop.
|
|
153
|
+
if (url.pathname === "/lead" && request.method === "POST") {
|
|
154
|
+
const { email } = (await request.json()) as { email: string };
|
|
155
|
+
const address = normalizeAddress(email);
|
|
156
|
+
|
|
157
|
+
const gate = await throttle.consumeAll([
|
|
158
|
+
["address", address],
|
|
159
|
+
["ip", request.headers.get("cf-connecting-ip") ?? "unknown"],
|
|
160
|
+
]);
|
|
161
|
+
if (!gate.allowed) return new Response("Too many requests", { status: 429 });
|
|
162
|
+
|
|
163
|
+
const check = await checkAddress(address);
|
|
164
|
+
if (check.verdict === "invalid")
|
|
165
|
+
return Response.json({ ok: false, reasons: check.reasons }, { status: 422 });
|
|
166
|
+
if (await isSuppressed(env.suppressionStore, address)) return Response.json({ ok: true }); // say nothing
|
|
167
|
+
|
|
168
|
+
const token = await signToken(
|
|
169
|
+
{ purpose: "confirm", address, ttlSeconds: 48 * 3600 },
|
|
170
|
+
secrets,
|
|
171
|
+
);
|
|
172
|
+
await env.sendMail({ to: address, link: `${url.origin}/confirm?t=${token}` });
|
|
173
|
+
return Response.json({ ok: true, suggestion: check.suggestion });
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// 2. Confirm link: only now is the lead enrolled. Use a POST from a confirm page, so a
|
|
177
|
+
// mail scanner that pre-fetches links cannot confirm for the owner.
|
|
178
|
+
if (url.pathname === "/confirm" && request.method === "POST") {
|
|
179
|
+
const result = await verifyToken(url.searchParams.get("t") ?? "", secrets, {
|
|
180
|
+
purpose: "confirm",
|
|
181
|
+
});
|
|
182
|
+
if (!result.valid) return new Response("Link invalid or expired", { status: 400 });
|
|
183
|
+
await env.enrollLead(result.address);
|
|
184
|
+
return Response.json({ ok: true });
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// 3. Unsubscribe link: stateless, then recorded in the shared suppression list.
|
|
188
|
+
if (url.pathname === "/unsubscribe" && request.method === "POST") {
|
|
189
|
+
const result = await verifyToken(url.searchParams.get("t") ?? "", secrets, {
|
|
190
|
+
purpose: "unsubscribe",
|
|
191
|
+
});
|
|
192
|
+
if (!result.valid) return new Response("Link invalid or expired", { status: 400 });
|
|
193
|
+
await suppress(env.suppressionStore, {
|
|
194
|
+
address: result.address,
|
|
195
|
+
reason: "unsubscribe",
|
|
196
|
+
source: "my-app",
|
|
197
|
+
});
|
|
198
|
+
return Response.json({ ok: true });
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return new Response("Not found", { status: 404 });
|
|
202
|
+
},
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
// 4. Before every marketing send (a cron stepper, for example):
|
|
206
|
+
async function mayMail(env: Env, address: string): Promise<boolean> {
|
|
207
|
+
const row = await env.loadContactFacts(address); // your database
|
|
208
|
+
const decision = canSendMarketing({
|
|
209
|
+
confirmed: row.confirmed,
|
|
210
|
+
accountVerified: row.accountVerified,
|
|
211
|
+
accountClosed: row.accountClosed,
|
|
212
|
+
suppressed: await isSuppressed(env.suppressionStore, address),
|
|
213
|
+
lastMarketingSentAt: row.sentTimestamps,
|
|
214
|
+
now: Date.now(),
|
|
215
|
+
});
|
|
216
|
+
return decision.allow;
|
|
217
|
+
}
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
## Testing your integration
|
|
221
|
+
|
|
222
|
+
`@simplycubed/email-guard/testing` exports in-memory stores and a fake resolver so your tests
|
|
223
|
+
never touch a network or a database:
|
|
224
|
+
|
|
225
|
+
```ts
|
|
226
|
+
import {
|
|
227
|
+
createMemoryThrottleStore,
|
|
228
|
+
createMemorySuppressionStore,
|
|
229
|
+
createFakeResolver,
|
|
230
|
+
} from "@simplycubed/email-guard/testing";
|
|
231
|
+
|
|
232
|
+
const resolver = createFakeResolver({
|
|
233
|
+
"example.com": { kind: "records", exchanges: ["mx.example.com"] },
|
|
234
|
+
});
|
|
235
|
+
await checkAddress("sam@example.com", { resolver });
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
## Development
|
|
239
|
+
|
|
240
|
+
```sh
|
|
241
|
+
pnpm install
|
|
242
|
+
pnpm check # lint, typecheck, tests with coverage thresholds, build, leak scan
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
Node 24 or newer. The leak scan (`scripts/no-leaks.mjs`) keeps product names, internal hostnames
|
|
246
|
+
and secret-shaped strings out of everything that ships.
|
|
247
|
+
|
|
248
|
+
## License
|
|
249
|
+
|
|
250
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,71 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@simplycubed/email-guard",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
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
|
+
"packageManager": "pnpm@11.5.2",
|
|
36
|
+
"publishConfig": {
|
|
37
|
+
"access": "public"
|
|
38
|
+
},
|
|
39
|
+
"repository": {
|
|
40
|
+
"type": "git",
|
|
41
|
+
"url": "git+https://github.com/simplycubed/email-guard.git"
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
45
|
+
"clean": "rm -rf dist coverage test-results",
|
|
46
|
+
"typecheck": "tsc --noEmit",
|
|
47
|
+
"lint": "eslint . && prettier --check .",
|
|
48
|
+
"lint:eslint": "eslint .",
|
|
49
|
+
"lint:fix": "eslint . --fix && prettier --write .",
|
|
50
|
+
"format": "prettier --write .",
|
|
51
|
+
"format:check": "prettier --check .",
|
|
52
|
+
"test": "vitest run",
|
|
53
|
+
"test:coverage": "vitest run --coverage",
|
|
54
|
+
"no-leaks": "node scripts/no-leaks.mjs",
|
|
55
|
+
"assert-tag-version": "node scripts/assert-tag-version.mjs",
|
|
56
|
+
"check": "pnpm lint && pnpm typecheck && pnpm test:coverage && pnpm build && pnpm no-leaks"
|
|
57
|
+
},
|
|
58
|
+
"dependencies": {},
|
|
59
|
+
"devDependencies": {
|
|
60
|
+
"@cloudflare/workers-types": "^4.20260529.1",
|
|
61
|
+
"@eslint/js": "^9.39.4",
|
|
62
|
+
"@types/node": "^25.9.1",
|
|
63
|
+
"@vitest/coverage-v8": "4.1.8",
|
|
64
|
+
"eslint": "^9.39.4",
|
|
65
|
+
"globals": "^17.6.0",
|
|
66
|
+
"prettier": "^3.8.3",
|
|
67
|
+
"typescript": "^5.8.3",
|
|
68
|
+
"typescript-eslint": "^8.60.1",
|
|
69
|
+
"vitest": "4.1.11"
|
|
70
|
+
}
|
|
71
|
+
}
|
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
|
+
};
|