/** * email-validation.org for Clerk: stop sign-ups with bad email addresses. One file, no dependencies; copy it into * your app (Next.js, Remix, Hono, Express, Bun, Deno, Cloudflare Workers: anything with `fetch` and Web Crypto). * * Clerk has no hook that runs before it creates a user, and its webhooks are sent after the fact, so this file gives * two pieces (README.md says which to use when): * * - `createClerkSignupHook()`: a handler for Clerk's `user.created` webhook. It checks the signature (Svix, i.e. * Standard Webhooks), checks the new user's primary address and, when its status is one you stop, acts on the * account: `flag` (default: writes `public_metadata.email_validation`, which your app reads to keep the account * out), or `ban` or `delete` (switched on by you). It works with Clerk's prebuilt ``. * - `checkSignupEmail()`: a server-side check for a custom sign-up flow, called before `signUp.create()`, so a bad * address is refused before the account exists. * * Fails open: no key, a timeout, a network error, a rate limit or any error answer lets the sign-up through. Only a * definite answer whose status is in `stop` stops it. Our API key goes only to our API, Clerk's secret key only to * Clerk's Backend API; redirects are never followed; nothing here logs an address. */ export const VERSION = '1.0.0'; export const USER_AGENT = `email-validation-clerk/${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', }); /** Clerk's Backend API, the only host Clerk's secret key is sent to. */ export const CLERK_API_ORIGIN = 'https://api.clerk.com'; /** 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. */ timeoutMs: 6000, /** What the webhook handler does to an account whose address is stopped. */ onStop: 'flag' as const, }); /** 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 far a webhook's timestamp may be from now, in seconds (Standard Webhooks). */ export const WEBHOOK_TOLERANCE_S = 300; /** The key `flag` (and `ban`) writes in the user's public metadata. */ export const METADATA_KEY = 'email_validation'; export type FetchFn = (input: string, init?: RequestInit) => Promise; export interface CheckOptions { /** Your email-validation.org API key (permission "Validate addresses"). Server-side only. */ 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`, or the API's error code. */ 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 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; } /** 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 } } /** 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) { const name = err instanceof Error ? err.name : ''; if (name === 'TimeoutError' || name === 'AbortError') 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) { const name = err instanceof Error ? err.name : ''; if (name === 'TimeoutError' || name === 'AbortError') 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')); } /** * Checks an address in your own server code before your custom sign-up flow calls `signUp.create()`. Each check * uses one credit (`unknown`, malformed and sandbox addresses are free): call it only from your sign-up path. */ export function checkSignupEmail(email: string, options: CheckOptions): Promise { return createEmailCheck(options)(email); } // --------------------------------------------------------------------------------------------------------------- // Webhook verification (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 `user.created` webhook handler. export type StopAction = 'flag' | 'ban' | 'delete' | 'none'; export interface HookOptions extends CheckOptions { /** The endpoint's signing secret from Clerk (Dashboard → Webhooks), `whsec_…`. */ signingSecret: string | undefined; /** Clerk's secret key, for `flag`, `ban` and `delete` (not needed for `none`). */ clerkSecretKey?: string | undefined; /** * What happens to an account whose address is stopped: `flag` (default) writes * `public_metadata.email_validation`; `ban` writes it and bans the user (sessions revoked, no sign-in); `delete` * deletes the user; `none` only calls `onResult`. */ onStop?: StopAction; /** Called once per checked account (never with the address). Errors it throws are ignored. */ onResult?: (result: HookResult) => void | Promise; /** For tests: the current time in seconds. */ nowS?: () => number; } export interface HookResult { userId: string; /** `allowed`, `stopped`, or `unchecked` (no answer, or nothing could be done: the account stays). */ outcome: 'allowed' | 'stopped' | 'unchecked'; action: StopAction | null; /** Our answer. Its `didYouMean` is always null here: it is an address (the user's local part, another domain). */ decision: Decision; } export interface HookResponse { status: number; body: Record; } /** The metadata `flag` and `ban` write (`public_metadata.email_validation`), readable by your app, set only by Clerk's Backend API. */ export interface EmailValidationMetadata { status: Status; reason: string | null; stopped: true; checked_at: string; } function primaryEmail(data: Record): string | null { const list = Array.isArray(data.email_addresses) ? data.email_addresses : []; const entries = list.filter( (e): e is Record => e !== null && typeof e === 'object' && typeof e.email_address === 'string', ); const primary = entries.find((e) => e.id === data.primary_email_address_id) ?? entries[0]; return primary ? (primary.email_address as string) : null; } const USER_ID = /^[A-Za-z0-9_-]{1,128}$/; /** Clerk's Backend API refused or failed an action (status 0: no answer). */ class ClerkCallError extends Error { readonly status: number; constructor(status: number) { super(`Clerk answered HTTP ${status}`); this.status = status; } } /** Deliveries already checked (`svix-id` → decision), so a retry after a failed Clerk call does not pay twice. */ const SEEN_MAX = 1000; /** * Handles one delivery: `body` is the raw request body, `headers` its headers. Answers 400 for a delivery that fails * verification, 500 when Clerk's Backend API failed (5xx, 429, no answer: Clerk retries), else 200. */ export function createClerkWebhookHandler( options: HookOptions, ): (delivery: { body: string; headers: HeaderSource }) => Promise { const s = settings(options); const onStop = options.onStop ?? DEFAULTS.onStop; if (!['flag', 'ban', 'delete', 'none'].includes(onStop)) { throw new TypeError('onStop must be "flag", "ban", "delete" or "none".'); } const clerkKey = typeof options.clerkSecretKey === 'string' ? options.clerkSecretKey.trim() : ''; const signingSecret = typeof options.signingSecret === 'string' ? options.signingSecret.trim() : undefined; const seen = new Map(); async function clerk(method: string, path: string, body?: unknown): Promise { const response = await send( s.fetch, CLERK_API_ORIGIN, `${CLERK_API_ORIGIN}${path}`, { method, headers: { Authorization: `Bearer ${clerkKey}`, Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), }, 10_000, ); await discard(response); // 404: the user is already gone (deleted, or a dashboard test event): nothing left to stop. if (!response.ok && response.status !== 404) throw new ClerkCallError(response.status); } async function act(userId: string, decision: Decision): Promise { if (onStop === 'none') return; const path = `/v1/users/${encodeURIComponent(userId)}`; if (onStop === 'delete') return clerk('DELETE', path); const flag: EmailValidationMetadata = { status: decision.status as Status, reason: decision.reason, stopped: true, checked_at: new Date((options.nowS?.() ?? Date.now() / 1000) * 1000).toISOString(), }; await clerk('PATCH', `${path}/metadata`, { public_metadata: { [METADATA_KEY]: flag } }); if (onStop === 'ban') await clerk('POST', `${path}/ban`); } async function report(result: HookResult): Promise { try { await options.onResult?.(result); } catch { // the customer's callback never changes the answer to Clerk } } 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 } }; } if (event.type !== 'user.created') return { status: 200, body: { ignored: String(event.type ?? '') } }; const data = event.data !== null && typeof event.data === 'object' ? (event.data as Record) : {}; const userId = typeof data.id === 'string' && USER_ID.test(data.id) ? data.id : null; if (!userId) return { status: 200, body: { ignored: 'no_user_id' } }; const email = primaryEmail(data); if (!email) return { status: 200, body: { outcome: 'unchecked', error: 'no_email' } }; if (onStop !== 'none' && !clerkKey) { // Fails open like a missing API key: nothing could be done to the account, so nothing is checked or paid. await report({ userId, outcome: 'unchecked', action: null, decision: pass('missing_clerk_secret_key') }); return { status: 200, body: { outcome: 'unchecked', error: 'missing_clerk_secret_key' } }; } const deliveryId = header(headers, 'id') ?? ''; let decision = seen.get(deliveryId); if (!decision) { decision = await check(s, email).catch(() => pass('internal_error')); // `didYouMean` is a suggested address (the user's local part with another domain): the hook needs none, so it // is neither remembered nor handed to onResult. decision = { ...decision, didYouMean: null }; // Only definite answers are remembered: a delivery resent after our outage is checked again. if (decision.status !== null) { seen.set(deliveryId, decision); while (seen.size > SEEN_MAX) seen.delete(seen.keys().next().value as string); } } if (decision.allow) { const outcome = decision.status === null ? 'unchecked' : 'allowed'; await report({ userId, outcome, action: null, decision }); return { status: 200, body: { outcome, ...(decision.error ? { error: decision.error } : {}) } }; } try { await act(userId, decision); } catch (err) { const status = err instanceof ClerkCallError ? err.status : 0; if (status === 0 || status === 429 || status >= 500) { // Clerk retries the delivery. On this instance the answer above is reused, so the retry does not check (or // pay) again; a retry that reaches another instance (serverless) checks again. return { status: 500, body: { outcome: 'stopped', error: 'clerk_action_failed' } }; } // Refused (a wrong secret key, a bad request): a retry cannot help, so Clerk is told not to; the account stays. await report({ userId, outcome: 'unchecked', action: null, decision: { ...decision, allow: true, error: 'clerk_action_refused' }, }); return { status: 200, body: { outcome: 'unchecked', error: 'clerk_action_refused', clerk_status: status } }; } await report({ userId, outcome: 'stopped', action: onStop, decision }); return { status: 200, body: { outcome: 'stopped', action: onStop, status: decision.status } }; }; } /** 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 = createClerkSignupHook({ ... })`. */ export function createClerkSignupHook(options: HookOptions): (request: Request) => Promise { const handle = createClerkWebhookHandler(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 }); 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: new TextDecoder().decode(bytes), headers: request.headers }); return Response.json(result.body, { status: result.status }); }; }