// SPDX-License-Identifier: MIT // // MIT License // // Copyright (c) 2026 Email Validation LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. /** * email-validation.org for BDOW! (formerly Sumo): check the email address of each new subscriber. One file, no * dependencies; run it on your own server (Node 22.18+, Bun, Deno, Cloudflare Workers: anything with `fetch` and Web * Crypto; older Node through a TypeScript build step). * * BDOW!'s site webhook (a paid plan; Site Settings → Integrations, at the bottom) sends your URL one JSON event per * subscription through any of the site's campaign forms: `{ eventType: "FORM_SUBSCRIPTION", eventDate, email, siteId, * formId, executionContext: "LIVE", metadata }` (`metadata`: the form's field names and values). The Send Test button * sends the same event with `executionContext: "TEST"`, a placeholder address and no `formId`; a `PING` event carries * only `eventType` and `eventDate`. BDOW! does not sign its webhooks and lets you set only the URL, so the receiver asks * for a token of your own in the URL's `token` query parameter, compared in constant time before the body is read. * * The subscriber already exists when the event is sent and BDOW! does not document that it reads the answer, so nothing * here can stop a subscription: the receiver answers `200` at once and then checks `email` with one * `POST /v1/validate`. Your `onResult` callback gets each subscriber with the verdict (`flagged` when the status is one * you flag, default only a definite `invalid`), so your own code can unsubscribe, tag or skip them in your mail tool. * `PING`, `TEST` and any other event start nothing. * * Answers are remembered by the address's SHA-256 (never the address); a remembered answer is given again without a * new check, so a later timeout or `unknown` never clears an earlier verdict, and a repeated delivery costs nothing. Our * refused key, no credits or the key's daily cap pause the checks for five minutes; a rate limit for its `Retry-After`. * Our API key goes only to our API; redirects are never followed; nothing here logs or answers an address, a key or a * token. */ export const VERSION = '1.0.0'; export const USER_AGENT = `email-validation-sumo/${VERSION}`; /** Our API's two hosts: `eu` has addresses validated in the EU and their results stored there (same keys and credits). */ export const API_ORIGINS = Object.freeze({ us: 'https://api.email-validation.org', eu: 'https://api-eu.email-validation.org', }); /** The five statuses an answer can have. */ export const STATUSES = Object.freeze(['valid', 'invalid', 'catch_all', 'unknown', 'disposable'] as const); export type Status = (typeof STATUSES)[number]; /** The statuses you may flag. A `valid` answer is clean, unless it is marked disposable and `disposable` is flagged. */ export const FLAGGABLE = Object.freeze(['invalid', 'disposable', 'catch_all', 'unknown'] as const); export type FlaggableStatus = (typeof FLAGGABLE)[number]; /** `unknown` answers that mean our side ran out of time or failed: never flagged, even with `unknown` in `flag`. */ export const NEVER_FLAG_REASONS = Object.freeze(['timeout', 'internal_error'] as const); /** The one event that is checked, and only in its `LIVE` form. */ export const SUBSCRIPTION_EVENT = 'FORM_SUBSCRIPTION'; export const LIVE = 'LIVE'; export const DEFAULTS = Object.freeze({ /** Only an address that cannot receive mail is flagged by default. */ flag: Object.freeze(['invalid'] as const), /** * How long a check may take before the subscriber stays unchecked: a little over the API's own 5-second limit, so a * check that needs longer comes back as a free `unknown` first. */ timeoutMs: 6000, }); /** The API's shortest check time, in seconds: a check that needs longer ends as a free `unknown`. */ export const SERVER_TIMEOUT_S = 5; /** The largest body read (bytes): one subscription with its form fields stays far below it. */ export const MAX_BODY_BYTES = 64 * 1024; /** Answers remembered per instance (without a `store`). */ export const MEMORY_MAX = 1000; /** * How long an answer stays in the instance's memory (without a `store`): a day, so an address answered `invalid` for a * while (a full mailbox, a domain being moved) is checked again rather than flagged for the life of the process. */ export const MEMORY_TTL_MS = 24 * 60 * 60 * 1000; /** The longest a `store` read or write may take before it is treated as a miss (read) or skipped (write). */ export const STORE_TIMEOUT_MS = 1000; /** After a 429 or 503 from our API without Retry-After, checks pause this long; a longer Retry-After is cut. */ export const DEFAULT_PAUSE_S = 30; export const MAX_PAUSE_S = 300; /** * Our API's error codes that pause the checks for MAX_PAUSE_S: the key is refused, out of credits or over its daily * cap, so every check meanwhile would fail the same way (and a 401 repeated is a key being guessed at). */ export const STOP_CODES = Object.freeze([ 'unauthorized', 'forbidden', 'insufficient_credits', 'key_daily_cap', ] as const); /** The shortest `bridgeToken` accepted: it is the only thing guarding the receiver's URL. */ export const MIN_BRIDGE_TOKEN_LENGTH = 24; export type FetchFn = (input: string, init?: RequestInit) => Promise; export interface CheckOptions { /** Your email-validation.org API key (permission "Validate addresses"). Server-side only: read it from env. */ apiKey: string | undefined; /** `us` (default) or `eu`. */ region?: 'us' | 'eu'; /** The statuses that flag an address (default `invalid`). */ flag?: readonly FlaggableStatus[]; /** Milliseconds before the subscriber stays unchecked (whole milliseconds from 1 to 60000; default 6000). */ timeoutMs?: number; /** For tests and proxies; default: the global fetch. */ fetch?: FetchFn; } export interface Decision { /** True only when a definite answer's status is one you flag. */ flagged: boolean; /** The answer's status, or null when there was no answer (then `error` says why). */ status: Status | null; reason: string | null; /** * Why there is no verdict: `missing_key`, `no_address`, `not_an_address`, `paused`, `timeout`, `connection_error`, * `unexpected_response` or the API's error code; in the receiver's results also (with a status) our own `timeout` or * `internal_error` answer. */ error: string | null; requestId: string | null; } interface Settings { apiKey: string; origin: string; flag: readonly FlaggableStatus[]; timeoutMs: number; fetch: FetchFn; } /** What is remembered about an address (under its SHA-256): enough to decide again under the current `flag`. */ export interface Remembered { status: Status; reason: string | null; disposable: boolean; requestId: string | null; } /** Surrounding whitespace (a pasted line break) is trimmed; a key with whitespace inside is no key. */ function keyOf(value: unknown): string { const trimmed = typeof value === 'string' ? value.trim() : ''; return /^\S+$/.test(trimmed) ? trimmed : ''; } function isObject(v: unknown): v is Record { return v !== null && typeof v === 'object' && !Array.isArray(v); } function positiveMs(value: unknown, name: string): number { // Whole milliseconds up to a minute: AbortSignal.timeout throws on a fraction or a huge value. if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0 || value > 60_000) { throw new TypeError(`${name} must be a whole number of milliseconds from 1 to 60000.`); } return value; } function settings(options: CheckOptions): Settings { if (!options || typeof options !== 'object') throw new TypeError('Options are required.'); const region = options.region ?? 'us'; if (region !== 'us' && region !== 'eu') throw new TypeError(`region must be "us" or "eu", not ${String(region)}.`); const flag = options.flag ?? DEFAULTS.flag; if (!Array.isArray(flag) || flag.some((s) => !(FLAGGABLE as readonly string[]).includes(s))) { throw new TypeError(`flag must list only ${FLAGGABLE.join(', ')}.`); } return { apiKey: keyOf(options.apiKey), origin: API_ORIGINS[region], flag: Object.freeze([...flag]), timeoutMs: positiveMs(options.timeoutMs ?? DEFAULTS.timeoutMs, 'timeoutMs'), fetch: options.fetch ?? ((input: string, init?: RequestInit) => globalThis.fetch(input, init)), }; } function unchecked(error: string, requestId: string | null = null): Decision { return { flagged: false, status: null, reason: null, error, requestId }; } /** * Whether a value is worth a check: something@domain.tld with no spaces, no control characters and nothing of a link * (`:`, `/`, `?`, `#`): a link with an `@` in it, or a `mailto:`, is never sent. */ export function looksLikeAddress(value: unknown): value is string { if (typeof value !== 'string') return false; const v = value.trim(); return v.length <= 254 && !/\p{Cc}/u.test(v) && /^[^\s@:/]+@[^\s@:/?#]+\.[^\s@.:/?#]{2,}$/.test(v); } /** Retry-After in seconds: delay-seconds or an IMF-fixdate HTTP date; anything else is null. */ export function retryAfter(value: string | null, nowMs: number): number | null { if (typeof value !== 'string') return null; const t = value.trim(); if (/^\d+$/.test(t)) return Number(t); if (!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(t)) return null; const at = Date.parse(t); return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - nowMs) / 1000)); } /** * One request to an allowed origin only, redirects never followed, bounded by `timeoutMs`. Rejects on a foreign host, * no answer or a redirect; answers the Response for any other status. */ export async function send( fetchFn: FetchFn, origin: string, url: string, init: RequestInit, timeoutMs: number, ): Promise { if (new URL(url).origin !== origin) throw new Error(`Refused a request to a host other than ${origin}.`); const headers = new Headers(init.headers); headers.set('User-Agent', USER_AGENT); const response = await fetchFn(url, { ...init, headers, redirect: 'manual', signal: AbortSignal.timeout(timeoutMs) }); if ((response.status >= 300 && response.status < 400) || response.type === 'opaqueredirect') { await discard(response); throw new Error('redirect'); } return response; } async function discard(response: Response): Promise { try { await response.body?.cancel(); } catch { // already closed } } function isTimeout(err: unknown): boolean { const name = err instanceof Error ? err.name : ''; return name === 'TimeoutError' || name === 'AbortError'; } function flaggedFor(s: Settings, status: Status, reason: string | null, disposable: boolean): boolean { const ourFailure = status === 'unknown' && (NEVER_FLAG_REASONS as readonly string[]).includes(reason ?? ''); return ( !ourFailure && ((s.flag as readonly string[]).includes(status) || (s.flag.includes('disposable') && disposable)) ); } interface Checked { decision: Decision; /** Only a definite answer that is not `unknown` is remembered. */ remember: Remembered | null; /** Seconds the checks should pause (our refused key, no credits, the daily cap, a 429 or 503), or null. */ pauseS: number | null; } /** True when `text` holds 12 or more characters of the key in a row: such a value is never kept. */ function sharesKey(text: string, key: string): boolean { const run = 12; if (key.length < run) return key !== '' && text.includes(key); for (let i = 0; i + run <= key.length; i++) if (text.includes(key.slice(i, i + run))) return true; return false; } /** Our error code as sent (lowercase, digits, `_`), never cleaned into shape: anything else is no code. */ function codeOf(value: unknown, key: string): string { return typeof value === 'string' && /^[a-z][a-z0-9_]{0,63}$/.test(value) && !sharesKey(value, key) ? value : ''; } /** A request id of our shape (`req_` and letters or digits), else null. */ function requestIdOf(value: unknown, key: string): string | null { return typeof value === 'string' && /^req_[A-Za-z0-9]{1,60}$/.test(value) && !sharesKey(value, key) ? value : null; } /** One of our reasons (lowercase and `_`), else null. */ function reasonOf(value: unknown, key: string): string | null { return typeof value === 'string' && /^[a-z_]{1,64}$/.test(value) && !sharesKey(value, key) ? value : null; } async function check(s: Settings, email: unknown): Promise { const none = (error: string, requestId: string | null = null, pauseS: number | null = null): Checked => ({ decision: unchecked(error, requestId), remember: null, pauseS, }); if (!s.apiKey) return none('missing_key'); if (!looksLikeAddress(email)) return none('not_an_address'); let response: Response; try { response = await send( s.fetch, s.origin, `${s.origin}/v1/validate`, { method: 'POST', headers: { Authorization: `Bearer ${s.apiKey}`, 'Content-Type': 'application/json', Accept: 'application/json', }, body: JSON.stringify({ email: email.trim(), timeout: SERVER_TIMEOUT_S }), }, s.timeoutMs, ); } catch (err) { if (isTimeout(err)) return none('timeout'); if (err instanceof Error && err.message === 'redirect') return none('unexpected_response'); return none('connection_error'); } let body: unknown = null; try { body = await response.json(); } catch (err) { if (isTimeout(err)) return none('timeout'); } const record = isObject(body) ? body : {}; const headerId = requestIdOf(response.headers.get('x-request-id'), s.apiKey); if (!response.ok) { const error = isObject(record.error) ? record.error : {}; const code = codeOf(error.code, s.apiKey); const requestId = requestIdOf(error.request_id, s.apiKey) ?? headerId; // Our API's own refused key, no credits or daily cap (its error envelope's code, never a bare status, which an // edge page could send) pauses checks for MAX_PAUSE_S; a 429 or 503 pauses for its Retry-After. const stops = (STOP_CODES as readonly string[]).includes(code); const pauses = response.status === 429 || response.status === 503; const pauseS = stops ? MAX_PAUSE_S : pauses ? Math.min(retryAfter(response.headers.get('retry-after'), Date.now()) ?? DEFAULT_PAUSE_S, MAX_PAUSE_S) : null; return none(code || `http_${response.status}`, requestId, pauseS); } const status = record.status; const requestId = requestIdOf(record.request_id, s.apiKey) ?? headerId; if (typeof status !== 'string' || !(STATUSES as readonly string[]).includes(status)) { return none('unexpected_response', requestId); } const reason = reasonOf(record.reason, s.apiKey); const disposable = record.disposable === true; const flagged = flaggedFor(s, status as Status, reason, disposable); // An `unknown` (free) is never remembered: it says nothing definite, so it never stands in for a later answer. const remember = status === 'unknown' ? null : { status: status as Status, reason, disposable, requestId }; return { decision: { flagged, status: status as Status, reason, error: null, requestId }, remember, pauseS: null }; } /** * A checker for one configuration (options are checked once, here), for your own code. Never rejects. Each check * uses one credit (`unknown`, malformed and sandbox addresses are free). */ export function createEmailCheck(options: CheckOptions): (email: string) => Promise { const s = settings(options); return (email) => check(s, email) .then((c) => c.decision) .catch(() => unchecked('internal_error')); } // --------------------------------------------------------------------------------------------------------------- // The webhook receiver. /** * Where answers are remembered across restarts (Workers KV, Redis, a database table). Keys are * `ev-sumo:`, never the address. Errors are ignored (the receiver then checks, or forgets). */ export interface Store { get(key: string): Promise | Remembered | null | undefined; set(key: string, value: Remembered): Promise | void; } export interface ReceiverOptions extends CheckOptions { /** * A random token of your own, at least 24 characters of letters, digits, `-`, `_`, `.` and `~` (e.g. * `openssl rand -hex 24`), from env: characters that pass through a URL unchanged. BDOW! sends it in the webhook URL * you give it, as `?token=`. */ bridgeToken: string | undefined; /** * The BDOW! site ids whose events are taken (the `siteId` of a Send Test delivery). Default: any site that knows the * token. With a list, an event of another site is refused with `403` and starts nothing. */ siteIds?: readonly string[]; /** Keeps answers across restarts and instances. Default: this instance's memory (up to 1,000 addresses). */ store?: Store; /** * Called once per live subscription event (with or without a usable address), after the answer, with the verdict and * BDOW!'s event as received (it holds the address and the form's fields: keep it out of your logs). Awaited inside * `done`; errors are ignored. */ onResult?: (result: SubscriberResult) => void | Promise; /** Keeps the check running after the answer (Next.js `after`, Vercel `waitUntil`); Workers: pass `ctx` instead. */ waitUntil?: (work: Promise) => void; /** * The answers this handler remembers, by the address's SHA-256 (never the address), oldest first. Default: a new * one per handler. Tests pass their own to fill it to MEMORY_MAX directly instead of with a thousand checks. */ memory?: Map; } export type Outcome = 'clean' | 'flagged' | 'unchecked'; interface Verdict { outcome: Outcome; remembered: boolean; decision: Decision; } export interface SubscriberResult { /** The event's site id (letters, digits, `_`, `-`), or null. */ siteId: string | null; /** The campaign form's id (letters, digits, `_`, `-`), or null when the event has none. */ formId: string | null; /** `clean`; `flagged` (a status you flag); or `unchecked` (no verdict: `decision.error` says why). */ outcome: Outcome; /** True when the answer was remembered from an earlier check (no request was sent). */ remembered: boolean; decision: Decision; /** BDOW!'s event as received (`email`, `siteId`, `formId`, `eventDate`, `metadata`, …). */ delivery: Record; } /** The answer to BDOW!. Never holds an address. */ export type AnswerBody = { accepted: true } | { ready: true } | { error: string }; export interface ReceiverResponse { status: number; body: AnswerBody; /** * Settles once the subscriber is checked, the answer remembered and `onResult` has run (null when the delivery * starts no check: refused, empty, a `PING`, a `TEST` or another event). Never rejects. */ done: Promise; } export interface Delivery { /** The raw body. */ body: string | Uint8Array; /** The request URL (or its path and query, e.g. Express's `req.originalUrl`): read for the `?token=` only. */ url: string | undefined; } const encoder = new TextEncoder(); const STORE_PREFIX = 'ev-sumo:'; const ID = /^[A-Za-z0-9_-]{1,64}$/; /** `work`, or `fallback` once STORE_TIMEOUT_MS has passed (a hung store never holds the check). */ async function within(work: Promise, fallback: F): Promise { let timer: ReturnType | undefined; const late = new Promise((resolve) => { timer = setTimeout(() => resolve(fallback), STORE_TIMEOUT_MS); }); try { return await Promise.race([work, late]); } finally { clearTimeout(timer); } } function toHex(bytes: Uint8Array): string { let out = ''; for (const b of bytes) out += b.toString(16).padStart(2, '0'); return out; } async function sha256(text: string): Promise { return new Uint8Array(await crypto.subtle.digest('SHA-256', encoder.encode(text) as BufferSource)); } function sameBytes(a: Uint8Array, b: Uint8Array): boolean { if (a.length !== b.length) return false; let diff = 0; for (let i = 0; i < a.length; i++) diff |= (a[i] as number) ^ (b[i] as number); return diff === 0; } /** The URL's one `token` query parameter; null when there is none, an empty one, or more than one. */ function tokenOf(url: string | undefined): string | null { if (typeof url !== 'string' || !url) return null; let given: string[]; try { given = new URL(url, 'http://receiver.invalid').searchParams.getAll('token'); } catch { return null; } return given.length === 1 && given[0] ? given[0] : null; } /** Compares the delivery's token with yours in constant time (both hashed first, so lengths do not leak). */ async function sameToken(given: string | null, expected: string): Promise { if (given === null) return false; return sameBytes(await sha256(given), await sha256(expected)); } function rememberedOf(value: unknown): Remembered | null { if (!isObject(value)) return null; const { status, reason, disposable, requestId } = value; if (typeof status !== 'string' || status === 'unknown' || !(STATUSES as readonly string[]).includes(status)) { return null; } return { status: status as Status, reason: typeof reason === 'string' ? reason : null, disposable: disposable === true, requestId: typeof requestId === 'string' ? requestId : null, }; } function bridgeTokenOf(value: unknown): string { const token = typeof value === 'string' ? value.trim() : ''; // Only characters a URL query carries unchanged: a `+`, `&`, `#` or `%` would arrive changed, and every event would // be refused. if (token.length < MIN_BRIDGE_TOKEN_LENGTH || !/^[A-Za-z0-9._~-]+$/.test(token)) { throw new TypeError( `bridgeToken must be at least ${MIN_BRIDGE_TOKEN_LENGTH} characters of letters, digits, -, _, . and ~.`, ); } return token; } function siteIdsOf(value: unknown): ReadonlySet | null { if (value === undefined) return null; if (!Array.isArray(value) || value.length === 0 || value.some((id) => typeof id !== 'string' || !ID.test(id))) { throw new TypeError('siteIds must be a non-empty list of site ids (letters, digits, _ and -).'); } return new Set(value as string[]); } /** An id the event carries, as a string when it has the shape of one; else null. */ function idOf(value: unknown): string | null { return (typeof value === 'string' || typeof value === 'number') && ID.test(String(value)) ? String(value) : null; } const nothing: Promise = Promise.resolve(null); /** * Handles one delivery from BDOW!. Answers `401` without the right token (the body is not parsed), `400` for a body * that is not a JSON object, `403` for a site not in `siteIds`, and `200` for everything else, before any check. Only a * `LIVE` `FORM_SUBSCRIPTION` starts one; it runs in `done`. */ export function createSumoWebhookHandler(options: ReceiverOptions): (delivery: Delivery) => Promise { const s = settings(options); const bridgeToken = bridgeTokenOf(options.bridgeToken); const siteIds = siteIdsOf(options.siteIds); const store = options.store; if (store !== undefined && (typeof store?.get !== 'function' || typeof store?.set !== 'function')) { throw new TypeError('store must have get and set.'); } // Keyed by the address's SHA-256 (never the address), each with the time it expires (ms since the epoch). const memory: Map = options.memory ?? new Map(); // Work running now, by the same key: two deliveries of one address at once share one store read and one check. const inflight = new Map>(); // Our refused key, no credits, the daily cap or a rate limit: no check before this time (ms since the epoch). let pausedUntil = 0; async function recall(hash: string): Promise { if (!store) { const entry = memory.get(hash); if (!entry) return null; if (Date.now() < entry.until) return entry.value; memory.delete(hash); return null; } try { return rememberedOf( await within( Promise.resolve().then(() => store.get(STORE_PREFIX + hash)), null, ), ); } catch { return null; } } async function keep(hash: string, value: Remembered): Promise { if (!store) { memory.delete(hash); memory.set(hash, { value, until: Date.now() + MEMORY_TTL_MS }); while (memory.size > MEMORY_MAX) memory.delete(memory.keys().next().value as string); return; } try { await within( Promise.resolve().then(() => store.set(STORE_PREFIX + hash, value)), undefined, ); } catch { // the answer stands; it is only not remembered } } /** One address's verdict, from what is remembered or from one check (remembered before this settles). */ async function resolve(email: string, hash: string): Promise { const known = await recall(hash); if (known) { const flagged = flaggedFor(s, known.status, known.reason, known.disposable); const decision: Decision = { flagged, status: known.status, reason: known.reason, error: null, requestId: known.requestId, }; return { outcome: flagged ? 'flagged' : 'clean', remembered: true, decision }; } if (Date.now() < pausedUntil) return { outcome: 'unchecked', remembered: false, decision: unchecked('paused') }; const { decision, remember, pauseS } = await check(s, email).catch( (): Checked => ({ decision: unchecked('internal_error'), remember: null, pauseS: null }), ); if (pauseS !== null) pausedUntil = Math.max(pausedUntil, Date.now() + pauseS * 1000); if (remember) await keep(hash, remember).catch(() => {}); // No answer: nothing is said about the address. if (decision.status === null) return { outcome: 'unchecked', remembered: false, decision }; // Our own timeout or failure (a free `unknown`): no verdict. if ((NEVER_FLAG_REASONS as readonly string[]).includes(decision.reason ?? '')) { return { outcome: 'unchecked', remembered: false, decision: { ...decision, flagged: false, error: decision.reason }, }; } return { outcome: decision.flagged ? 'flagged' : 'clean', remembered: false, decision }; } /** * The subscriber's verdict. The work for an address (store read, check, store write) is in `inflight` from before * the store is asked until the answer is remembered, so a delivery of the same address meanwhile joins it and never * starts a second check. Joined or started synchronously, before the first await: the handler calls it before it * answers, so the next delivery of the address always finds it. */ async function decide(email: string, hash: string): Promise { let running = inflight.get(hash); if (!running) { const started: Promise = resolve(email, hash) .catch((): Verdict => ({ outcome: 'unchecked', remembered: false, decision: unchecked('internal_error') })) .finally(() => { if (inflight.get(hash) === started) inflight.delete(hash); }); running = started; inflight.set(hash, started); } const verdict = await running; // Each delivery gets its own copy of a shared verdict. return { ...verdict, decision: { ...verdict.decision } }; } /** The verdict (already running when this is called), then `onResult`. */ async function report( running: Promise, base: { siteId: string | null; formId: string | null }, delivery: Record, ): Promise { const verdict = await running.catch( (): Verdict => ({ outcome: 'unchecked', remembered: false, decision: unchecked('internal_error') }), ); const result: SubscriberResult = { ...base, ...verdict, delivery }; try { // A copy of the decision: changing it never changes what is remembered. await options.onResult?.({ ...result, decision: { ...result.decision } }); } catch { // the customer's callback changes nothing } return result; } return async ({ body, url }) => { const allowed = await sameToken(tokenOf(url), bridgeToken).catch(() => false); if (!allowed) return { status: 401, body: { error: 'Missing or wrong token.' }, done: nothing }; // The raw body only: an object a framework already parsed (express.json) is refused, not guessed at. if (typeof body !== 'string' && !(body instanceof Uint8Array)) { return { status: 400, body: { error: 'Pass the raw body (a string or bytes).' }, done: nothing }; } const text = typeof body === 'string' ? body : new TextDecoder().decode(body); // An empty POST (a connection check) has nothing to check. if (!text.trim()) return { status: 200, body: { accepted: true }, done: nothing }; let parsed: unknown = null; try { parsed = JSON.parse(text); } catch { parsed = null; } if (!isObject(parsed)) return { status: 400, body: { error: 'The body is not a JSON object.' }, done: nothing }; const siteId = idOf(parsed.siteId); // A PING carries no site id; any event that names a site must name one of yours. if (siteIds && parsed.eventType !== 'PING' && (siteId === null || !siteIds.has(siteId))) { return { status: 403, body: { error: 'This site is not configured here.' }, done: nothing }; } // Only a live subscription is checked: a PING, the Send Test button's TEST event (a placeholder address) and any // other event start nothing and cost nothing. if (parsed.eventType !== SUBSCRIPTION_EVENT || parsed.executionContext !== LIVE) { return { status: 200, body: { accepted: true }, done: nothing }; } const email = parsed.email; let running: Promise; if (typeof email !== 'string' || !email.trim()) { running = Promise.resolve({ outcome: 'unchecked', remembered: false, decision: unchecked('no_address') }); } else if (!looksLikeAddress(email)) { running = Promise.resolve({ outcome: 'unchecked', remembered: false, decision: unchecked('not_an_address') }); } else { // The address's key is taken before the answer, and the work joined or started with it, so a repeated delivery // that BDOW! sends after this answer finds it running. const hash = await sha256(email.trim().toLowerCase()) .then(toHex) .catch(() => null); running = hash === null ? Promise.resolve({ outcome: 'unchecked', remembered: false, decision: unchecked('internal_error') }) : decide(email, hash); } const done = report(running, { siteId, formId: idOf(parsed.formId) }, parsed).catch(() => null); return { status: 200, body: { accepted: true }, done }; }; } /** Reads a body up to `max` bytes; null (and the rest left unread) as soon as it is longer, chunked or not. */ async function readCapped(request: Request, max: number): Promise { if (!request.body) return new Uint8Array(0); const reader = request.body.getReader(); const chunks: Uint8Array[] = []; let size = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; size += value.byteLength; if (size > max) { await reader.cancel().catch(() => {}); return null; } chunks.push(value); } const out = new Uint8Array(size); let offset = 0; for (const chunk of chunks) { out.set(chunk, offset); offset += chunk.byteLength; } return out; } /** What Cloudflare Workers pass as the second argument of `fetch(request, env, ctx)`: keeps the check running. */ export interface WaitUntilContext { waitUntil(work: Promise): void; } /** * The same receiver for a web `Request` (Cloudflare Workers, Next.js route handlers, Remix, Hono, Bun, Deno). A `GET` * or `HEAD` with the right token answers `200` (a connection check); other methods but `POST` answer `405`. The check * and `onResult` run after the answer: through `ctx.waitUntil` when given, else `options.waitUntil`, else on in the * process. */ export function createSumoWebhook( options: ReceiverOptions, ): (request: Request, ctx?: WaitUntilContext) => Promise { const handle = createSumoWebhookHandler(options); // Valid here: the handler above refuses a missing or short token. const bridgeToken = bridgeTokenOf(options.bridgeToken); return async (request, ctx) => { const method = request.method; if (method !== 'POST' && method !== 'GET' && method !== 'HEAD') { return Response.json({ error: 'Use POST.' }, { status: 405 }); } // The token is in the URL: checked before any of the body is read (the handler checks it again). const allowed = await sameToken(tokenOf(request.url), bridgeToken).catch(() => false); if (!allowed) return Response.json({ error: 'Missing or wrong token.' }, { status: 401 }); if (method !== 'POST') return Response.json({ ready: true } satisfies AnswerBody, { status: 200 }); const declared = Number(request.headers.get('content-length') ?? '0'); if (declared > MAX_BODY_BYTES) return Response.json({ error: 'Body too large.' }, { status: 413 }); const bytes = await readCapped(request, MAX_BODY_BYTES); if (bytes === null) return Response.json({ error: 'Body too large.' }, { status: 413 }); const result = await handle({ body: bytes, url: request.url }); try { if (ctx && typeof ctx.waitUntil === 'function') ctx.waitUntil(result.done); else options.waitUntil?.(result.done); } catch { // the work runs on regardless } return Response.json(result.body, { status: result.status }); }; }