// 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 Formbricks: check the email answers of each survey response. One file, no dependencies; * run it on your own server (Node 22+, Bun, Deno, Cloudflare Workers: anything with `fetch` and Web Crypto). * * A Formbricks webhook (Configuration → Integrations → Webhooks; trigger "Response Finished" by default) POSTs each * response here, signed in the Standard Webhooks format with the webhook's `whsec_…` signing secret. The receiver * verifies the signature (and a 5-minute timestamp window) before it parses anything, answers Formbricks `200` at once, * then checks each address answer (an Email-type free text answer, a Contact Info answer's email, a hidden field) * with one `POST /v1/validate` per address and hands the verdict (`flagged`, `outcome`, `status`; never the address) * to your `onResult` callback (default: only a definite `invalid` is flagged). * * Formbricks cannot be told to refuse a response, and this receiver changes nothing in Formbricks: the verdict is * yours to act on (a message, a CRM field, a deletion of your own). * * Fails open: no key, a timeout, a network error, a rate limit or any error answer is reported `flagged: false`, * `outcome: "unchecked"`. 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. Our API key goes * only to our API; redirects are never followed; nothing here logs an address, a key or a secret. */ export const VERSION = '1.0.0'; export const USER_AGENT = `email-validation-formbricks/${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 passes, 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 answer is `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): a response with long free-text answers stays far below it. */ export const MAX_BODY_BYTES = 1024 * 1024; /** Answers remembered per instance (without a `store`). */ export const MEMORY_MAX = 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; 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 answer is `unchecked` (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 answer: `missing_key`, `not_an_address`, `timeout`, `connection_error`, or the API's error code. */ 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 colon and no slash (anything else is never * sent; the domain also has no `?` or `#`). So a link, with a scheme (`https://example.com/@name`) or without one * (`www.example.com/@name`, `example.com/@name`), or a `mailto:` is not one. */ export function looksLikeAddress(value: unknown): value is string { if (typeof value !== 'string') return false; const v = value.trim(); return v.length <= 254 && /^[^\s@:/]+@[^\s@:/?#]+\.[^\s@.:/?#]{2,}$/.test(v); } /** * 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)) ); } /** 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<{ decision: Decision; remember: Remembered | null }> { if (!s.apiKey) return { decision: unchecked('missing_key'), remember: null }; if (!looksLikeAddress(email)) return { decision: unchecked('not_an_address'), remember: null }; 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 { decision: unchecked('timeout'), remember: null }; if (err instanceof Error && err.message === 'redirect') { return { decision: unchecked('unexpected_response'), remember: null }; } return { decision: unchecked('connection_error'), remember: null }; } let body: unknown = null; try { body = await response.json(); } catch (err) { if (isTimeout(err)) return { decision: unchecked('timeout'), remember: null }; } 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) || `http_${response.status}`; return { decision: unchecked(code, requestIdOf(error.request_id, s.apiKey) ?? headerId), remember: null, }; } const status = record.status; const requestId = requestIdOf(record.request_id, s.apiKey) ?? headerId; if (typeof status !== 'string' || !(STATUSES as readonly string[]).includes(status)) { return { decision: unchecked('unexpected_response', requestId), remember: null }; } 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 }; } /** * 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((r) => r.decision) .catch(() => unchecked('internal_error')); } // --------------------------------------------------------------------------------------------------------------- // The webhook receiver. /** Formbricks' three webhook triggers. `responseUpdated` fires on every change, a reviewer's mark included. */ export const EVENTS = Object.freeze(['responseCreated', 'responseUpdated', 'responseFinished'] as const); export type FormbricksEvent = (typeof EVENTS)[number]; /** The body of Formbricks' "Test Endpoint" button (signed like a delivery): answered `200`, nothing checked. */ export const TEST_EVENT = 'testEndpoint'; /** The most addresses checked in one response (each distinct address is one check). */ export const MAX_ADDRESSES = 5; /** * Where answers are remembered across restarts (Workers KV, Redis, a database table). Keys are * `ev-formbricks:`, 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 { /** * The webhook's signing secret, `whsec_…` (Formbricks shows it once the webhook is created). From env. Not set yet: * every delivery is answered `401` and nothing is checked (Formbricks' Test Endpoint accepts that, so the webhook can * be created first). */ webhookSecret: string | undefined; /** The triggers that start a check (default `responseFinished`); others are answered `ignored`. */ events?: readonly FormbricksEvent[]; /** * The answers to read: question ids, question codes or hidden field names. Default: every answer of the response, * of which only those that are exactly one address (or a list holding one, like Contact Info) are checked. */ fields?: readonly string[]; /** How far a delivery's signed `webhook-timestamp` may be from now, in seconds (default 300, at most 3600). */ toleranceS?: number; /** Keeps answers across restarts and instances. Default: this instance's memory (up to 1,000 addresses). */ store?: Store; /** Called once per accepted delivery, after its checks, with the verdicts (never an address). Errors are ignored. */ onResult?: (result: ResponseResult) => void | Promise; /** Keeps the checks running after the answer (Next.js `after`, Vercel `waitUntil`); Workers: pass `ctx` instead. */ waitUntil?: (work: Promise) => void; /** For tests: the clock, in milliseconds. */ now?: () => number; } export type Outcome = 'allowed' | 'flagged' | 'unchecked'; /** One address's verdict, shared by every delivery of it that arrives while it is worked out. */ type Verdict = Omit; export interface AddressResult { /** The question id, question code or hidden field name the address was answered in. */ field: string; /** `allowed`; `flagged` (a status you flag); or `unchecked` (no answer: `decision.error` says why). */ outcome: Outcome; /** True when the answer was remembered from an earlier check (no request was sent). */ remembered: boolean; decision: Decision; } export interface ResponseResult { event: FormbricksEvent; /** Formbricks' ids (letters, digits, `_`, `-`), or null when the delivery has none. */ responseId: string | null; surveyId: string | null; /** The delivery's `webhook-id` (the same on Formbricks' retries of one delivery). */ messageId: string; /** True when any address of the response is flagged. */ flagged: boolean; /** One entry per distinct address found (none: the response has no address answer). */ checks: AddressResult[]; } /** The answer to Formbricks. Never holds an address. */ export type AnswerBody = | { accepted: true; addresses: number } | { ignored: 'test' | 'other_event'; event: string | null } | { error: string }; export interface ReceiverResponse { status: number; body: AnswerBody; /** Settles once the checks and `onResult` are done (null when nothing was checked). Never rejects. */ done: Promise; } /** A web `Headers`, or Node's `req.headers` (lower-case names; a repeated header is an array and is refused). */ export type HeaderSource = Headers | Record; export interface Delivery { /** The raw body, exactly as received: the signature covers these bytes. */ body: string | Uint8Array; headers: HeaderSource; } const encoder = new TextEncoder(); const STORE_PREFIX = 'ev-formbricks:'; const ID = /^[A-Za-z0-9_-]{1,64}$/; const DEFAULT_EVENTS: readonly FormbricksEvent[] = Object.freeze(['responseFinished']); const DEFAULT_TOLERANCE_S = 300; /** `work`, or `fallback` once STORE_TIMEOUT_MS has passed (a hung store never holds the checks). */ 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; } function fromBase64(text: string): Uint8Array | null { if (!/^[A-Za-z0-9+/]+={0,2}$/.test(text) || text.length % 4 !== 0) return null; try { return Uint8Array.from(atob(text), (c) => c.charCodeAt(0)); } catch { return null; } } function toBase64(bytes: Uint8Array): string { let binary = ''; for (const b of bytes) binary += String.fromCharCode(b); return btoa(binary); } /** The key bytes of a signing secret, `whsec_` and padded base64 (the prefix optional, as Formbricks reads it), or null. */ export function secretBytes(secret: unknown): Uint8Array | null { if (typeof secret !== 'string') return null; const bytes = fromBase64(secret.startsWith('whsec_') ? secret.slice('whsec_'.length) : secret); return bytes && bytes.length >= 16 ? bytes : null; } /** A header by name, any case; null when missing, empty or repeated. */ function header(headers: HeaderSource, name: string): string | null { if (typeof (headers as Headers).get === 'function') { const value = (headers as Headers).get(name); return value ? value : null; } let found: string | null = null; for (const [key, value] of Object.entries(headers as Record)) { if (key.toLowerCase() !== name) continue; const one = Array.isArray(value) ? (value.length === 1 ? value[0] : undefined) : value; if (found !== null || typeof one !== 'string' || !one) return null; found = one; } return found; } function hmacKey(bytes: Uint8Array): Promise { return crypto.subtle.importKey('raw', bytes as BufferSource, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); } function signedContent(id: string, timestamp: string, body: Uint8Array): Uint8Array { const prefix = encoder.encode(`${id}.${timestamp}.`); const out = new Uint8Array(prefix.length + body.length); out.set(prefix, 0); out.set(body, prefix.length); return out; } /** * Whether a delivery is Formbricks' (Standard Webhooks): `webhook-id`, a `webhook-timestamp` within the window, and a * `webhook-signature` entry `v1,..">` that matches, compared in * constant time. */ export async function verifyDelivery( body: Uint8Array, headers: HeaderSource, key: CryptoKey, nowS: number, toleranceS: number, ): Promise { const id = header(headers, 'webhook-id'); const timestamp = header(headers, 'webhook-timestamp'); const signatures = header(headers, 'webhook-signature'); if (!id || id.length > 256 || !timestamp || !signatures) return false; if (!/^[0-9]{1,12}$/.test(timestamp) || Math.abs(nowS - Number(timestamp)) > toleranceS) return false; const expected = new Uint8Array( await crypto.subtle.sign('HMAC', key, signedContent(id, timestamp, body) as BufferSource), ); let match = false; // Space-separated entries; a proxy that joined repeated headers adds a comma after each. for (const raw of signatures.split(/ +/)) { const entry = raw.replace(/,$/, ''); if (!entry.startsWith('v1,')) continue; const given = fromBase64(entry.slice(3)); if (given && sameBytes(given, expected)) match = true; } return match; } /** The `webhook-signature` value for a body, as Formbricks computes it (for tests of a receiver). */ export async function signDelivery(secret: string, id: string, timestamp: number, body: string): Promise { const bytes = secretBytes(secret); if (!bytes) throw new TypeError('Not a whsec_ secret.'); const mac = await crypto.subtle.sign( 'HMAC', await hmacKey(bytes), signedContent(id, String(timestamp), encoder.encode(body)) as BufferSource, ); return `v1,${toBase64(new Uint8Array(mac))}`; } /** The strings an answer holds: itself, a list's items (Contact Info, Address), an object's values (one level). */ function stringsOf(value: unknown): string[] { if (typeof value === 'string') return [value]; const items = Array.isArray(value) ? value : isObject(value) ? Object.values(value) : []; return items.filter((v): v is string => typeof v === 'string'); } /** The distinct addresses of a response (at most MAX_ADDRESSES), each with the answer it came from. */ export function addressesOf( response: Record, fields?: readonly string[], ): { field: string; email: string }[] { const answers = isObject(response.data) ? response.data : {}; const byCode = isObject(response.dataByQuestionCode) ? response.dataByQuestionCode : {}; const pairs: [string, unknown][] = fields ? fields.map((f) => [f, Object.hasOwn(answers, f) ? answers[f] : Object.hasOwn(byCode, f) ? byCode[f] : null]) : Object.entries(answers); const seen = new Set(); const out: { field: string; email: string }[] = []; for (const [field, value] of pairs) { for (const candidate of stringsOf(value)) { if (!looksLikeAddress(candidate)) continue; const email = candidate.trim(); const folded = email.toLowerCase(); if (seen.has(folded)) continue; seen.add(folded); // A key is the respondent's to choose: one that looks like it holds an address is not passed on. out.push({ field: field.includes('@') ? 'answer' : field, email }); if (out.length >= MAX_ADDRESSES) return out; } } return out; } 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 bytesOf(body: string | Uint8Array): Uint8Array { return typeof body === 'string' ? encoder.encode(body) : body; } const nothing: Promise = Promise.resolve(null); /** * Handles one delivery from Formbricks. Answers `401` for a missing, wrong or stale signature, or while no secret is set * (nothing is parsed), * `400` for a body that is not a JSON object, and `200` for everything else: at once, before the checks, which run on * in `done` (fail open: `flagged: false` when there is no answer). */ export function createFormbricksWebhookHandler( options: ReceiverOptions, ): (delivery: Delivery) => Promise { const s = settings(options); const unset = options.webhookSecret === undefined || options.webhookSecret === null || options.webhookSecret === ''; const keyBytes = unset ? null : secretBytes(options.webhookSecret); if (!unset && !keyBytes) { throw new TypeError("webhookSecret must be the webhook's signing secret: whsec_ followed by base64."); } // No secret yet: nothing verifies, so every delivery is answered 401. const key = keyBytes ? hmacKey(keyBytes) : null; const toleranceS = options.toleranceS ?? DEFAULT_TOLERANCE_S; if (typeof toleranceS !== 'number' || !Number.isFinite(toleranceS) || toleranceS <= 0 || toleranceS > 3600) { throw new TypeError('toleranceS must be a number of seconds above 0, at most 3600.'); } const events = options.events ?? DEFAULT_EVENTS; if (!Array.isArray(events) || events.length === 0 || events.some((e) => !(EVENTS as readonly string[]).includes(e))) { throw new TypeError(`events must list some of ${EVENTS.join(', ')}.`); } const fields = options.fields; if ( fields !== undefined && (!Array.isArray(fields) || fields.length === 0 || fields.some((f) => typeof f !== 'string' || !f.trim())) ) { throw new TypeError('fields must list question ids, question codes or hidden field names.'); } const store = options.store; if (store !== undefined && (typeof store?.get !== 'function' || typeof store?.set !== 'function')) { throw new TypeError('store must have get and set.'); } const now = options.now ?? Date.now; // Keyed by the address's SHA-256 (never the address). const 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>(); async function recall(hash: string): Promise { if (!store) return memory.get(hash) ?? 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); 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' : 'allowed', remembered: true, decision }; } const { decision, remember } = await check(s, email).catch(() => ({ decision: unchecked('internal_error'), remember: null, })); if (remember) await keep(hash, remember).catch(() => {}); // No answer, or our own timeout or failure (a free `unknown`): nothing is said about the address. if (decision.status === null) return { outcome: 'unchecked', remembered: false, decision }; 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' : 'allowed', remembered: false, decision }; } /** * One address's result. 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 (not even when that whole check ends during the later delivery's own slow store read). */ async function decide(field: string, email: string): Promise { const hash = toHex(await sha256(email.toLowerCase())); 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 { field, ...verdict, decision: { ...verdict.decision } }; } async function run( event: FormbricksEvent, messageId: string, response: Record, found: { field: string; email: string }[], ): Promise { const checks = await Promise.all( found.map(({ field, email }) => decide(field, email).catch( (): AddressResult => ({ field, outcome: 'unchecked', remembered: false, decision: unchecked('internal_error'), }), ), ), ); const id = (v: unknown) => (typeof v === 'string' && ID.test(v) ? v : null); const result: ResponseResult = { event, responseId: id(response.id), surveyId: id(response.surveyId), messageId, flagged: checks.some((c) => c.outcome === 'flagged'), checks, }; try { await options.onResult?.(result); } catch { // the customer's callback changes nothing } return result; } return async ({ body, headers }) => { const bytes = bytesOf(body); let verified = false; try { verified = key !== null && (await verifyDelivery(bytes, headers, await key, Math.floor(now() / 1000), toleranceS)); } catch { verified = false; } if (!verified) return { status: 401, body: { error: 'Missing, wrong or stale signature.' }, done: nothing }; let parsed: unknown = null; try { parsed = JSON.parse(new TextDecoder().decode(bytes)); } catch { parsed = null; } if (!isObject(parsed)) return { status: 400, body: { error: 'The body is not a JSON object.' }, done: nothing }; const event = typeof parsed.event === 'string' && /^[A-Za-z]{1,64}$/.test(parsed.event) ? parsed.event : null; if (event === TEST_EVENT) return { status: 200, body: { ignored: 'test', event }, done: nothing }; if (event === null || !(events as readonly string[]).includes(event) || !isObject(parsed.data)) { return { status: 200, body: { ignored: 'other_event', event }, done: nothing }; } const response = parsed.data; const found = addressesOf(response, fields); const messageId = header(headers, 'webhook-id') as string; const done = run(event as FormbricksEvent, messageId, response, found).catch(() => null); return { status: 200, body: { accepted: true, addresses: found.length }, 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 checks 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). The * checks run after the answer: through `ctx.waitUntil` when given, else `options.waitUntil`, else on in the process. */ export function createFormbricksWebhook( options: ReceiverOptions, ): (request: Request, ctx?: WaitUntilContext) => Promise { const handle = createFormbricksWebhookHandler(options); return async (request, ctx) => { if (request.method !== 'POST') return Response.json({ error: 'Use POST.' }, { status: 405 }); 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, headers: request.headers }); try { if (ctx && typeof ctx.waitUntil === 'function') ctx.waitUntil(result.done); else options.waitUntil?.(result.done); } catch { // the checks run on regardless } return Response.json(result.body, { status: result.status }); }; }