// 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 ConvertFlow, on your server: check the email address of each new form submission. 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). Its browser twin, `email-validation-convertflow-browser.js`, * checks the address in the visitor's browser before the form is sent. * * ConvertFlow's custom webhooks (Settings → Webhooks) send your URL each submission of a topic you pick ("Fields * submitted by visitors", "Contact created or updated", "Automation triggered") as a JSON object: the campaign * (`cta_id`, `name`, `cta_type`, `cta_variant`, `cta_step`), `event`, `visitor_token`, `fields` (the submission: * `email`, `name`, `phone`, …, custom fields under `extra`) and `contact` (empty for an anonymous visitor). ConvertFlow's * help centre documents no signature, 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. * * A webhook is sent once the submission is saved, so nothing here can stop a sign-up (the browser twin can): the * receiver answers `200` at once and then checks `fields.email`, the address the visitor typed, with one * `POST /v1/validate`. Your `onResult` callback gets each submission with that address and its verdict (`flagged` when * the status is one you flag, default only a definite `invalid`), so your own code can unsubscribe, tag or skip it in * your mail tool. A submission without `fields.email` (a quiz or survey step) starts 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, a key limited to browser origins or the key's daily cap pause the checks for five minutes; a * rate limit for its `Retry-After`. A browser key (the browser twin's) is refused when the receiver is created. * 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-convertflow/${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); 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 submission 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 submission with its contact stays far below it. */ export const MAX_BODY_BYTES = 64 * 1024; /** Answers remembered per instance. */ export const MEMORY_MAX = 1000; /** * How long an answer stays in the instance's memory: 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, over its daily cap * or limited to browser origins (`forbidden_origin`: a server sends no Origin), 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', 'forbidden_origin', 'insufficient_credits', 'key_daily_cap', ] as const); /** * A browser key (`ev_live_`, the 22-character account part, then `browser`): limited to allowed origins, so from a * server, which sends no Origin, every check would be refused. Only our server mints one. */ const BROWSER_KEY = /^ev_live_[0-9A-Za-z]{22}browser[0-9A-Za-z]{50}$/; /** 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", without allowed origins: a browser key is * refused here). 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 submission 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(', ')}.`); } const apiKey = keyOf(options.apiKey); if (BROWSER_KEY.test(apiKey)) { throw new TypeError('This is a browser key; use a key without allowed origins on the server.'); } return { 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 * (`:` anywhere; `/`, `?` or `#` in the domain; a `/` that starts or ends the local part, or two together): a link with * an `@` in it, or a `mailto:`, is never sent. A `/` inside the local part (`first/last@example.com`) is allowed, as * RFC 5322 allows it. */ 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@:/?#]+\.[^\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-convertflow:`, never the address. Errors are ignored (the receiver then checks, or * keeps the answer in its own memory only). */ 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. Put it in the webhook URL you * give ConvertFlow, as `?token=`. */ bridgeToken: string | undefined; /** Keeps answers across restarts and instances (the instance's own memory is kept too). */ store?: Store; /** * Called once per submission with a `fields.email` (usable or not), after the answer, with the address judged, its * verdict and the submission as received (it holds the address, the name and the contact: keep it out of your * logs). Awaited inside `done`; errors are ignored. */ onResult?: (result: SubmissionResult) => 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 SubmissionResult { /** `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; /** * The address the verdict is for: `fields.email` trimmed, or null when it is empty or not a string. Act on this address, * never on `contact.email` (a contact's stored address can differ from the one just typed). */ email: string | null; decision: Decision; /** The submission as ConvertFlow sent it (`cta_id`, `event`, `fields`, `contact`, …). */ submission: Record; } /** The answer to ConvertFlow. Never holds an address. */ export type AnswerBody = { accepted: true } | { error: string }; export interface ReceiverResponse { status: number; body: AnswerBody; /** * Settles once the submission is checked, the answer remembered and `onResult` has run (null when the request * starts no check: refused, or without `fields.email`). Never rejects. */ done: Promise; } export interface Delivery { /** `POST` as ConvertFlow sends it; any other method is read as a connection check. */ method?: string; /** The raw body (a JSON object, whatever its declared type). */ body?: string | Uint8Array; /** The request URL (or its path and query, e.g. Express's `req.originalUrl`): its `?token=`. */ url: string | undefined; } const encoder = new TextEncoder(); const STORE_PREFIX = 'ev-convertflow:'; /** `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 delivery // 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; } /** * True when an object anywhere in `text` (valid JSON, already parsed) names one key twice, after its escapes are read * (`"email"` and `"email"` are one key). JSON.parse keeps the last, another reader may keep the first: such a body * is refused rather than judged by a guess at which address is meant. */ export function hasDuplicateKeys(text: string): boolean { const open: { keys: Set | null; expectKey: boolean }[] = []; for (let i = 0; i < text.length; i++) { const c = text[i]; if (c === '"') { let j = i + 1; while (j < text.length && text[j] !== '"') j += text[j] === '\\' ? 2 : 1; const top = open[open.length - 1]; if (top?.keys && top.expectKey) { const key = JSON.parse(text.slice(i, j + 1)) as string; if (top.keys.has(key)) return true; top.keys.add(key); top.expectKey = false; } i = j; } else if (c === '{') open.push({ keys: new Set(), expectKey: true }); else if (c === '[') open.push({ keys: null, expectKey: false }); else if (c === '}' || c === ']') open.pop(); else if (c === ',') { const top = open[open.length - 1]; if (top?.keys) top.expectKey = true; } } return false; } type Parsed = { ok: true; submission: Record } | { ok: false; error: string }; /** The submission: a JSON object (whatever the declared type), without a key named twice. */ function submissionOf(text: string): Parsed { let parsed: unknown; try { parsed = JSON.parse(text); } catch { return { ok: false, error: 'The body is not a JSON object.' }; } if (!isObject(parsed)) return { ok: false, error: 'The body is not a JSON object.' }; if (hasDuplicateKeys(text)) return { ok: false, error: 'The body names a key twice.' }; return { ok: true, submission: parsed }; } const nothing: Promise = Promise.resolve(null); /** * Handles one request from ConvertFlow. Answers `401` without the right token (the body is not parsed), `400` for a * body that is not a JSON object or names a key twice, and `200` for everything else, before any check. A submission * with `fields.email` starts one; it runs in `done`. */ export function createConvertFlowWebhookHandler( options: ReceiverOptions, ): (delivery: Delivery) => Promise { const s = settings(options); const bridgeToken = bridgeTokenOf(options.bridgeToken); 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). Kept with // a store too, so a store that refuses a write never makes this instance pay for the same address again. 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; function fromMemory(hash: string): Remembered | null { const entry = memory.get(hash); if (!entry) return null; if (Date.now() < entry.until) return entry.value; memory.delete(hash); return null; } async function recall(hash: string): Promise { const known = fromMemory(hash); if (known || !store) return known; 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 { 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); if (!store) return; try { await within( Promise.resolve().then(() => store.set(STORE_PREFIX + hash, value)), undefined, ); } catch { // the answer stands, and this instance remembers it; the store only does not } } /** 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 submission'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. */ 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); } // Each delivery gets its own copy of a shared verdict. return running.then((verdict) => ({ ...verdict, decision: { ...verdict.decision } })); } /** The verdict (already running when this is called), then `onResult`. */ async function report( running: Promise, email: string | null, submission: Record, ): Promise { const verdict = await running.catch( (): Verdict => ({ outcome: 'unchecked', remembered: false, decision: unchecked('internal_error') }), ); const result: SubmissionResult = { ...verdict, email, submission }; 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 ({ method, body, url }) => { const allowed = await sameToken(tokenOf(url), bridgeToken).catch(() => false); if (!allowed) return { status: 401, body: { error: 'Missing or wrong token.' }, done: nothing }; // Only a POST carries a submission; a GET or HEAD with the right token is a connection check. if ((method ?? 'POST').toUpperCase() !== 'POST') return { status: 200, body: { accepted: true }, done: nothing }; // The raw body only: an object a framework already parsed (express.json) is refused, not guessed at. if (body !== undefined && typeof body !== 'string' && !(body instanceof Uint8Array)) { return { status: 400, body: { error: 'Pass the raw body (a string or bytes).' }, done: nothing }; } const text = body === undefined ? '' : 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 }; const parsed = submissionOf(text); if (!parsed.ok) return { status: 400, body: { error: parsed.error }, done: nothing }; const { submission } = parsed; const fields = submission.fields; // No `fields.email` (a quiz or survey step, a connection check): nothing to check. if (!isObject(fields) || !Object.hasOwn(fields, 'email')) { return { status: 200, body: { accepted: true }, done: nothing }; } const value = fields.email; const email = typeof value === 'string' && value.trim() ? value.trim() : null; let running: Promise; if (!email) { 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 ConvertFlow sends after this answer finds it running. const hash = await sha256(email.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, email, submission).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). `POST` * reads the body (64 KiB at most, `413` past it); a `GET` or `HEAD` with the right token answers `200` (a connection * check); other methods 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 createConvertFlowWebhook( options: ReceiverOptions, ): (request: Request, ctx?: WaitUntilContext) => Promise { const handle = createConvertFlowWebhookHandler(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 === 'HEAD') return new Response(null, { status: 200 }); if (method === 'GET') return Response.json({ accepted: true }, { 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({ method, body: bytes, url: request.url }); keepRunning(result.done, ctx); return Response.json(result.body, { status: result.status }); }; function keepRunning(done: Promise, ctx: WaitUntilContext | undefined): void { try { if (ctx && typeof ctx.waitUntil === 'function') ctx.waitUntil(done); else options.waitUntil?.(done); } catch { // the work runs on regardless } } }