/** * Findings: S-03, S-04 * * Sliding-window limits keyed on IP *and* on the submitted email (hashed), so a bot * rotating IPs still can't hammer one victim's inbox, and one IP can't spray many emails. * * Production uses Upstash Redis (works on serverless/edge where in-memory state is per * instance). Local development falls back to an in-process map. */ import { Ratelimit } from "@upstash/ratelimit"; import { Redis } from "@upstash/redis"; type Decision = { success: boolean; retryAfterSeconds: number }; type Limiter = { limit(key: string): Promise }; type Window = `${number} ${"s" | "m" | "h" | "d"}`; function upstash(prefix: string, tokens: number, window: Window): Limiter { const rl = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(tokens, window), prefix: `rl:${prefix}`, analytics: false, }); return { async limit(key) { const r = await rl.limit(key); return { success: r.success, retryAfterSeconds: Math.max(1, Math.ceil((r.reset - Date.now()) / 1000)) }; }, }; } function memory(tokens: number, windowMs: number): Limiter { const hits = new Map(); return { async limit(key) { const now = Date.now(); const recent = (hits.get(key) ?? []).filter((t) => now - t < windowMs); const success = recent.length < tokens; if (success) recent.push(now); hits.set(key, recent); const oldest = recent[0] ?? now; return { success, retryAfterSeconds: Math.max(1, Math.ceil((oldest + windowMs - now) / 1000)) }; }, }; } const useRedis = Boolean(process.env.UPSTASH_REDIS_REST_URL); const make = (prefix: string, tokens: number, window: Window, windowMs: number) => useRedis ? upstash(prefix, tokens, window) : memory(tokens, windowMs); /** Limits per surface. Tune from real traffic; these are deliberately conservative. */ export const limiters = { applicationByIp: make("app-ip", 5, "1 h", 3_600_000), applicationByEmail: make("app-email", 3, "1 d", 86_400_000), contactByIp: make("contact-ip", 5, "10 m", 600_000), newsletterByIp: make("nl-ip", 3, "1 h", 3_600_000), // Caps outbound acknowledgement mail to any single address, whichever form triggered it. outboundToRecipient: make("mail-to", 2, "1 d", 86_400_000), }; /** * Client IP as seen by the platform. On Vercel `x-forwarded-for` is set by the edge and the * left-most value is the client; on other hosts, only trust it behind a known proxy. */ export function clientIp(req: Request): string { return req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || req.headers.get("x-real-ip") || "unknown"; }