import type { BetterAuthPlugin } from "better-auth"; import { APIError, createAuthMiddleware } from "better-auth/api"; /** What the SeeReal API returns for one address (POST /api/v1/check). */ export interface SeeRealResult { email: string; domain: string; action: "allow" | "review" | "block"; verdict: string; is_disposable: boolean; risk_score: number; reasons: string[]; suggestion: string | null; relay_provider: string | null; latency_ms: number; } export interface SeeRealOptions { /** Your SeeReal key (sr_beta_...). Defaults to process.env.SEEREAL_API_KEY. */ apiKey?: string; /** API endpoint. Defaults to https://app.seereal.email/api/v1/check. */ endpoint?: string; /** Give up after this many milliseconds and let the signup through. Default 3000. */ timeoutMs?: number; /** Block throwaway inboxes. Default true. */ blockDisposable?: boolean; /** Block domains that cannot receive mail. Default true. */ blockUndeliverable?: boolean; /** Reject typos like gmial.com with a "Did you mean ...?" message. Default true. */ blockTypos?: boolean; /** Also block privacy relays (Hide My Email, Firefox Relay). Default false: they forward to real people. */ blockRelays?: boolean; /** Which Better Auth endpoints to guard. Default: email sign-up, magic link, email OTP and change email. */ paths?: string[]; /** Custom decision: return an error message to block, or null to allow. Runs instead of the built-in rules. */ decide?: (result: SeeRealResult) => string | null | Promise; /** Called when the check could not run (no key, timeout, quota, network). The signup always goes through. */ onError?: (error: unknown, email: string) => void; /** For tests: a fetch implementation. Defaults to the global fetch. */ fetch?: typeof fetch; } const DEFAULT_PATHS = ["/sign-up/email", "/sign-in/magic-link", "/email-otp/send-verification-otp", "/change-email"]; /** Checks one address. Returns null when the check could not run, so callers can fail open. */ export async function checkEmail(email: string, options: SeeRealOptions = {}): Promise { const apiKey = options.apiKey ?? (typeof process !== "undefined" ? process.env.SEEREAL_API_KEY : undefined); const doFetch = options.fetch ?? fetch; if (!apiKey) { options.onError?.(new Error("SeeReal: no API key (set SEEREAL_API_KEY or pass apiKey)"), email); return null; } try { const res = await doFetch(options.endpoint ?? "https://app.seereal.email/api/v1/check", { method: "POST", headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" }, body: JSON.stringify({ email }), signal: AbortSignal.timeout(options.timeoutMs ?? 3000), }); const body = (await res.json().catch(() => null)) as (SeeRealResult & { error?: { code: string } }) | null; if (!res.ok || !body || typeof body.action !== "string") { options.onError?.(new Error(`SeeReal: ${body?.error?.code ?? `HTTP ${res.status}`}`), email); return null; } return body; } catch (err) { options.onError?.(err, email); return null; } } /** The built-in rules. Returns the message to show, or null to allow. */ export function defaultDecision(result: SeeRealResult, options: SeeRealOptions = {}): string | null { if (result.is_disposable && options.blockDisposable !== false) { return "Please use a permanent email address. Temporary inboxes are not accepted."; } if (result.relay_provider && options.blockRelays === true) { return "Please use your regular email address instead of a forwarding alias."; } if (result.action === "block" && options.blockUndeliverable !== false) { return "This email domain cannot receive mail. Please check the address."; } if (result.suggestion && options.blockTypos !== false) { return `Did you mean ${result.suggestion}? Please check the address.`; } return null; } /** * Better Auth plugin: checks the email on sign-up (and magic link, email OTP, change email) with SeeReal * and rejects throwaway, undeliverable and mistyped addresses with a 400 and a clear message. * Fails open: if SeeReal cannot be reached, the request goes through. */ export const seereal = (options: SeeRealOptions = {}) => { const paths = new Set(options.paths ?? DEFAULT_PATHS); return { id: "seereal", hooks: { before: [ { matcher: (context) => paths.has(context.path ?? ""), handler: createAuthMiddleware(async (ctx) => { const body = (ctx.body ?? {}) as { email?: unknown; newEmail?: unknown }; const email = typeof body.newEmail === "string" ? body.newEmail : body.email; if (typeof email !== "string" || !email.includes("@")) return; const result = await checkEmail(email.trim().toLowerCase(), options); if (!result) return; const message = options.decide ? await options.decide(result) : defaultDecision(result, options); if (message) { throw new APIError("BAD_REQUEST", { message, code: "SEEREAL_EMAIL_REJECTED" }); } }), }, ], }, } satisfies BetterAuthPlugin; }; export default seereal;