// 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 Stytch: stop sign-ups with bad email addresses. One file, no dependencies; copy it into * the server that calls Stytch's backend API (Node 20+, Next.js, Remix, Hono, Express, Bun, Deno, Cloudflare * Workers: anything with `fetch` and Web Crypto). * * Stytch has no hook that runs before it creates a user (Consumer) or a member (B2B), and its webhooks (sent through * Svix) report a change after it happened. So this file gives two pieces (README.md says which covers what): * * - `createStytchSignupGuard()`: a check your server runs before it calls Stytch's create endpoints (magic link * login-or-create, email OTP login-or-create, password create, user create, invites; B2B discovery and * login-or-signup sends, member create). A stopped address never reaches Stytch, so no user or member is created. * - `createStytchWebhookNotice()`: a handler for Stytch's webhooks that checks the address of each created user or * member and tells your `onResult` callback. It changes nothing in Stytch and cannot undo a sign-up: it is a * notice, for the sign-ups the guard cannot see (OAuth, SSO, SCIM, the frontend SDK, the Dashboard). * * Fails open: no key, a timeout, a network error, a rate limit or any error answer lets the sign-up through, and a * check is never retried. Only a definite answer whose status is in `stop` stops it. Our API key goes only to our * API; redirects are never followed; nothing here logs an address or a key. */ export const VERSION = '1.0.0'; export const USER_AGENT = `email-validation-stytch/${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 stop. A `valid` answer passes, unless it is marked disposable and `disposable` is stopped. */ export const STOPPABLE = Object.freeze(['invalid', 'disposable', 'catch_all', 'unknown'] as const); export type StoppableStatus = (typeof STOPPABLE)[number]; /** * `unknown` answers that mean our side ran out of time or failed: they never stop a sign-up, even with `unknown` * in `stop` (a slow or failing API lets the sign-up through). */ export const NEVER_STOP_REASONS = Object.freeze(['timeout', 'internal_error'] as const); export const DEFAULTS = Object.freeze({ stop: Object.freeze(['invalid', 'disposable'] as const), /** * How long a check may take before the sign-up goes through unchecked: a little over the API's own 5-second limit, * so a check that needs longer comes back as a free `unknown` first. Well inside the 30 seconds Svix waits for a * webhook answer. */ timeoutMs: 6000, /** What `SignupRefusedError` says to the person signing up. */ message: 'Please sign up with another email address.', }); /** The API's shortest check time, in seconds: a check that needs longer ends as a free `unknown`. */ export const SERVER_TIMEOUT_S = 5; /** How long Svix waits for a webhook answer before it counts the attempt as failed (Svix's docs). */ export const SVIX_RESPONSE_LIMIT_S = 30; /** How far a webhook's timestamp may be from now, in seconds (Standard Webhooks, as our SDKs use it). */ export const WEBHOOK_TOLERANCE_S = 300; export type FetchFn = (input: string, init?: RequestInit) => Promise; export interface CheckOptions { /** Your email-validation.org API key (permission "Validate addresses"). Read it from your secret store. */ apiKey: string | undefined; /** `us` (default) or `eu`. */ region?: 'us' | 'eu'; /** The statuses that stop a sign-up (default `invalid`, `disposable`). */ stop?: readonly StoppableStatus[]; /** Milliseconds before the sign-up goes through unchecked (default 6000). */ timeoutMs?: number; /** For tests and proxies; default: the global fetch. */ fetch?: FetchFn; } export interface Decision { /** False only when a definite answer's status is one you stop. */ allow: boolean; /** The answer's status, or null when there was no answer (then `error` says why). */ status: Status | null; reason: string | null; /** A suggested correction for a typo, e.g. `name@gmail.com`, or null. */ didYouMean: string | null; /** * Why there is no answer: `missing_key`, `not_an_address`, `timeout`, `connection_error`, `unexpected_response`, * `internal_error`, the API's error code, or (guard only) `existing_user` / `existing_user_check_failed`. */ error: string | null; requestId: string | null; } interface Settings { apiKey: string; origin: string; stop: readonly StoppableStatus[]; timeoutMs: number; fetch: FetchFn; } 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 stop = options.stop ?? DEFAULTS.stop; if (!Array.isArray(stop) || stop.some((s) => !(STOPPABLE as readonly string[]).includes(s))) { throw new TypeError(`stop must list only ${STOPPABLE.join(', ')}.`); } const timeoutMs = options.timeoutMs ?? DEFAULTS.timeoutMs; // Whole milliseconds up to a minute: AbortSignal.timeout throws on a fraction or a huge value. if (typeof timeoutMs !== 'number' || !Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 60_000) { throw new TypeError('timeoutMs must be a whole number of milliseconds from 1 to 60000.'); } const fetchFn = options.fetch ?? ((input: string, init?: RequestInit) => globalThis.fetch(input, init)); // Surrounding whitespace (a pasted line break) is trimmed; a key with whitespace inside is no key: the check is // skipped and the sign-up goes through. const trimmed = typeof options.apiKey === 'string' ? options.apiKey.trim() : ''; const key = /^\S+$/.test(trimmed) ? trimmed : ''; return { apiKey: key, origin: API_ORIGINS[region], stop: Object.freeze([...stop]), timeoutMs, fetch: fetchFn }; } function pass(error: string, requestId: string | null = null): Decision { return { allow: true, status: null, reason: null, didYouMean: null, error, requestId }; } /** Whether a value is worth a check: something@domain.tld with no spaces (anything else 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 && /^[^\s@]+@[^\s@]+\.[^\s@.]{2,}$/.test(v); } /** * One request to our API 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 (!(Object.values(API_ORIGINS) as string[]).includes(origin) || new URL(url).origin !== origin) { throw new Error('Refused a request to a host other than our API.'); } 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; } /** Frees a response's connection when its body is not read. */ async function discard(response: Response): Promise { try { await response.body?.cancel(); } catch { // already closed } } function timedOut(err: unknown): boolean { const name = err instanceof Error ? err.name : ''; return name === 'TimeoutError' || name === 'AbortError'; } /** 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 { if (!s.apiKey) return pass('missing_key'); if (!looksLikeAddress(email)) return pass('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 (timedOut(err)) return pass('timeout'); if (err instanceof Error && err.message === 'redirect') return pass('unexpected_response'); return pass('connection_error'); } let body: unknown = null; try { body = await response.json(); } catch (err) { if (timedOut(err)) return pass('timeout'); body = null; } const record = body !== null && typeof body === 'object' ? (body as Record) : {}; const headerId = requestIdOf(response.headers.get('x-request-id'), s.apiKey); if (!response.ok) { const error = record.error !== null && typeof record.error === 'object' ? (record.error as Record) : {}; const code = codeOf(error.code, s.apiKey) || `http_${response.status}`; return pass(code, requestIdOf(error.request_id, s.apiKey) ?? headerId); } const status = record.status; const requestId = requestIdOf(record.request_id, s.apiKey) ?? headerId; if (typeof status !== 'string' || !(STATUSES as readonly string[]).includes(status)) { return pass('unexpected_response', requestId); } const reason = reasonOf(record.reason, s.apiKey); const ourFailure = status === 'unknown' && (NEVER_STOP_REASONS as readonly string[]).includes(reason ?? ''); const stopped = !ourFailure && ((s.stop as readonly string[]).includes(status) || (s.stop.includes('disposable') && record.disposable === true)); return { allow: !stopped, status: status as Status, reason, didYouMean: typeof record.did_you_mean === 'string' && !sharesKey(record.did_you_mean, s.apiKey) && record.did_you_mean ? record.did_you_mean : null, error: null, requestId, }; } /** A checker for one configuration (options are checked once, here). Never rejects. */ export function createEmailCheck(options: CheckOptions): (email: string) => Promise { const s = settings(options); return (email) => check(s, email).catch(() => pass('internal_error')); } // --------------------------------------------------------------------------------------------------------------- // The guard: runs in your server before it calls Stytch. /** Thrown by `guard.protect()` when the address is stopped; Stytch was not called. Its message is safe to show. */ export class SignupRefusedError extends Error { readonly decision: Decision; constructor(message: string, decision: Decision) { super(message); this.name = 'SignupRefusedError'; this.decision = decision; } } export interface GuardOptions extends CheckOptions { /** * Stytch's login-or-create endpoints serve log-ins too. Answer true for an address that already has an account * (from your own user table), and it is let through unchecked: no credit spent, and an existing user is never * locked out. Any truthy answer (a user record, say) counts as existing. If it throws, the address is let through * unchecked as well. It is awaited outside `timeoutMs`: keep it quick. */ isExistingUser?: (email: string) => unknown; /** The message of `SignupRefusedError` (default "Please sign up with another email address."). */ message?: string; /** * Called once per guarded address, never with the address (nor `didYouMean`, a suggested address). Errors it * throws are ignored. It is awaited before the sign-up goes on, outside `timeoutMs`: keep it quick. */ onResult?: (result: GuardResult) => void | Promise; } /** A decision as `onResult` gets it: without `didYouMean`, which is an address (the suggested correction). */ export type ReportedDecision = Omit; function forReport(decision: Decision): ReportedDecision { const { didYouMean: _suggested, ...rest } = decision; return rest; } export interface GuardResult { /** `allowed`, `stopped`, `existing_user` (not checked) or `unchecked` (no answer: let through). */ outcome: 'allowed' | 'stopped' | 'existing_user' | 'unchecked'; decision: ReportedDecision; } export interface StytchSignupGuard { /** Checks an address; never rejects. `allow: false` means: do not call Stytch, ask for another address. */ check(email: string): Promise; /** * Checks the address, then runs `signUp` (your Stytch call) only when it is allowed. A stopped address throws * `SignupRefusedError` and `signUp` never runs; an error from `signUp` itself is passed on unchanged. */ protect(email: string, signUp: () => T | Promise): Promise; } export function createStytchSignupGuard(options: GuardOptions): StytchSignupGuard { const s = settings(options); const message = options.message ?? DEFAULTS.message; if (typeof message !== 'string' || message.trim() === '') throw new TypeError('message must be a non-empty string.'); if (options.isExistingUser !== undefined && typeof options.isExistingUser !== 'function') { throw new TypeError('isExistingUser must be a function.'); } async function report(result: GuardResult): Promise { try { await options.onResult?.(result); } catch { // the customer's callback never changes the decision } } async function decide(email: string): Promise { if (options.isExistingUser) { let existing: boolean; try { existing = Boolean(await options.isExistingUser(email)); } catch { const decision = pass('existing_user_check_failed'); await report({ outcome: 'unchecked', decision: forReport(decision) }); return decision; } if (existing) { const decision = pass('existing_user'); await report({ outcome: 'existing_user', decision: forReport(decision) }); return decision; } } const decision = await check(s, email).catch(() => pass('internal_error')); await report({ outcome: !decision.allow ? 'stopped' : decision.status === null ? 'unchecked' : 'allowed', decision: forReport(decision), }); return decision; } return { check: (email) => decide(email).catch(() => pass('internal_error')), async protect(email: string, signUp: () => T | Promise): Promise { if (typeof signUp !== 'function') throw new TypeError('protect() needs the Stytch call as a function.'); const decision = await decide(email).catch(() => pass('internal_error')); if (!decision.allow) throw new SignupRefusedError(message, decision); return signUp(); }, }; } // --------------------------------------------------------------------------------------------------------------- // Webhook verification (Stytch sends its webhooks through Svix = Standard Webhooks): `..`, // HMAC-SHA256 with the secret after `whsec_` (base64), compared in constant time; the same checks and messages as // our SDKs (sdks/SDK_SPEC.md §9). export class WebhookVerificationError extends Error { constructor(message: string) { super(message); this.name = 'WebhookVerificationError'; } } export type HeaderSource = Headers | Record; const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; function decodeBase64(text: string): Uint8Array | null { if (!BASE64.test(text)) return null; const binary = atob(text); const out = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i); return out; } function encodeBase64(bytes: Uint8Array): string { let binary = ''; for (const b of bytes) binary += String.fromCharCode(b); return btoa(binary); } /** A header, any case, `svix-` or `webhook-` prefixed; repeated values joined with one space. */ function header(headers: HeaderSource, name: 'id' | 'timestamp' | 'signature'): string | null { const names = [`svix-${name}`, `webhook-${name}`]; if (headers instanceof Headers) { for (const n of names) { const v = headers.get(n); if (v !== null) return v; } return null; } if (!headers || typeof headers !== 'object') return null; for (const n of names) { const values: string[] = []; for (const [key, value] of Object.entries(headers)) { if (key.toLowerCase() !== n || value === undefined || value === null) continue; if (typeof value === 'string') values.push(value); else if (Array.isArray(value) && value.every((v) => typeof v === 'string')) values.push(...value); else return null; } if (values.length > 0) return values.join(' '); } return null; } function secretBytes(secret: string | undefined): Uint8Array { if (typeof secret !== 'string' || secret === '') throw new WebhookVerificationError('Missing webhook secret.'); const key = decodeBase64(secret.startsWith('whsec_') ? secret.slice(6) : secret); if (key === null || key.length === 0) { throw new WebhookVerificationError('The webhook secret is not valid (expected whsec_ followed by base64).'); } return key; } async function hmac(key: Uint8Array, content: string): Promise { const cryptoKey = await crypto.subtle.importKey( 'raw', key as BufferSource, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'], ); return new Uint8Array(await crypto.subtle.sign('HMAC', cryptoKey, new TextEncoder().encode(content))); } 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 `svix-signature` value for a body (for tests of a receiver). */ export async function signWebhook(id: string, timestampS: number, body: string, secret: string): Promise { return `v1,${encodeBase64(await hmac(secretBytes(secret), `${id}.${timestampS}.${body}`))}`; } /** * Verifies a delivery and returns the parsed event. `body` is the raw request body, exactly as received. Throws * `WebhookVerificationError` on any failed check. */ export async function verifyWebhook( body: string, headers: HeaderSource, secret: string | undefined, options: { nowS?: number; toleranceS?: number } = {}, ): Promise> { const id = header(headers, 'id'); const timestamp = header(headers, 'timestamp'); const signatures = header(headers, 'signature'); if (!id || !timestamp || !signatures) throw new WebhookVerificationError('Missing webhook headers.'); if (!/^[0-9]{1,12}$/.test(timestamp)) throw new WebhookVerificationError('Invalid webhook timestamp.'); const tolerance = options.toleranceS ?? WEBHOOK_TOLERANCE_S; const now = options.nowS ?? Math.floor(Date.now() / 1000); if (Math.abs(now - Number(timestamp)) > tolerance) { throw new WebhookVerificationError('Webhook timestamp is outside the allowed tolerance.'); } const expected = await hmac(secretBytes(secret), `${id}.${timestamp}.${body}`); // runs of spaces; a stack that joins repeated header lines with ", " leaves one trailing comma on an entry for (const raw of signatures.split(/ +/)) { const entry = raw.endsWith(',') ? raw.slice(0, -1) : raw; const comma = entry.indexOf(','); if (comma < 0 || entry.slice(0, comma) !== 'v1') continue; const given = decodeBase64(entry.slice(comma + 1)); if (given !== null && sameBytes(given, expected)) return parseEvent(body); } throw new WebhookVerificationError('No webhook signature matched.'); } function parseEvent(body: string): Record { let event: unknown = null; try { event = JSON.parse(body); } catch { // not JSON: refused below } if (event === null || typeof event !== 'object' || Array.isArray(event)) { throw new WebhookVerificationError('The webhook body is not JSON.'); } return event as Record; } // --------------------------------------------------------------------------------------------------------------- // The webhook notice: after Stytch created a user or member. It changes nothing in Stytch. export interface NoticeOptions extends CheckOptions { /** The webhook endpoint's signing secret (`whsec_…`), from the Stytch Dashboard's Webhooks page. */ signingSecret: string | undefined; /** * Called once per checked user or member, never with the address (nor `didYouMean`). Errors it throws are * ignored. It is awaited before Svix gets its answer: keep it well inside Svix's 30 s. */ onResult: (result: NoticeResult) => void | Promise; /** For tests: the current time in seconds. */ nowS?: () => number; } export interface NoticeResult { /** `user` (Consumer) or `member` (B2B). */ objectType: 'user' | 'member'; /** The Stytch `user_id` or `member_id` (Stytch's top-level `id`). */ id: string; /** The member's `organization_id` (B2B), else null. */ organizationId: string | null; /** Stytch's `source`: `DIRECT` (your API calls, the SDKs, OAuth, SSO), `DASHBOARD` or `SCIM`. */ source: string | null; /** Stytch's `event_id`. */ eventId: string | null; /** * `on_stop_list`: the address's status is one you stop. The user or member already exists in Stytch, and this * handler did nothing to it. `allowed`, or `unchecked` (no answer). */ outcome: 'on_stop_list' | 'allowed' | 'unchecked'; decision: ReportedDecision; } export interface NoticeResponse { status: number; body: Record; } const STYTCH_ID = /^[A-Za-z0-9_-]{1,128}$/; /** Deliveries already checked (`svix-id`), so a resent delivery is not checked (or paid) twice on one instance. */ const SEEN_MAX = 1000; function asRecord(v: unknown): Record { return v !== null && typeof v === 'object' && !Array.isArray(v) ? (v as Record) : {}; } /** The address of a created user (`user.emails[].email`, the first one) or member (`member.email_address`). */ function createdAddress(objectType: 'user' | 'member', object: Record): string | null { if (objectType === 'member') return typeof object.email_address === 'string' ? object.email_address : null; const emails = Array.isArray(object.emails) ? object.emails : []; const first = emails.map(asRecord).find((e) => typeof e.email === 'string'); return first ? (first.email as string) : null; } /** * Handles one delivery: `body` is the raw request body, `headers` its headers. Answers 400 for a delivery that fails * verification (Svix retries it), and 200 for everything else, so a delivery is never resent for our sake. */ export function createStytchWebhookNotice( options: NoticeOptions, ): (delivery: { body: string; headers: HeaderSource }) => Promise { const s = settings(options); if (typeof options.onResult !== 'function') throw new TypeError('onResult is required: the notice only reports.'); const signingSecret = typeof options.signingSecret === 'string' ? options.signingSecret.trim() : undefined; const seen = new Set(); async function report(result: NoticeResult): Promise { try { await options.onResult(result); } catch { // the customer's callback never changes the answer to Stytch } } return async ({ body, headers }) => { let event: Record; try { event = await verifyWebhook(body, headers, signingSecret, { nowS: options.nowS?.() }); } catch (err) { const message = err instanceof WebhookVerificationError ? err.message : 'Webhook verification failed.'; return { status: 400, body: { error: message } }; } try { const objectType = event.object_type; if (event.action !== 'CREATE' || (objectType !== 'user' && objectType !== 'member')) { return { status: 200, body: { ignored: `${String(event.action ?? '')} ${String(objectType ?? '')}`.trim() } }; } const object = asRecord(event[objectType]); const rawId = typeof event.id === 'string' ? event.id : object[`${objectType}_id`]; const id = typeof rawId === 'string' && STYTCH_ID.test(rawId) ? rawId : null; if (!id) return { status: 200, body: { ignored: 'no_id' } }; const deliveryId = header(headers, 'id') ?? ''; if (deliveryId && seen.has(deliveryId)) return { status: 200, body: { ignored: 'already_checked' } }; const email = createdAddress(objectType, object); if (!email) return { status: 200, body: { outcome: 'unchecked', error: 'no_email' } }; const decision = await check(s, email).catch(() => pass('internal_error')); if (decision.status !== null && deliveryId) { seen.add(deliveryId); while (seen.size > SEEN_MAX) seen.delete(seen.values().next().value as string); } const outcome = !decision.allow ? 'on_stop_list' : decision.status === null ? 'unchecked' : 'allowed'; const orgId = objectType === 'member' ? object.organization_id : null; await report({ objectType, id, organizationId: typeof orgId === 'string' && STYTCH_ID.test(orgId) ? orgId : null, source: typeof event.source === 'string' ? event.source : null, eventId: typeof event.event_id === 'string' && STYTCH_ID.test(event.event_id) ? event.event_id : null, outcome, decision: forReport(decision), }); return { status: 200, body: { outcome, ...(decision.error ? { error: decision.error } : {}) } }; } catch { // A verified delivery always gets a 2xx, so Svix does not resend it (and pay for a check again). return { status: 200, body: { outcome: 'unchecked', error: 'internal_error' } }; } }; } /** The largest body read (bytes): a delivery is a few kilobytes. */ const MAX_BODY_BYTES = 256 * 1024; /** Reads a body as a stream, stopping past `max` bytes (a chunked body has no Content-Length to check first). */ async function readCapped(request: Request, max: number): Promise | null> { 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; } /** * The same handler for a web `Request` (Next.js route handlers, Remix, Hono, Workers, Bun, Deno): * `export const POST = createStytchWebhookNoticeHook({ ... })`. */ export function createStytchWebhookNoticeHook(options: NoticeOptions): (request: Request) => Promise { const handle = createStytchWebhookNotice(options); return async (request) => { 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 }); let body: string; try { const bytes = await readCapped(request, MAX_BODY_BYTES); if (bytes === null) return Response.json({ error: 'Body too large.' }, { status: 413 }); body = new TextDecoder().decode(bytes); } catch { // the sender went away mid-body: nothing verified, nothing checked return Response.json({ error: 'Could not read the request body.' }, { status: 400 }); } const result = await handle({ body, headers: request.headers }); return Response.json(result.body, { status: result.status }); }; }