// 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 Auth.js: stop sign-ups with bad email addresses. One file, no dependencies; copy it into * the server side of your app next to your Auth.js configuration (Next.js with `next-auth` v5, SvelteKit, Express, * Qwik or anything else on `@auth/core`). * * Auth.js has one documented place where an app can refuse a sign-in: the `signIn` callback ("Returning `false` or * throwing an error will stop the sign-in flow"). Auth.js calls it for every sign-in method, new and returning users * alike, so this file gives: * * - `createSignInCheck()`: a `signIn` callback (or a function your own `signIn` callback calls first). For OAuth and * OIDC it runs after the provider answers and before Auth.js creates the user; for an email (magic link) provider * it runs before the mail is sent; for WebAuthn it runs before a new passkey account is created. It checks only * new users: it asks your Auth.js database adapter whether the person already has an account, or your own * `isNewUser()`, and leaves everyone it knows alone. * - `checkSignupEmail()`: the same check for your own registration code (the Credentials provider has no sign-up in * Auth.js: you create those users yourself, so you call this before you do). * * Fails open: no key, a timeout, a network error, a rate limit, no credits or any error answer lets the sign-up * through, and so does a failing adapter lookup. 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, and it refuses to run in * a browser. */ export const VERSION = '1.0.0'; export const USER_AGENT = `email-validation-authjs/${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); /** The Auth.js account types (`account.type`) whose new users the `signIn` callback can check. */ export const CHECKABLE_TYPES = Object.freeze(['oauth', 'oidc', 'email', 'webauthn'] as const); export type CheckableType = (typeof CHECKABLE_TYPES)[number]; 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. Auth.js itself sets no limit on its callbacks. */ timeoutMs: 6000, methods: CHECKABLE_TYPES, }); /** The API's shortest check time, in seconds: a check that needs longer ends as a free `unknown`. */ export const SERVER_TIMEOUT_S = 5; 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; } /** Throws in a browser: the API key must stay on the server (never in client code or a `NEXT_PUBLIC_` variable). */ function serverOnly(): void { if (typeof (globalThis as { document?: unknown }).document !== 'undefined') { throw new Error('email-validation-authjs runs on the server only: keep your API key out of browser code.'); } } function settings(options: CheckOptions): Settings { serverOnly(); 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, e.g. your registration route before it creates a user for the * Credentials provider. 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); } // --------------------------------------------------------------------------------------------------------------- // The `signIn` callback. Its argument and return value follow `@auth/core` (`callbacks.signIn` in its `index.ts`, // called from `lib/actions/signin/send-token.ts` and `lib/actions/callback/index.ts`): `true` lets the sign-in go on, // `false` makes Auth.js throw `AccessDenied` (the error page, `?error=AccessDenied`), a string makes it redirect // there. The types below are the parts of Auth.js's own types this file reads, so it needs no import. /** What Auth.js passes to `callbacks.signIn` (the fields this file reads). */ export interface SignInParams { user?: { id?: string | null; email?: string | null } | null; account?: { type?: string; provider?: string; providerAccountId?: string } | null; profile?: { email?: string | null } | null; /** `{ verificationRequest: true }` on an email provider's first call, before the mail is sent. */ email?: { verificationRequest?: boolean } | null; credentials?: Record; } /** The two lookups of an Auth.js database adapter this file uses (pass the same adapter you give Auth.js). */ export interface AdapterLookup { getUserByEmail?: ((email: string) => unknown) | undefined; getUserByAccount?: ((account: { provider: string; providerAccountId: string }) => unknown) | undefined; } export type Outcome = /** Checked; the status is not on your stop list. */ | 'allowed' /** Checked; the status is on your stop list: the sign-in is refused. */ | 'stopped' /** Checked, but there was no definite answer (`decision.error` says why): let through. */ | 'failed_open' /** The person already has an account (adapter or `isNewUser`): not checked. */ | 'returning' /** A method or call this hook does not check (Credentials, a magic link being opened, a type not in `methods`). */ | 'not_checked' /** Your adapter or `isNewUser` threw: not checked, let through. */ | 'lookup_failed'; export interface SignInResult { /** The provider id, e.g. `github`, `resend`. */ provider: string | null; /** The account type: `oauth`, `oidc`, `email`, `webauthn` or `credentials`. */ type: string | null; outcome: Outcome; /** The check's decision when a check ran, else null. Its `didYouMean` is always null here: it is an address. */ decision: Decision | null; } export interface SignInCheckOptions extends CheckOptions { /** * Your Auth.js database adapter: the hook asks it whether the person already has an account (`getUserByAccount` * for OAuth, then `getUserByEmail`) and checks only those who do not. One of `adapter`, `isNewUser` or * `checkEverySignIn: true` is required. */ adapter?: AdapterLookup | null; /** Your own answer to "is this a new user?" (wins over `adapter`). Throwing lets the sign-in through unchecked. */ isNewUser?: (params: SignInParams) => boolean | Promise; /** * With no adapter (sessions in a JWT only) Auth.js keeps no users, so nothing can tell a new user from a returning * one. `true` checks every sign-in: a returning user whose address has since become a stopped status is refused. */ checkEverySignIn?: boolean; /** * Where a stopped sign-in goes, e.g. `/signup?error=email`. Default: Auth.js's error page (`AccessDenied`). Not for * WebAuthn: Auth.js ignores a string answer there and would create the account, so a stopped passkey sign-up * always answers `false` (the error page). */ redirectTo?: string; /** The account types to check (default all four: `oauth`, `oidc`, `email`, `webauthn`). */ methods?: readonly CheckableType[]; /** Called once per sign-in with what happened (never the address). Errors in it are ignored. */ onResult?: (result: SignInResult) => unknown; } /** Answers whether the person is new; throws when the lookup failed. */ type NewUserTest = (params: SignInParams, email: string) => Promise; function newUserTest(options: SignInCheckOptions): NewUserTest { const { isNewUser, adapter, checkEverySignIn } = options; if (isNewUser !== undefined) { if (typeof isNewUser !== 'function') throw new TypeError('isNewUser must be a function.'); return async (params) => Boolean(await isNewUser(params)); } if (adapter !== undefined && adapter !== null) { if (typeof adapter !== 'object' || typeof adapter.getUserByEmail !== 'function') { throw new TypeError('adapter must be your Auth.js database adapter (it needs getUserByEmail).'); } const byEmail = adapter.getUserByEmail.bind(adapter); const byAccount = typeof adapter.getUserByAccount === 'function' ? adapter.getUserByAccount.bind(adapter) : null; return async (params, email) => { const account = params.account; if ( byAccount && (account?.type === 'oauth' || account?.type === 'oidc') && typeof account.provider === 'string' && typeof account.providerAccountId === 'string' ) { const known = await byAccount({ provider: account.provider, providerAccountId: account.providerAccountId }); if (known) return false; } // Auth.js keeps addresses as its provider gave them (an email provider lowercases them first). return !(await byEmail(email.trim())); }; } if (checkEverySignIn === true) return async () => true; throw new TypeError( 'Choose how new users are told from returning ones: pass your Auth.js adapter, an isNewUser function, or ' + 'checkEverySignIn: true (every sign-in is then checked, returning users too).', ); } /** * A `signIn` callback for Auth.js that refuses a new user whose address has a status you stop. Use it as * `callbacks: { signIn: emailCheck }`, or call it first in your own `signIn` callback and return its answer when it * is not `true`. Never throws during a sign-in; answers `true`, `false` or your `redirectTo`. */ export function createSignInCheck(options: SignInCheckOptions): (params: SignInParams) => Promise { const s = settings(options); const isNew = newUserTest(options); const redirectTo = options.redirectTo; if (redirectTo !== undefined && (typeof redirectTo !== 'string' || redirectTo.trim() === '')) { throw new TypeError('redirectTo must be a URL or a path such as /signup?error=email.'); } const methods = options.methods ?? DEFAULTS.methods; if (!Array.isArray(methods) || methods.some((m) => !(CHECKABLE_TYPES as readonly string[]).includes(m))) { throw new TypeError(`methods must list only ${CHECKABLE_TYPES.join(', ')}.`); } const checked = Object.freeze([...methods]) as readonly string[]; const onResult = options.onResult; if (onResult !== undefined && typeof onResult !== 'function') throw new TypeError('onResult must be a function.'); const report = (params: SignInParams, outcome: Outcome, decision: Decision | null) => { if (!onResult) return; const provider = typeof params?.account?.provider === 'string' ? params.account.provider : null; const type = typeof params?.account?.type === 'string' ? params.account.type : null; // `didYouMean` is a suggested address (the user's local part with another domain): never handed on. const safe = decision ? { ...decision, didYouMean: null } : null; try { Promise.resolve(onResult({ provider, type, outcome, decision: safe })).catch(() => undefined); } catch { // the customer's callback failed: the sign-in is not its business } }; const run = async (params: SignInParams): Promise => { const type = params?.account?.type; // Credentials: Auth.js has no sign-up for them; `authorize` already found (or made) the user. An email provider // calls back a second time when the link is opened: the address was checked before the mail went out. if (typeof type !== 'string' || !checked.includes(type)) { report(params, 'not_checked', null); return true; } if (type === 'email' && params.email?.verificationRequest !== true) { report(params, 'not_checked', null); return true; } const email = typeof params.user?.email === 'string' && params.user.email ? params.user.email : typeof params.profile?.email === 'string' ? params.profile.email : ''; if (!looksLikeAddress(email)) { report(params, 'not_checked', pass('not_an_address')); return true; } let fresh: boolean; try { fresh = await isNew(params, email); } catch { report(params, 'lookup_failed', null); return true; } if (!fresh) { report(params, 'returning', null); return true; } const decision = await check(s, email).catch(() => pass('internal_error')); if (decision.allow) { report(params, decision.status === null ? 'failed_open' : 'allowed', decision); return true; } report(params, 'stopped', decision); // Auth.js's WebAuthn branch ignores what handleAuthorized returns: only `false` (or a throw) stops it there. if (type === 'webauthn') return false; return redirectTo ?? false; }; return (params) => run(params).catch(() => true); }