@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/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";
@@ -0,0 +1,50 @@
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
+ return lowered.slice(0, at + 1) + lowered.slice(at + 1).replace(/\.+$/, "");
24
+ }
25
+
26
+ /** The two halves of a normalized address, or null when it has no single `@` to split on. */
27
+ export function splitAddress(email: string): { local: string; domain: string } | null {
28
+ const normalized = normalizeAddress(email);
29
+ const at = normalized.indexOf("@");
30
+ if (at <= 0 || at !== normalized.lastIndexOf("@") || at === normalized.length - 1) return null;
31
+ return { local: normalized.slice(0, at), domain: normalized.slice(at + 1) };
32
+ }
33
+
34
+ // Whitespace, C0/C1 controls, line separators and zero-width characters. None can appear in
35
+ // an address that is safe to put in a header, a token or a store key.
36
+ // eslint-disable-next-line no-control-regex -- matching control characters is the point
37
+ const UNSAFE_CHARS = /[\u0000-\u0020\u007f-\u009f\u00a0\u2028\u2029\u200b-\u200f\u2060\ufeff]/;
38
+
39
+ /**
40
+ * Internal guard for `signToken` and `suppress`, which accept any address a consumer has
41
+ * (including ones `checkAddress` would reject): exactly one `@`, both halves non-empty,
42
+ * at most 254 characters, and no whitespace, control or zero-width characters (CR and LF
43
+ * would be a header-injection vector in any mailer that trusted the value). Not exported
44
+ * from the package barrel.
45
+ */
46
+ export function isMailboxShaped(normalized: string): boolean {
47
+ return (
48
+ normalized.length <= 254 && !UNSAFE_CHARS.test(normalized) && splitAddress(normalized) !== null
49
+ );
50
+ }
@@ -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
+ }
@@ -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
+ }