import { HONEYPOT_FIELD_NAMES, TURNSTILE_TOKEN_FIELD } from '../constants' import type { ContactData, ContactErrorCode, ContactField } from '../types' import { renderContactEmail, type BrandConfig } from '../email/template' import { getClientIp } from './ip' import { validateHoneypot } from './honeypot' import { verifyTurnstileToken } from './turnstile' import { createRateLimiter, type RateLimitConfig } from './rate-limit' import { validateContact } from './validate' import { sendContactEmail } from './send' export interface ContactRouteResendConfig { /** Resend API key (read from env in the consuming app and passed here). */ apiKey: string /** Sender, e.g. `"Acme "`. Domain must be verified in Resend. */ from: string /** Recipient(s) of the notification email. */ to: string | string[] /** * Which field becomes the email Reply-To. Defaults to the first `email` * field in the schema. Set to `null` to disable. */ replyToField?: string | null } export interface ContactRouteTurnstileConfig { /** Turnstile secret key. */ secretKey: string /** * When `false`, a failed/missing token is tolerated (verify-if-present). * Default `true` (a valid token is required). */ required?: boolean } export interface ContactRouteHoneypotConfig { /** Disable the honeypot + time-trap entirely. Default enabled. */ enabled?: boolean /** Minimum fill time in ms. Default 2000. */ minFillMs?: number /** Maximum form age in ms. Default 30 minutes. */ maxAgeMs?: number } export interface ContactSubmissionContext { data: ContactData ip: string | null userAgent: string | null } export interface ContactRouteConfig { /** Field schema. Drives validation and the email layout. */ fields: ReadonlyArray /** Resend delivery config. */ resend: ContactRouteResendConfig /** Branding for the default email template. */ brand?: BrandConfig /** Subject line or builder for the default template. */ subject?: string | ((data: ContactData) => string) /** Lead paragraph for the default template. */ intro?: string /** * Provide your own email renderer instead of the built-in template. * Receives the validated data + request metadata. */ render?: (ctx: ContactSubmissionContext & { fields: ReadonlyArray }) => { subject: string html: string } /** Cloudflare Turnstile. Omit to skip captcha verification. */ turnstile?: ContactRouteTurnstileConfig /** Honeypot + time-trap. Enabled by default. */ honeypot?: ContactRouteHoneypotConfig /** Rate limiting. Pass `false` to disable, omit for in-memory defaults. */ rateLimit?: RateLimitConfig | false /** * Optional side effect run before the email is sent (persist to a DB / CRM). * If it throws, the request fails with `server_error` and no email is sent. */ onSubmit?: (ctx: ContactSubmissionContext) => void | Promise /** Attach IP + user-agent to the email and `onSubmit`. Default `true`. */ includeMeta?: boolean } /** A Web-standard POST handler — assign it to `export const POST` in a route. */ export type ContactRouteHandler = (request: Request) => Promise function jsonResponse(body: unknown, status: number): Response { return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' }, }) } function fail(error: ContactErrorCode, status: number): Response { return jsonResponse({ success: false, error }, status) } function asString(value: unknown): string | undefined { if (typeof value === 'string') return value if (value == null) return undefined return String(value) } /** * Build a framework-neutral contact POST handler. Works as a Next.js App * Router route handler (`export const POST = createContactRoute(...)`) or in * any runtime that speaks the Fetch `Request`/`Response` API. * * Pipeline (cheapest checks first): parse → honeypot → validate → rate-limit * → Turnstile → onSubmit → email. */ export function createContactRoute(config: ContactRouteConfig): ContactRouteHandler { const limiter = config.rateLimit === false ? null : createRateLimiter(config.rateLimit ?? {}) const replyToField = config.resend.replyToField === null ? undefined : (config.resend.replyToField ?? config.fields.find((field) => field.type === 'email')?.name) return async function POST(request: Request): Promise { try { let body: Record try { body = (await request.json()) as Record } catch { return fail('invalid_request', 400) } if (body == null || typeof body !== 'object') { return fail('invalid_request', 400) } // 1. Honeypot + time-trap (cheap, runs first). Silent success on failure // so bots can't tell they were caught. if (config.honeypot?.enabled !== false) { const honeypot = validateHoneypot( { honeypotValue: asString(body[HONEYPOT_FIELD_NAMES.honeypot]), renderedAt: body[HONEYPOT_FIELD_NAMES.renderedAt] as | number | string | undefined, }, { minFillMs: config.honeypot?.minFillMs, maxAgeMs: config.honeypot?.maxAgeMs } ) if (!honeypot.ok) { return jsonResponse({ success: true }, 200) } } // 2. Field validation. const validation = validateContact(config.fields, body) if (!validation.ok) { return fail(validation.code, 400) } const data = validation.data // 3. Rate limit per IP. const ip = getClientIp(request) if (limiter) { const limit = await limiter.check(ip) if (!limit.allowed) { return fail('rate_limited', 429) } } // 4. Cloudflare Turnstile. if (config.turnstile) { const verdict = await verifyTurnstileToken({ token: asString(body[TURNSTILE_TOKEN_FIELD]) ?? '', secretKey: config.turnstile.secretKey, remoteIp: ip === 'unknown' ? undefined : ip, }) if (!verdict.success && config.turnstile.required !== false) { return fail('captcha_failed', 400) } } const withMeta = config.includeMeta !== false const userAgent = withMeta ? request.headers.get('user-agent') : null const metaIp = withMeta ? (ip === 'unknown' ? null : ip) : null const ctx: ContactSubmissionContext = { data, ip: metaIp, userAgent } // 5. Persist hook (hard): if it throws, surface a server error. if (config.onSubmit) { await config.onSubmit(ctx) } // 6. Email. const replyTo = replyToField ? data[replyToField] || undefined : undefined const email = config.render ? config.render({ ...ctx, fields: config.fields }) : renderContactEmail({ fields: config.fields, data, brand: config.brand, subject: config.subject, intro: config.intro, meta: { ip: ctx.ip, userAgent: ctx.userAgent }, replyToEmail: replyTo, }) const send = await sendContactEmail( { apiKey: config.resend.apiKey, from: config.resend.from, to: config.resend.to, replyTo, }, email ) // Email is the only delivery channel and it failed → tell the client. // If an onSubmit persisted the lead, treat a mail hiccup as non-fatal. if (!send.success && !config.onSubmit) { return fail('server_error', 500) } return jsonResponse({ success: true }, 200) } catch (err) { console.error('[contact-form] route error:', err) return fail('server_error', 500) } } }