// 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 Better Auth: stop sign-ups with bad email addresses. One file; copy it into your app and * add `emailValidation({ apiKey: process.env.EV_API_KEY })` to the `plugins` of your **server** `betterAuth({ ... })` * config. There is no client plugin: the API key stays on your server. * * Two pieces, both added by the one plugin (README.md says what each covers per sign-in method): * * - A `user.create.before` database hook (added through the plugin's `init()`). Better Auth runs it before it writes * any new user row: email and password sign-up, a new user's magic link or email OTP sign-in, a first social or * generic OAuth sign-in, and users created by plugins or your own server code. It never runs for a returning user * (no row is created), so a returning user is never stopped by it. * - A request hook on `POST /sign-in/magic-link` and `POST /email-otp/send-verification-otp` (type `sign-in`): it * checks the address before Better Auth sends the link or code, so no mail goes to a bad address. It looks the * address up first and lets a returning user (one with an account) through unchecked. * * A stopped sign-up gets Better Auth's `APIError` `BAD_REQUEST` with code `EMAIL_ADDRESS_NOT_ACCEPTED`: a JSON error * for email and password, magic link sending and email OTP, a redirect to your error URL with * `?error=EMAIL_ADDRESS_NOT_ACCEPTED` for OAuth callbacks and magic link verification. * * Fails open: no key, a timeout, a network error, a rate limit, no credits 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; redirects are * never followed; nothing here logs an address or the key. */ import type { BetterAuthPlugin } from 'better-auth'; import { APIError, createAuthMiddleware } from 'better-auth/api'; export const VERSION = '1.0.0'; export const USER_AGENT = `email-validation-better-auth/${VERSION}`; export const PLUGIN_ID = 'email-validation'; /** 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. */ timeoutMs: 6000, 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; /** The `code` of the error a stopped sign-up gets (and the `error` query value of an OAuth or magic link redirect). */ export const ERROR_CODE = 'EMAIL_ADDRESS_NOT_ACCEPTED'; /** * How long a definite answer is reused for the same address on the same server instance (milliseconds), so a magic * link or code checked when it was sent is not paid for again when it is used. Better Auth's links and codes last 5 * minutes by default. */ export const REUSE_MS = 15 * 60 * 1000; const REUSE_MAX = 1000; /** The endpoints the request hook checks before Better Auth sends a link or a code. */ export const SEND_PATHS = Object.freeze(['/sign-in/magic-link', '/email-otp/send-verification-otp'] as const); export type FetchFn = (input: string, init?: RequestInit) => Promise; /** How a user is being created, read from the endpoint Better Auth is running. */ export type SignupMethod = | 'email-password' | 'magic-link' | 'email-otp' | 'oauth' | 'anonymous' | 'phone-number' | 'siwe' | 'other'; /** * Methods skipped by default: their users' addresses are usually placeholders Better Auth makes up (anonymous users, * phone number sign-ups' `getTempEmail`, wallet sign-ins), not addresses a person typed. */ export const SKIPPED_BY_DEFAULT = Object.freeze(['anonymous', 'phone-number', 'siwe'] as const); 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; } export interface CheckResult { method: SignupMethod; /** Better Auth's endpoint path, e.g. `/sign-up/email` or `/callback/:id`; null outside a request. */ path: string | null; /** `allowed`, `stopped`, or `unchecked` (no answer: the sign-up went through). */ outcome: 'allowed' | 'stopped' | 'unchecked'; /** `create` (the database hook) or `send` (before a magic link or code is sent). */ stage: 'create' | 'send'; /** Our answer, without the did-you-mean correction (it holds most of the address): only whether there was one. */ decision: Omit & { hasSuggestion: boolean }; } export interface SkipInfo { method: SignupMethod; path: string | null; /** The fields Better Auth is about to write (database hook), or `{ email }` (before sending). */ user: Record; } export interface EmailValidationOptions { /** 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; /** The message a stopped sign-up gets (default "Please sign up with another email address."). */ message?: string; /** * Check magic link and email OTP sign-ups before the link or code is sent (default true). Off: they are checked * only when the new user is created, after the mail went out. */ checkBeforeSending?: boolean; /** * Return true to let a sign-up through unchecked (no credit used). Default: `SKIPPED_BY_DEFAULT` (anonymous users, * phone number and wallet sign-ups, whose addresses are usually made up). Your function replaces the default. * It is awaited before the check, so keep it quick. */ skip?: (info: SkipInfo) => boolean | Promise; /** Called once per check (never with the address). Not awaited: it cannot hold up a sign-up; errors are ignored. */ onResult?: (result: CheckResult) => void | Promise; /** For tests and proxies; default: the global fetch. */ fetch?: FetchFn; } interface Settings { apiKey: string; origin: string; stop: readonly StoppableStatus[]; timeoutMs: number; fetch: FetchFn; } function settings(options: EmailValidationOptions): 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` (connect, headers and body). Rejects * on a foreign host, no answer or a redirect; answers the Response for any other status. */ async function send(s: Settings, url: string, init: RequestInit, signal: AbortSignal): Promise { if (new URL(url).origin !== s.origin) throw new Error(`Refused a request to a host other than ${s.origin}.`); const headers = new Headers(init.headers); headers.set('User-Agent', USER_AGENT); const response = await s.fetch(url, { ...init, headers, redirect: 'manual', signal }); if ((response.status >= 300 && response.status < 400) || response.type === 'opaqueredirect') { try { await response.body?.cancel(); } catch { // already closed } throw new Error('redirect'); } return response; } function isTimeout(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'); // One signal for the whole exchange, so a stalled body cannot outlast `timeoutMs`. No retry. const signal = AbortSignal.timeout(s.timeoutMs); let response: Response; try { response = await send( s, `${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 }), }, signal, ); } catch (err) { if (isTimeout(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 (isTimeout(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 failed = status === 'unknown' && (NEVER_STOP_REASONS as readonly string[]).includes(reason ?? ''); // An answer flagged `disposable` is stopped when `disposable` is in `stop`, whatever its status (our API keeps // `invalid` or `unknown` as the status of some addresses on disposable domains). const stopped = !failed && ((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. For your own server code; the * plugin uses the same check. */ export function createEmailCheck(options: EmailValidationOptions): (email: string) => Promise { const s = settings(options); return (email) => check(s, email).catch(() => pass('internal_error')); } /** Which sign-in method an endpoint path belongs to. */ export function methodOf(path: string | null | undefined): SignupMethod { if (typeof path !== 'string') return 'other'; if (path === '/sign-up/email') return 'email-password'; if (path === '/sign-in/magic-link' || path === '/magic-link/verify') return 'magic-link'; if (path === '/sign-in/email-otp' || path === '/email-otp/send-verification-otp') return 'email-otp'; if (path === '/sign-in/anonymous') return 'anonymous'; if (path === '/phone-number/verify' || path === '/sign-in/phone-number') return 'phone-number'; if (path === '/siwe/verify') return 'siwe'; if (path === '/sign-in/social' || path.startsWith('/callback/') || path === '/one-tap/callback') { return 'oauth'; } return 'other'; } /** Definite answers by SHA-256 of the lower-cased address (the address itself is not kept), for `REUSE_MS`. */ class Reuse { readonly #entries = new Map(); static async key(email: string): Promise { const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(email.trim().toLowerCase())); return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join(''); } get(key: string, now: number): Decision | undefined { const entry = this.#entries.get(key); if (!entry) return undefined; if (entry.until <= now) { this.#entries.delete(key); return undefined; } return entry.decision; } set(key: string, decision: Decision, now: number): void { this.#entries.delete(key); this.#entries.set(key, { decision, until: now + REUSE_MS }); while (this.#entries.size > REUSE_MAX) this.#entries.delete(this.#entries.keys().next().value as string); } } /** The part of Better Auth's endpoint context this plugin reads (`ctx.path`, `ctx.body`, the internal adapter). */ interface EndpointContextLike { path?: string; body?: unknown; context?: { internalAdapter?: { findUserByEmail?: (email: string) => Promise }; getPlugin?: (id: string) => { options?: { disableSignUp?: unknown } } | null | undefined; }; } /** Whether an answer means our side ran out of time or failed (never stops, never reused). */ function ourFailure(d: Decision): boolean { return d.status === 'unknown' && (NEVER_STOP_REASONS as readonly string[]).includes(d.reason ?? ''); } function defaultSkip(info: SkipInfo): boolean { return (SKIPPED_BY_DEFAULT as readonly string[]).includes(info.method); } /** * The Better Auth plugin. Add it to your server config only: * * ```ts * import { betterAuth } from 'better-auth'; * import { emailValidation } from './email-validation-better-auth'; * * export const auth = betterAuth({ * // ... * plugins: [emailValidation({ apiKey: process.env.EV_API_KEY })], * }); * ``` */ export function emailValidation(options: EmailValidationOptions) { const s = settings(options); const message = typeof options.message === 'string' && options.message.trim() ? options.message.trim() : DEFAULTS.message; const checkBeforeSending = options.checkBeforeSending ?? true; const skip = options.skip ?? defaultSkip; const now = (): number => Date.now(); const reuse = new Reuse(); function report(result: CheckResult): void { // The customer's callback never changes or delays the sign-up: not awaited, errors ignored. try { const returned = options.onResult?.(result) as unknown; if (returned instanceof Promise) returned.catch(() => {}); } catch { // ignored } } async function shouldSkip(info: SkipInfo): Promise { try { return (await skip(info)) === true; } catch { return false; } } /** Checks (or reuses an answer), reports, and throws Better Auth's APIError when the address is stopped. */ async function decide(email: string, method: SignupMethod, path: string | null, stage: 'create' | 'send') { let key: string | null = null; let decision: Decision | undefined; try { key = await Reuse.key(email); decision = reuse.get(key, now()); } catch { key = null; } if (!decision) { decision = await check(s, email).catch(() => pass('internal_error')); // Only definite answers are kept, without the correction: after our outage, or an `unknown` that means our // side timed out or failed, the next attempt is checked again. if (key && decision.status !== null && !ourFailure(decision)) { reuse.set(key, { ...decision, didYouMean: null }, now()); } } const outcome = decision.allow ? (decision.status === null ? 'unchecked' : 'allowed') : 'stopped'; const { didYouMean, ...reported } = decision; report({ method, path, outcome, stage, decision: { ...reported, hasSuggestion: didYouMean !== null } }); if (!decision.allow) { // BAD_REQUEST, never FORBIDDEN: Better Auth's email sign-up answers a 403 from user creation with its generic // "user already exists" response when it hides duplicate sign-ups. The `code` makes the OAuth callback and // magic link verification redirect with `?error=` instead of failing. throw new APIError('BAD_REQUEST', { code: ERROR_CODE, message, ...(didYouMean ? { didYouMean } : {}), }); } } return { id: PLUGIN_ID, init() { return { options: { databaseHooks: { user: { create: { // Better Auth passes the endpoint context, or nothing outside a request. Returning nothing keeps the // user's data as it is; throwing stops the creation. before: async (user: Record, ctx?: EndpointContextLike | null) => { const path = typeof ctx?.path === 'string' ? ctx.path : null; const method = user?.isAnonymous === true ? 'anonymous' : methodOf(path); const email = user?.email; if (typeof email !== 'string' || email === '') return; if (await shouldSkip({ method, path, user: { ...user } })) return; await decide(email, method, path, 'create'); }, }, }, }, }, }; }, hooks: { before: [ { matcher: (context: EndpointContextLike) => checkBeforeSending && (SEND_PATHS as readonly string[]).includes(context.path ?? ''), handler: createAuthMiddleware(async (ctx) => { const c = ctx as unknown as EndpointContextLike; const path = c.path ?? null; const body = c.body !== null && typeof c.body === 'object' ? (c.body as Record) : {}; // Email OTP: only a sign-in code can create a user; verification and password reset codes are left alone. if (path === '/email-otp/send-verification-otp' && body.type !== 'sign-in') return; // The sign-in plugin cannot create users (`disableSignUp`): no new user can come of this, so no check. let signInPlugin: { options?: { disableSignUp?: unknown } } | null | undefined; try { signInPlugin = c.context?.getPlugin?.(path === '/sign-in/magic-link' ? 'magic-link' : 'email-otp'); } catch { signInPlugin = null; } if (signInPlugin?.options?.disableSignUp === true) return; const email = body.email; if (!looksLikeAddress(email)) return; // A returning user is never checked here. If the lookup fails, nothing is checked now: the database hook // still checks a new user when the link or code is used. const find = c.context?.internalAdapter?.findUserByEmail; if (typeof find !== 'function') return; let existing: unknown; try { existing = await find.call(c.context?.internalAdapter, email.trim().toLowerCase()); } catch { return; } if (existing) return; const method = methodOf(path); if (await shouldSkip({ method, path, user: { email } })) return; await decide(email, method, path, 'send'); }), }, ], }, $ERROR_CODES: { [ERROR_CODE]: { code: ERROR_CODE, message } }, } satisfies BetterAuthPlugin; }