/** * Fixed-window per-key rate limiter with two backends: * * - **Upstash Redis** when `redis` config is supplied (durable, shared across * serverless instances). `@upstash/redis` is an optional peer dependency, * imported lazily so projects that don't use it never need to install it. * - **In-memory** otherwise (per-process). Fine for low-volume contact forms * on a single instance; on multi-instance serverless each instance keeps its * own window, so the effective limit is multiplied by the instance count. */ export interface RateLimitRedisConfig { url: string token: string } export interface RateLimitConfig { /** Max submissions per window per key. Default 5. */ maxAttempts?: number /** Window length in ms. Default 1 hour. */ windowMs?: number /** Namespace for keys. Default `'contact:'`. */ keyPrefix?: string /** Supply to use Upstash Redis; omit for the in-memory backend. */ redis?: RateLimitRedisConfig } export interface RateLimitResult { allowed: boolean remaining: number /** Ms until the window resets (only when `allowed` is false). */ retryAfterMs?: number } export interface RateLimiter { check(key: string): Promise } interface Entry { count: number resetAt: number } const DEFAULTS = { maxAttempts: 5, windowMs: 60 * 60 * 1000, keyPrefix: 'contact:', } as const /** Build a rate limiter. Picks the Upstash backend when `config.redis` is set. */ export function createRateLimiter(config: RateLimitConfig = {}): RateLimiter { const maxAttempts = config.maxAttempts ?? DEFAULTS.maxAttempts const windowMs = config.windowMs ?? DEFAULTS.windowMs const prefix = config.keyPrefix ?? DEFAULTS.keyPrefix return config.redis ? upstashLimiter(config.redis, prefix, maxAttempts, windowMs) : memoryLimiter(prefix, maxAttempts, windowMs) } function decide(entry: Entry | null, now: number, max: number, windowMs: number): { result: RateLimitResult next: Entry } { if (!entry || now > entry.resetAt) { const next: Entry = { count: 1, resetAt: now + windowMs } return { result: { allowed: true, remaining: max - 1 }, next } } if (entry.count >= max) { return { result: { allowed: false, remaining: 0, retryAfterMs: entry.resetAt - now }, next: entry, } } const next: Entry = { count: entry.count + 1, resetAt: entry.resetAt } return { result: { allowed: true, remaining: max - next.count }, next } } function memoryLimiter(prefix: string, max: number, windowMs: number): RateLimiter { const store = new Map() return { async check(key: string): Promise { const now = Date.now() const k = `${prefix}${key}` const current = store.get(k) ?? null const { result, next } = decide(current, now, max, windowMs) if (!result.allowed) return result store.set(k, next) // Opportunistic cleanup so the map can't grow unbounded. if (store.size > 10_000) { for (const [mapKey, entry] of store) { if (now > entry.resetAt) store.delete(mapKey) } } return result }, } } function upstashLimiter( redisConfig: RateLimitRedisConfig, prefix: string, max: number, windowMs: number ): RateLimiter { let clientPromise: Promise | null = null function getClient(): Promise { if (!clientPromise) { clientPromise = import('@upstash/redis').then( (mod) => new mod.Redis({ url: redisConfig.url, token: redisConfig.token }) ) } return clientPromise } const rateLimitKey = (key: string) => `${prefix}ratelimit:${key}` return { async check(key: string): Promise { const redis = await getClient() const now = Date.now() const redisKey = rateLimitKey(key) const raw = await redis.get(redisKey) let entry: Entry | null = null if (raw) { entry = typeof raw === 'string' ? (JSON.parse(raw) as Entry) : (raw as Entry) if (now > entry.resetAt) entry = null } const { result, next } = decide(entry, now, max, windowMs) if (!result.allowed) return result const ttlSeconds = Math.max(Math.ceil((next.resetAt - now) / 1000), 1) await redis.set(redisKey, JSON.stringify(next), { ex: ttlSeconds }) return result }, } }