/** * email-validation.org for Supabase 1.0.0: a "Before User Created" Auth Hook, as a Supabase Edge Function. * * Supabase Auth calls it before it creates each new user (email and password, phone, magic link and OTP sign-ups, * new OAuth users). It checks the new user's email address with email-validation.org and refuses the sign-up, with a * message the person sees, when the result's status is one you chose to stop. Everything else goes through: a fine * address, a sign-up without an email address (phone, anonymous), and whenever a check cannot be made (our API slow, * down, rate limited, a wrong or missing key, an unexpected answer, any error here). A check is never retried, so it * never holds a sign-up up for longer than TIMEOUT_MS. One file, no dependencies. * * Settings are the function's secrets (`supabase secrets set NAME=value`, or Dashboard → Edge Functions → Secrets): * BEFORE_USER_CREATED_HOOK_SECRET required: the hook's secret from Authentication → Hooks (`v1,whsec_…`). A * request that does not carry its signature is never checked and gets the "go on" answer, so a * wrong secret lets every sign-up through rather than blocking them (the log says so). * EV_API_KEY required: an API key with the permission "Validate addresses" (a daily credit cap is wise). * EV_REGION optional: "eu" sends the checks to our EU host (EU data residency); anything else is US. * EV_STOP_STATUSES optional: the statuses that stop a sign-up, separated by commas, from invalid, disposable, * catch_all and unknown. Default "invalid,disposable"; "none" stops nothing (results only logged). * EV_DENY_MESSAGE optional: the message the person signing up sees instead of the default ones below. * * Each check costs one credit; unknown results and test addresses on sandbox.email-validation.org are free. * Logs hold the status, the reason, our error code and the request id, never the address or the key. */ export const VERSION = '1.0.0'; export const USER_AGENT = `email-validation-supabase/${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. `valid` always passes. */ export const STOPPABLE = Object.freeze(['invalid', 'disposable', 'catch_all', 'unknown'] as const); export type StoppableStatus = (typeof STOPPABLE)[number]; export const DEFAULT_STOP: readonly StoppableStatus[] = Object.freeze(['invalid', 'disposable'] as const); /** * `unknown` answers that mean our side ran out of time or failed, not something about the address: they never stop a * sign-up, even with `unknown` in EV_STOP_STATUSES. */ export const NEVER_STOP_REASONS = Object.freeze(['timeout', 'internal_error'] as const); /** The API's shortest check time, in seconds (the `timeout` field's minimum). */ export const SERVER_TIMEOUT_S = 5; /** * How long a check may take, answer and body included, before the sign-up goes through unchecked. Supabase Auth gives * an HTTP hook 5 seconds in all (the function's cold start included) and refuses the sign-up when the hook has not * answered by then, so the function stops waiting well before. */ export const TIMEOUT_MS = 3000; /** Supabase Auth's limit for one HTTP hook call, in milliseconds (its `defaultHTTPHookTimeout`). */ export const SUPABASE_HOOK_LIMIT_MS = 5000; /** How far a request's timestamp may be from now, in seconds (Standard Webhooks). */ export const WEBHOOK_TOLERANCE_S = 300; /** The HTTP status Supabase Auth answers the sign-up with when it is refused (its error's `http_code`). */ export const DENY_HTTP_CODE = 400; /** * The largest request read, in bytes. Supabase Auth takes sign-up requests of up to 1 MiB and copies the sign-up's * `data` into `user_metadata` unchecked, and its JSON escapes `<`, `>` and `&` as six bytes each, so a hook request * can be up to about 6 MiB: the cap is above that, so a padded sign-up is still checked. Only a request no Supabase * sign-up can produce is larger; it is not checked. */ export const MAX_BODY_BYTES = 8 * 1024 * 1024; /** After a 429 or 503 without Retry-After, no check is sent for this long; a longer Retry-After is cut to the max. */ export const DEFAULT_PAUSE_S = 30; export const MAX_PAUSE_S = 300; export const MESSAGES = Object.freeze({ invalid: 'This email address cannot receive email. Please check it or use another address.', disposable: 'Please sign up with a permanent email address, not a disposable one.', other: 'Please sign up with a different email address.', }); export type FetchFn = (input: string, init?: RequestInit) => Promise; export interface HandlerOptions { /** Reads a setting (the function's secrets): `Deno.env.get` in Supabase. */ env: (name: string) => string | undefined; /** For tests and proxies; default: the global fetch. */ fetch?: FetchFn; /** For tests: the check's time limit (default TIMEOUT_MS). */ timeoutMs?: number; /** For tests: the current time in milliseconds. */ nowMs?: () => number; /** Where the one log line per run goes (default console.log, which Supabase keeps as the function's logs). */ log?: (line: string) => void; } /** What a check found: a status, or null when there was no answer (`note` says why). */ export interface CheckResult { status: Status | null; reason: string; disposable: boolean; didYouMean: string; requestId: string; note: string; } // --------------------------------------------------------------------------------------------------------------- // The answers Supabase Auth understands (its HTTP hook contract): HTTP 200 with `Content-Type: application/json`; a // body without an `error` lets the user be created, `{"error":{"http_code":…,"message":…}}` refuses the sign-up with // that status and message. Any other HTTP status (400, 401, 403, 500…) or content type makes Auth refuse the sign-up // with a generic error, so this function never answers one to Auth. function allow(): Response { return new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } }); } function deny(message: string): Response { return new Response(JSON.stringify({ error: { http_code: DENY_HTTP_CODE, message } }), { status: 200, headers: { 'Content-Type': 'application/json' }, }); } /** 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); } /** * The stop list from EV_STOP_STATUSES: absent or empty is the default, "none" is an empty list; names that are not a * stoppable status are noted and left out, and a list left with none of them falls back to the default. */ export function stopList(value: string | undefined, notes: string[] = []): readonly StoppableStatus[] { if (typeof value !== 'string' || value.trim() === '') return DEFAULT_STOP; if (value.trim().toLowerCase() === 'none') return []; const names = value .split(',') .map((name) => name.trim().toLowerCase()) .filter((name) => name !== ''); const known = names.filter((name): name is StoppableStatus => (STOPPABLE as readonly string[]).includes(name)); const left = names.filter((name) => !(STOPPABLE as readonly string[]).includes(name)); if (left.length > 0) notes.push(`EV_STOP_STATUSES: left out ${left.join(', ')} (not a status that can be stopped).`); if (known.length === 0) { notes.push('EV_STOP_STATUSES names no status that can be stopped: the default invalid,disposable applies.'); return DEFAULT_STOP; } return Object.freeze([...new Set(known)]); } /** Retry-After in seconds: delay-seconds, or an HTTP date (IMF-fixdate, RFC 850 or asctime); anything else is null. */ const HTTP_DATES = [ /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/, /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), \d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{2} \d{2}:\d{2}:\d{2} GMT$/, /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [ \d]\d \d{2}:\d{2}:\d{2} \d{4}$/, ]; export function retryAfterSeconds(value: string | null, nowMs: number): number | null { if (typeof value !== 'string') return null; const text = value.trim(); if (/^\d+$/.test(text)) return Number(text); if (!HTTP_DATES.some((form) => form.test(text))) return null; // asctime has no zone: it is GMT. const at = Date.parse(/GMT$/.test(text) ? text : `${text} GMT`); return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - nowMs) / 1000)); } // --------------------------------------------------------------------------------------------------------------- // Request verification (Standard Webhooks, as Supabase Auth signs its HTTP hooks): `webhook-id`, `webhook-timestamp` // and `webhook-signature` (`v1,..">`), keyed with the base64 after // `v1,whsec_`, 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'; } } 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); } /** The key bytes of a secret: `v1,whsec_` as Supabase shows it, `whsec_`, or the base64 alone. */ function secretBytes(secret: string | undefined): Uint8Array { if (typeof secret !== 'string' || secret === '') throw new WebhookVerificationError('Missing webhook secret.'); let text = secret.startsWith('v1,') ? secret.slice(3) : secret; if (text.startsWith('whsec_')) text = text.slice(6); const key = decodeBase64(text); 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 `webhook-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}`))}`; } type HeaderSource = Headers | Record; /** A header in any case; repeated values joined with one space. */ function header(headers: HeaderSource, name: string): string | null { if (headers instanceof Headers) return headers.get(name); if (!headers || typeof headers !== 'object') return null; const values: string[] = []; for (const [key, value] of Object.entries(headers)) { if (key.toLowerCase() !== name || 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; } return values.length > 0 ? values.join(' ') : null; } /** * Verifies a request and returns its parsed JSON body. `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, 'webhook-id'); const timestamp = header(headers, 'webhook-timestamp'); const signatures = header(headers, 'webhook-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 parseBody(body); } throw new WebhookVerificationError('No webhook signature matched.'); } function parseBody(body: string): Record { let parsed: unknown = null; try { parsed = JSON.parse(body); } catch { // not JSON: refused below } if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { throw new WebhookVerificationError('The webhook body is not JSON.'); } return parsed as Record; } /** * Verifies against each secret in turn: the setting may hold several separated by `|` (as Supabase's own `secrets` * setting does while a secret is rotated). The last secret's error is thrown when none matches. */ async function verifyWithAny( body: string, headers: Headers, secrets: readonly string[], nowS: number, ): Promise> { let last: unknown = new WebhookVerificationError('Missing webhook secret.'); for (const secret of secrets) { try { return await verifyWebhook(body, headers, secret, { nowS }); } catch (err) { last = err; } } throw last; } // --------------------------------------------------------------------------------------------------------------- // The check. interface Run { outcome: string[]; notes: string[]; } function asRecord(value: unknown): Record { return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record) : {}; } /** Reads a body (a body that does not come in time rejects, like no answer); null when it is not JSON. */ async function readJson(response: Response): Promise { const text = await response.text(); try { return JSON.parse(text); } catch { return null; } } /** A request's body as text, read up to `max` bytes (a chunked body too); null when it is longer. */ async function readBounded(request: Request, max: number): Promise { if (!request.body) return ''; 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 bytes = new Uint8Array(size); let at = 0; for (const chunk of chunks) { bytes.set(chunk, at); at += chunk.byteLength; } return new TextDecoder().decode(bytes); } /** 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; } const REASON = /^[a-z_]{1,64}$/; // a reason is kept only in this shape /** 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 } } /** * The hook. Answers Supabase Auth: `{}` (the user is created) or the refusal; never anything else, so no failure on * this side can block a sign-up. */ export function createHandler(options: HandlerOptions): (request: Request) => Promise { const fetchFn: FetchFn = options.fetch ?? ((input, init) => globalThis.fetch(input, init)); const timeoutMs = options.timeoutMs ?? TIMEOUT_MS; const nowMs = options.nowMs ?? (() => Date.now()); const log = options.log ?? ((line: string) => console.log(line)); // Until when no check is sent, after our API asked to wait. Lives as long as Supabase keeps this function's // instance running. let pausedUntil = 0; function setting(name: string): string { try { const value = options.env(name); return typeof value === 'string' ? value.trim() : ''; } catch { return ''; } } async function check(email: string, apiKey: string, region: string, run: Run): Promise { if (nowMs() < pausedUntil) { run.outcome.push('not checked: paused after a rate limit.'); return null; } const origin = region.toLowerCase() === 'eu' ? API_ORIGINS.eu : API_ORIGINS.us; let response: Response; let body: unknown; try { // One signal bounds the answer and its body. Never retried: the check may have run and been charged, and the // sign-up is waiting. response = await fetchFn(`${origin}/v1/validate`, { method: 'POST', headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', Accept: 'application/json', 'User-Agent': USER_AGENT, }, body: JSON.stringify({ email: email.trim(), timeout: SERVER_TIMEOUT_S }), redirect: 'manual', signal: AbortSignal.timeout(timeoutMs), }); if ((response.status >= 300 && response.status < 400) || response.type === 'opaqueredirect') { await discard(response); run.outcome.push(`not checked (HTTP ${response.status}, a redirect is never followed).`); return null; } body = await readJson(response); } catch { run.outcome.push('not checked: no answer from the API in time (not retried).'); return null; } const record = asRecord(body); // Never a value that quotes the key (a broken or hostile proxy): code, request id and reason only in our shapes. const headerId = requestIdOf(response.headers.get('x-request-id'), apiKey) ?? ''; if ( response.status === 200 && typeof record.status === 'string' && (STATUSES as readonly string[]).includes(record.status) ) { return { status: record.status as Status, reason: typeof record.reason === 'string' && REASON.test(record.reason) && !sharesKey(record.reason, apiKey) ? record.reason : '', disposable: record.disposable === true, didYouMean: looksLikeAddress(record.did_you_mean) && !sharesKey(record.did_you_mean, apiKey) ? record.did_you_mean : '', requestId: requestIdOf(record.request_id, apiKey) ?? headerId, note: '', }; } const error = asRecord(record.error); const code = codeOf(error.code, apiKey) || 'unexpected_response'; const requestId = requestIdOf(error.request_id, apiKey) ?? requestIdOf(record.request_id, apiKey) ?? headerId; const where = ` (HTTP ${response.status}, ${code}${requestId ? `, request ${requestId}` : ''})`; if ((response.status === 429 || response.status === 503) && code !== 'key_daily_cap') { const after = retryAfterSeconds(response.headers.get('retry-after'), nowMs()); pausedUntil = nowMs() + Math.min(after === null ? DEFAULT_PAUSE_S : after, MAX_PAUSE_S) * 1000; run.outcome.push(`not checked: rate limited${where}.`); return null; } run.outcome.push(`not checked${where}.`); return null; } /** The refusal's message when the sign-up is to be stopped, otherwise null. */ async function verdict(request: Request, run: Run): Promise { if (request.method !== 'POST') return null; const length = Number(request.headers.get('content-length') ?? '0'); if (Number.isFinite(length) && length > MAX_BODY_BYTES) { run.outcome.push('not checked: the request is larger than a hook request.'); return null; } const raw = await readBounded(request, MAX_BODY_BYTES); if (raw === null) { run.outcome.push('not checked: the request is larger than a hook request.'); return null; } const secrets = setting('BEFORE_USER_CREATED_HOOK_SECRET') .split('|') .map((s) => s.trim()) .filter((s) => s !== ''); if (secrets.length === 0) { run.outcome.push('not checked: the secret BEFORE_USER_CREATED_HOOK_SECRET is missing.'); return null; } let event: Record; try { event = await verifyWithAny(raw, request.headers, secrets, Math.floor(nowMs() / 1000)); } catch (err) { // Not from Supabase Auth, or the secret here is not the hook's: nothing is checked and the answer is "go on" // (it creates nothing by itself; only Supabase Auth acts on it). const why = err instanceof WebhookVerificationError ? err.message : 'verification failed.'; run.outcome.push(`not checked: the request's signature did not verify: ${why}`); return null; } const user = asRecord(event.user); // Phone and anonymous sign-ups, and OAuth users without an address, have no email: they go through. if (!looksLikeAddress(user.email)) return null; const apiKey = setting('EV_API_KEY'); if (!apiKey || /\s/.test(apiKey)) { run.outcome.push('not checked: the secret EV_API_KEY is missing.'); return null; } const stop = stopList(setting('EV_STOP_STATUSES'), run.notes); const result = await check(user.email, apiKey, setting('EV_REGION'), run); if (!result || result.status === null) return null; const said = `${result.status} (reason ${result.reason || 'none'}, request ${result.requestId || 'none'})`; if (stop.length === 0) { run.outcome.push(`checked: ${said}; EV_STOP_STATUSES is none, nothing is stopped.`); return null; } const ourFailure = result.status === 'unknown' && (NEVER_STOP_REASONS as readonly string[]).includes(result.reason); // A `valid` answer for a disposable domain stops too when `disposable` is stopped. const stopped = !ourFailure && ((stop as readonly string[]).includes(result.status) || (stop.includes('disposable') && result.disposable)); if (!stopped) return null; run.outcome.push(`stopped: ${said}.`); const custom = setting('EV_DENY_MESSAGE'); if (custom) return custom; const kind = result.status === 'invalid' ? 'invalid' : result.status === 'disposable' || result.disposable ? 'disposable' : 'other'; let message: string = MESSAGES[kind]; if (kind === 'invalid' && result.didYouMean) message = `${message} Did you mean ${result.didYouMean}?`; return message; } return async (request) => { const run: Run = { outcome: [], notes: [] }; let message: string | null = null; try { message = await verdict(request, run); } catch { run.outcome.push('not checked: unexpected error; the sign-up goes on.'); message = null; } const parts = [...run.outcome, ...run.notes]; if (parts.length > 0) { try { log(`email-validation.org: ${parts.join(' ')}`); } catch { // logging never changes the answer } } return message === null ? allow() : deny(message); }; } // --------------------------------------------------------------------------------------------------------------- // Supabase Edge Functions run on Deno: serve the hook there. (Elsewhere, e.g. in tests, nothing starts.) export interface DenoLike { env: { get(name: string): string | undefined }; serve(handler: (request: Request) => Response | Promise): unknown; } export function main(deno: DenoLike): unknown { return deno.serve(createHandler({ env: (name) => deno.env.get(name) })); } const deno = (globalThis as { Deno?: DenoLike }).Deno; if (deno && typeof deno.serve === 'function' && deno.env && typeof deno.env.get === 'function') main(deno);