@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/src/throttle.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
Throttle,
|
|
3
|
+
ThrottleCounter,
|
|
4
|
+
ThrottleResult,
|
|
5
|
+
ThrottleRule,
|
|
6
|
+
ThrottleStore,
|
|
7
|
+
} from "./types.js";
|
|
8
|
+
|
|
9
|
+
export interface ThrottleOptions {
|
|
10
|
+
/** Clock in epoch milliseconds. Defaults to `Date.now`. */
|
|
11
|
+
now?: () => number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const MAX_ID_LENGTH = 512;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* `fresh` is true for the counter an `increment` just returned: it is live by definition, so
|
|
18
|
+
* its `expiresAt` is not compared with this process's clock (a store clock that disagrees
|
|
19
|
+
* with ours must not switch the limit off). A counter from `get` is checked against `now`.
|
|
20
|
+
*/
|
|
21
|
+
function resultFor(
|
|
22
|
+
rule: ThrottleRule,
|
|
23
|
+
counter: ThrottleCounter | null,
|
|
24
|
+
now: number,
|
|
25
|
+
fresh: boolean,
|
|
26
|
+
): ThrottleResult {
|
|
27
|
+
if (counter === null || (!fresh && counter.expiresAt <= now)) {
|
|
28
|
+
return { allowed: true, remaining: rule.limit, retryAfterSeconds: 0 };
|
|
29
|
+
}
|
|
30
|
+
if (!Number.isFinite(counter.count) || counter.count < 1) {
|
|
31
|
+
throw new Error("email-guard: throttle store returned an invalid counter");
|
|
32
|
+
}
|
|
33
|
+
const allowed = counter.count <= rule.limit;
|
|
34
|
+
const wait = Math.ceil((counter.expiresAt - now) / 1000);
|
|
35
|
+
return {
|
|
36
|
+
allowed,
|
|
37
|
+
remaining: Math.max(0, rule.limit - counter.count),
|
|
38
|
+
retryAfterSeconds: allowed
|
|
39
|
+
? 0
|
|
40
|
+
: Math.min(rule.windowSeconds, Math.max(1, Number.isFinite(wait) ? wait : 1)),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Fixed-window rate limiter over a consumer-supplied counter store. Rules are named
|
|
46
|
+
* (`address`, `ip`, ...) and each call names a rule and an id, so one throttle serves a
|
|
47
|
+
* whole signup flow. Every `consume` counts, allowed or not: an attacker hammering a
|
|
48
|
+
* limit stays limited instead of resetting the window by being refused.
|
|
49
|
+
*
|
|
50
|
+
* Ids are used as given, up to 512 characters. Pass `normalizeAddress(email)` for address rules.
|
|
51
|
+
* Plus tags are not folded, so `a+1@x.com` and `a+2@x.com` are two ids: pair an address rule
|
|
52
|
+
* with an IP rule and a per-domain rule. Store errors propagate (the caller picks fail-open or
|
|
53
|
+
* fail-closed); the ids end up in the store's keys, so hash them if the store is shared or
|
|
54
|
+
* logged.
|
|
55
|
+
*/
|
|
56
|
+
export function createThrottle(
|
|
57
|
+
store: ThrottleStore,
|
|
58
|
+
rules: Readonly<Record<string, ThrottleRule>>,
|
|
59
|
+
options: ThrottleOptions = {},
|
|
60
|
+
): Throttle {
|
|
61
|
+
const clock = options.now ?? Date.now;
|
|
62
|
+
for (const [name, rule] of Object.entries(rules)) {
|
|
63
|
+
if (
|
|
64
|
+
!Number.isInteger(rule.limit) ||
|
|
65
|
+
rule.limit < 1 ||
|
|
66
|
+
!Number.isInteger(rule.windowSeconds) ||
|
|
67
|
+
rule.windowSeconds < 1
|
|
68
|
+
) {
|
|
69
|
+
throw new Error(
|
|
70
|
+
`email-guard: throttle rule "${name}" needs integer limit and windowSeconds >= 1`,
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const ruleFor = (name: string): ThrottleRule => {
|
|
76
|
+
const rule = Object.hasOwn(rules, name) ? rules[name] : undefined;
|
|
77
|
+
if (rule === undefined) throw new Error(`email-guard: unknown throttle rule "${name}"`);
|
|
78
|
+
return rule;
|
|
79
|
+
};
|
|
80
|
+
const assertId = (id: string): void => {
|
|
81
|
+
if (typeof id !== "string" || id.length === 0 || id.length > MAX_ID_LENGTH) {
|
|
82
|
+
throw new Error(`email-guard: throttle id must be 1 to ${MAX_ID_LENGTH} characters`);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
const keyFor = (rule: string, id: string): string => `eg:throttle:${rule}:${id}`;
|
|
86
|
+
|
|
87
|
+
async function consume(name: string, id: string): Promise<ThrottleResult> {
|
|
88
|
+
const rule = ruleFor(name);
|
|
89
|
+
assertId(id);
|
|
90
|
+
const counter = await store.increment(keyFor(name, id), rule.windowSeconds);
|
|
91
|
+
return resultFor(rule, counter, clock(), true);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function peek(name: string, id: string): Promise<ThrottleResult> {
|
|
95
|
+
const rule = ruleFor(name);
|
|
96
|
+
assertId(id);
|
|
97
|
+
return resultFor(rule, await store.get(keyFor(name, id)), clock(), false);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function consumeAll(
|
|
101
|
+
pairs: ReadonlyArray<readonly [rule: string, id: string]>,
|
|
102
|
+
): Promise<ThrottleResult> {
|
|
103
|
+
if (pairs.length === 0) throw new Error("email-guard: consumeAll needs at least one rule");
|
|
104
|
+
const results: ThrottleResult[] = [];
|
|
105
|
+
for (const [name, id] of pairs) results.push(await consume(name, id));
|
|
106
|
+
return {
|
|
107
|
+
allowed: results.every((r) => r.allowed),
|
|
108
|
+
remaining: Math.min(...results.map((r) => r.remaining)),
|
|
109
|
+
retryAfterSeconds: Math.max(...results.map((r) => r.retryAfterSeconds)),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return { consume, peek, consumeAll };
|
|
114
|
+
}
|
package/src/token.ts
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { isMailboxShaped, normalizeAddress } from "./normalize.js";
|
|
2
|
+
import type { TokenPayload, TokenResult, VerifyTokenOptions } from "./types.js";
|
|
3
|
+
|
|
4
|
+
const MIN_SECRET_LENGTH = 32;
|
|
5
|
+
const MAX_TOKEN_LENGTH = 2048;
|
|
6
|
+
const MAX_TTL_SECONDS = 400 * 24 * 60 * 60;
|
|
7
|
+
const PURPOSE_PATTERN = /^[a-z0-9][a-z0-9_.:-]{0,63}$/;
|
|
8
|
+
const DEFAULT_SKEW_SECONDS = 60;
|
|
9
|
+
const FORMAT_VERSION = 1;
|
|
10
|
+
|
|
11
|
+
const encoder = new TextEncoder();
|
|
12
|
+
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false });
|
|
13
|
+
|
|
14
|
+
function toBase64Url(bytes: Uint8Array): string {
|
|
15
|
+
let binary = "";
|
|
16
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
17
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function fromBase64Url(text: string): Uint8Array | null {
|
|
21
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1) return null;
|
|
22
|
+
const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.length + 3) % 4);
|
|
23
|
+
try {
|
|
24
|
+
return Uint8Array.from(atob(padded), (c) => c.charCodeAt(0));
|
|
25
|
+
} catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function assertSecret(secret: string): void {
|
|
31
|
+
if (typeof secret !== "string" || secret.length < MIN_SECRET_LENGTH) {
|
|
32
|
+
throw new Error(`email-guard: token secrets must be at least ${MIN_SECRET_LENGTH} characters`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function hmacKey(secret: string, usage: "sign" | "verify"): Promise<CryptoKey> {
|
|
37
|
+
return crypto.subtle.importKey(
|
|
38
|
+
"raw",
|
|
39
|
+
encoder.encode(secret),
|
|
40
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
41
|
+
false,
|
|
42
|
+
[usage],
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function assertPurpose(purpose: string): void {
|
|
47
|
+
if (!PURPOSE_PATTERN.test(purpose)) {
|
|
48
|
+
throw new Error("email-guard: purpose must match /^[a-z0-9][a-z0-9_.:-]{0,63}$/");
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Stateless signed token: `base64url(payload).base64url(HMAC-SHA256(payload))`, built on
|
|
54
|
+
* Web Crypto so it runs on Workers and Node alike. There is no database row behind it, so
|
|
55
|
+
* a double opt-in confirm link or an unsubscribe link costs no storage.
|
|
56
|
+
*
|
|
57
|
+
* Pass one secret, or an array for key rotation: the FIRST is used to sign, and
|
|
58
|
+
* `verifyToken` accepts any of them. The address is normalized before signing. A token is
|
|
59
|
+
* bearer proof of one purpose for one address until it expires, nothing more.
|
|
60
|
+
*/
|
|
61
|
+
export async function signToken(
|
|
62
|
+
payload: TokenPayload,
|
|
63
|
+
secret: string | readonly string[],
|
|
64
|
+
): Promise<string> {
|
|
65
|
+
const signingSecret = typeof secret === "string" ? secret : secret[0];
|
|
66
|
+
if (signingSecret === undefined) throw new Error("email-guard: no signing secret supplied");
|
|
67
|
+
assertSecret(signingSecret);
|
|
68
|
+
assertPurpose(payload.purpose);
|
|
69
|
+
if (!Number.isInteger(payload.ttlSeconds) || payload.ttlSeconds <= 0) {
|
|
70
|
+
throw new Error("email-guard: ttlSeconds must be a positive integer");
|
|
71
|
+
}
|
|
72
|
+
if (payload.ttlSeconds > MAX_TTL_SECONDS) {
|
|
73
|
+
throw new Error("email-guard: ttlSeconds exceeds the 400 day maximum");
|
|
74
|
+
}
|
|
75
|
+
const address = normalizeAddress(payload.address);
|
|
76
|
+
if (!isMailboxShaped(address)) {
|
|
77
|
+
throw new Error("email-guard: token address is not an email address");
|
|
78
|
+
}
|
|
79
|
+
const issuedAt = payload.issuedAt ?? Date.now();
|
|
80
|
+
if (!Number.isInteger(issuedAt) || issuedAt < 0) {
|
|
81
|
+
throw new Error("email-guard: issuedAt must be epoch milliseconds");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const body = toBase64Url(
|
|
85
|
+
encoder.encode(
|
|
86
|
+
JSON.stringify({
|
|
87
|
+
v: FORMAT_VERSION,
|
|
88
|
+
p: payload.purpose,
|
|
89
|
+
a: address,
|
|
90
|
+
i: issuedAt,
|
|
91
|
+
e: issuedAt + payload.ttlSeconds * 1000,
|
|
92
|
+
}),
|
|
93
|
+
),
|
|
94
|
+
);
|
|
95
|
+
const key = await hmacKey(signingSecret, "sign");
|
|
96
|
+
const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(body)));
|
|
97
|
+
return `${body}.${toBase64Url(mac)}`;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
interface DecodedBody {
|
|
101
|
+
p: string;
|
|
102
|
+
a: string;
|
|
103
|
+
i: number;
|
|
104
|
+
e: number;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function decodeBody(body: string): DecodedBody | null {
|
|
108
|
+
const bytes = fromBase64Url(body);
|
|
109
|
+
if (bytes === null) return null;
|
|
110
|
+
let parsed: unknown;
|
|
111
|
+
try {
|
|
112
|
+
parsed = JSON.parse(decoder.decode(bytes));
|
|
113
|
+
} catch {
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
if (typeof parsed !== "object" || parsed === null) return null;
|
|
117
|
+
const { v, p, a, i, e } = parsed as Record<string, unknown>;
|
|
118
|
+
if (v !== FORMAT_VERSION) return null;
|
|
119
|
+
if (typeof p !== "string" || typeof a !== "string") return null;
|
|
120
|
+
if (typeof i !== "number" || typeof e !== "number") return null;
|
|
121
|
+
return { p, a, i, e };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Check a token. The signature is verified first and the payload is only trusted after.
|
|
126
|
+
* Signature comparison is `crypto.subtle.verify`, which is constant time, and every
|
|
127
|
+
* supplied secret is tried without early exit so rotation does not leak which key matched.
|
|
128
|
+
* A token signed for another purpose fails with `wrong_purpose` even if the signature is
|
|
129
|
+
* good, so a confirm link can never double as an unsubscribe link.
|
|
130
|
+
*/
|
|
131
|
+
export async function verifyToken(
|
|
132
|
+
token: string,
|
|
133
|
+
secret: string | readonly string[],
|
|
134
|
+
options: VerifyTokenOptions,
|
|
135
|
+
): Promise<TokenResult> {
|
|
136
|
+
const secrets = typeof secret === "string" ? [secret] : [...secret];
|
|
137
|
+
if (secrets.length === 0) throw new Error("email-guard: no verification secret supplied");
|
|
138
|
+
for (const s of secrets) assertSecret(s);
|
|
139
|
+
assertPurpose(options.purpose);
|
|
140
|
+
|
|
141
|
+
if (typeof token !== "string" || token.length === 0 || token.length > MAX_TOKEN_LENGTH) {
|
|
142
|
+
return { valid: false, reason: "malformed" };
|
|
143
|
+
}
|
|
144
|
+
const parts = token.split(".");
|
|
145
|
+
if (parts.length !== 2) return { valid: false, reason: "malformed" };
|
|
146
|
+
const [body, mac] = parts as [string, string];
|
|
147
|
+
const macBytes = fromBase64Url(mac);
|
|
148
|
+
if (body.length === 0 || macBytes === null || macBytes.length !== 32) {
|
|
149
|
+
return { valid: false, reason: "malformed" };
|
|
150
|
+
}
|
|
151
|
+
// Reject non-canonical base64url (spare trailing bits set): several strings would otherwise
|
|
152
|
+
// decode to one MAC, so a consumer's "token already used" set keyed on the string could be
|
|
153
|
+
// dodged by flipping the last character.
|
|
154
|
+
if (toBase64Url(macBytes) !== mac) return { valid: false, reason: "malformed" };
|
|
155
|
+
|
|
156
|
+
let matched = false;
|
|
157
|
+
for (const s of secrets) {
|
|
158
|
+
const key = await hmacKey(s, "verify");
|
|
159
|
+
const ok = await crypto.subtle.verify("HMAC", key, macBytes, encoder.encode(body));
|
|
160
|
+
matched = matched || ok;
|
|
161
|
+
}
|
|
162
|
+
if (!matched) return { valid: false, reason: "bad_signature" };
|
|
163
|
+
|
|
164
|
+
const decoded = decodeBody(body);
|
|
165
|
+
if (decoded === null) return { valid: false, reason: "malformed" };
|
|
166
|
+
if (decoded.p !== options.purpose) return { valid: false, reason: "wrong_purpose" };
|
|
167
|
+
|
|
168
|
+
const now = options.now ?? Date.now();
|
|
169
|
+
const skewMs = (options.clockSkewSeconds ?? DEFAULT_SKEW_SECONDS) * 1000;
|
|
170
|
+
if (decoded.i - skewMs > now) return { valid: false, reason: "not_yet_valid" };
|
|
171
|
+
if (now >= decoded.e) return { valid: false, reason: "expired" };
|
|
172
|
+
|
|
173
|
+
return {
|
|
174
|
+
valid: true,
|
|
175
|
+
purpose: decoded.p,
|
|
176
|
+
address: decoded.a,
|
|
177
|
+
issuedAt: decoded.i,
|
|
178
|
+
expiresAt: decoded.e,
|
|
179
|
+
};
|
|
180
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/** Result of one MX lookup. A lookup that could not be completed is `error`, never a guess. */
|
|
2
|
+
export type MxLookup =
|
|
3
|
+
| {
|
|
4
|
+
kind: "records";
|
|
5
|
+
/** Mail exchanger hostnames. An empty list means the domain exists but takes no mail. */
|
|
6
|
+
exchanges: readonly string[];
|
|
7
|
+
}
|
|
8
|
+
| { kind: "nxdomain" }
|
|
9
|
+
| { kind: "error"; message: string };
|
|
10
|
+
|
|
11
|
+
/** Injectable DNS resolver. The default is `createDohResolver()`. */
|
|
12
|
+
export interface DnsResolver {
|
|
13
|
+
resolveMx(domain: string): Promise<MxLookup>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type AddressVerdict = "valid" | "risky" | "invalid";
|
|
17
|
+
|
|
18
|
+
export type AddressReason =
|
|
19
|
+
| "invalid_syntax"
|
|
20
|
+
| "domain_not_found"
|
|
21
|
+
| "no_mx"
|
|
22
|
+
| "null_mx"
|
|
23
|
+
| "mx_lookup_failed"
|
|
24
|
+
| "disposable_domain"
|
|
25
|
+
| "typo_domain"
|
|
26
|
+
| "role_address";
|
|
27
|
+
|
|
28
|
+
export interface AddressCheck {
|
|
29
|
+
verdict: AddressVerdict;
|
|
30
|
+
reasons: AddressReason[];
|
|
31
|
+
/** The normalized address (see `normalizeAddress`). */
|
|
32
|
+
address: string;
|
|
33
|
+
/** Present with `typo_domain`: the full address the user probably meant. */
|
|
34
|
+
suggestion?: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface CheckAddressOptions {
|
|
38
|
+
/** Resolver for the MX layer. Defaults to a Cloudflare DNS-over-HTTPS resolver. */
|
|
39
|
+
resolver?: DnsResolver;
|
|
40
|
+
/** Skip the MX layer entirely (no network). Defaults to false. */
|
|
41
|
+
skipMx?: boolean;
|
|
42
|
+
/** Extra throwaway domains, added to the bundled seed list. */
|
|
43
|
+
extraDisposableDomains?: Iterable<string>;
|
|
44
|
+
/** `invalid` (default) rejects disposable domains; `risky` only flags them. */
|
|
45
|
+
disposablePolicy?: "invalid" | "risky";
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export type ConsentDenyReason =
|
|
49
|
+
"suppressed" | "account_closed" | "not_confirmed" | "daily_cap" | "monthly_cap";
|
|
50
|
+
|
|
51
|
+
export interface MarketingState {
|
|
52
|
+
/** The address clicked a double opt-in confirm link (a lead). */
|
|
53
|
+
confirmed: boolean;
|
|
54
|
+
/** The address belongs to an account whose email was verified. */
|
|
55
|
+
accountVerified?: boolean;
|
|
56
|
+
/** The account is closed or deactivated. */
|
|
57
|
+
accountClosed?: boolean;
|
|
58
|
+
/**
|
|
59
|
+
* The address is on a suppression list. Required, and anything but an explicit `false`
|
|
60
|
+
* denies, so forgetting the lookup can never read as "not suppressed".
|
|
61
|
+
*/
|
|
62
|
+
suppressed: boolean;
|
|
63
|
+
/** Epoch milliseconds of each marketing email already sent to this address. */
|
|
64
|
+
lastMarketingSentAt: readonly number[];
|
|
65
|
+
/** Epoch milliseconds, supplied by the caller so the decision stays pure. */
|
|
66
|
+
now: number;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface MarketingCaps {
|
|
70
|
+
/** Maximum marketing emails per rolling 24 hours. Default 1. */
|
|
71
|
+
perDay?: number;
|
|
72
|
+
/** Maximum marketing emails per rolling 30 days. Default 12. */
|
|
73
|
+
perMonth?: number;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export type MarketingDecision =
|
|
77
|
+
{ allow: true; reason: "ok" } | { allow: false; reason: ConsentDenyReason; retryAt?: number };
|
|
78
|
+
|
|
79
|
+
export interface TokenPayload {
|
|
80
|
+
/** What the token is for, for example `confirm` or `unsubscribe`. Binds the token. */
|
|
81
|
+
purpose: string;
|
|
82
|
+
address: string;
|
|
83
|
+
/** Epoch milliseconds. Defaults to now. */
|
|
84
|
+
issuedAt?: number;
|
|
85
|
+
/** Lifetime in seconds. */
|
|
86
|
+
ttlSeconds: number;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export type TokenFailure =
|
|
90
|
+
"malformed" | "bad_signature" | "wrong_purpose" | "expired" | "not_yet_valid";
|
|
91
|
+
|
|
92
|
+
export type TokenResult =
|
|
93
|
+
| {
|
|
94
|
+
valid: true;
|
|
95
|
+
purpose: string;
|
|
96
|
+
/** Normalized address. */
|
|
97
|
+
address: string;
|
|
98
|
+
issuedAt: number;
|
|
99
|
+
expiresAt: number;
|
|
100
|
+
}
|
|
101
|
+
| { valid: false; reason: TokenFailure };
|
|
102
|
+
|
|
103
|
+
export interface VerifyTokenOptions {
|
|
104
|
+
/** The purpose the caller expects. A correctly signed token for another purpose fails. */
|
|
105
|
+
purpose: string;
|
|
106
|
+
/** Epoch milliseconds. Defaults to now. */
|
|
107
|
+
now?: number;
|
|
108
|
+
/** Tolerated clock skew for `issuedAt` in the future, in seconds. Default 60. */
|
|
109
|
+
clockSkewSeconds?: number;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export interface ThrottleRule {
|
|
113
|
+
limit: number;
|
|
114
|
+
windowSeconds: number;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export interface ThrottleCounter {
|
|
118
|
+
count: number;
|
|
119
|
+
/** Epoch milliseconds at which the counter resets. */
|
|
120
|
+
expiresAt: number;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Counter storage supplied by the consumer. `increment` MUST be atomic and MUST set the
|
|
125
|
+
* expiry only when it creates the counter (fixed window). Workers KV is not atomic and is
|
|
126
|
+
* the wrong backing store; use a Durable Object, SQL database or Postgres upsert.
|
|
127
|
+
*/
|
|
128
|
+
export interface ThrottleStore {
|
|
129
|
+
get(key: string): Promise<ThrottleCounter | null>;
|
|
130
|
+
increment(key: string, ttlSeconds: number): Promise<ThrottleCounter>;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export interface ThrottleResult {
|
|
134
|
+
allowed: boolean;
|
|
135
|
+
remaining: number;
|
|
136
|
+
retryAfterSeconds: number;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export interface Throttle {
|
|
140
|
+
/** Count one attempt against `rule` for `id` and say whether it is within the limit. */
|
|
141
|
+
consume(rule: string, id: string): Promise<ThrottleResult>;
|
|
142
|
+
/** Read the current state without counting an attempt. */
|
|
143
|
+
peek(rule: string, id: string): Promise<ThrottleResult>;
|
|
144
|
+
/** Count one attempt against every pair. Allowed only if all are. */
|
|
145
|
+
consumeAll(pairs: ReadonlyArray<readonly [rule: string, id: string]>): Promise<ThrottleResult>;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export type SuppressionReason = "unsubscribe" | "hard_bounce" | "complaint" | "manual";
|
|
149
|
+
|
|
150
|
+
export interface SuppressionEntry {
|
|
151
|
+
/** Always normalized. */
|
|
152
|
+
address: string;
|
|
153
|
+
reason: SuppressionReason;
|
|
154
|
+
/** Which product or system recorded it. Free text chosen by the consumer. */
|
|
155
|
+
source: string;
|
|
156
|
+
/** Epoch milliseconds. */
|
|
157
|
+
addedAt: number;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Suppression storage supplied by the consumer. Receives normalized addresses only. */
|
|
161
|
+
export interface SuppressionStore {
|
|
162
|
+
add(entry: SuppressionEntry): Promise<void>;
|
|
163
|
+
has(address: string): Promise<boolean>;
|
|
164
|
+
}
|