All files / middleware rate-limit.middleware.ts

100% Statements 68/68
97.67% Branches 42/43
100% Functions 5/5
100% Lines 66/66

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287                                  6x     6x       130x             2x 10000x           23x 2x 2x 10000x 5000x       2x 1x 1x 1x 101x 100x 100x                                                   76x     76x   76x   163x 23x       163x   163x     163x       163x       163x 163x 163x     163x     163x     163x 2x 2x       163x 8x 8x 7x 2x   2x               163x   130x       130x     130x 6x 6x                 33x   13x 13x                                       20x 20x     20x 2x 2x                       150x       150x 150x       150x           150x               6x                     6x                   6x                     6x                   6x                   6x                     6x          
// Rate Limiting Middleware for Cloudflare Workers
// Uses L1 (in-memory) + L2 (KV) dual-layer storage for cross-isolate consistency
import type { MiddlewareHandler } from "hono";
 
type RateLimitConfig = {
	windowMs: number; // Time window in milliseconds
	max: number; // Max requests per window per IP in production
	devMax?: number; // Higher limit for local/dev to accommodate parallel E2E tests
	message?: string;
};
 
type RateLimitRecord = {
	count: number;
	resetTime: number; // Unix timestamp in ms
};
 
// L1: In-memory store (per worker isolate, fast path)
const l1Store = new Map<string, RateLimitRecord>();
 
// Max L1 entries before pruning oldest
const MAX_L1_SIZE = 5000;
 
/** Clear all rate limit state (for tests) */
export function resetRateLimitStore() {
	l1Store.clear();
}
 
/** Populate L1 store with entries for testing (for tests only) */
export function _populateL1StoreForTest(
	entries: Array<{ key: string; count: number; resetTime: number }>,
) {
	for (const e of entries) {
		l1Store.set(e.key, { count: e.count, resetTime: e.resetTime });
	}
}
 
// Evict expired L1 entries when the map exceeds MAX_L1_SIZE
function pruneL1() {
	if (l1Store.size < MAX_L1_SIZE) return;
	const now = Date.now();
	for (const [key, record] of l1Store.entries()) {
		if (now > record.resetTime) {
			l1Store.delete(key);
		}
	}
	// If still too large after expiry cleanup, drop oldest entries
	if (l1Store.size >= MAX_L1_SIZE) {
		const excess = l1Store.size - MAX_L1_SIZE + 100; // drop 100 extra for headroom
		let dropped = 0;
		for (const key of l1Store.keys()) {
			if (dropped >= excess) break;
			l1Store.delete(key);
			dropped++;
		}
	}
}
 
/**
 * Rate limiting middleware using L1 (in-memory) + L2 (Cloudflare KV).
 *
 * L1 provides instant (<1ms) blocking within a single isolate.
 * L2 provides cross-isolate consistency via KV (~10ms reads).
 *
 * On each request:
 * 1. Check L1 for a valid record — if found and over limit, block immediately.
 * 2. If L1 misses or is stale, check L2 (KV) for a shared record.
 * 3. Increment count in both L1 and L2.
 *
 * Race condition note: KV doesn't support atomic increments, so under high
 * concurrency a few extra requests may slip through. This is acceptable for
 * our rate limits (10-100 req/min).
 */
export function rateLimit(config: RateLimitConfig): MiddlewareHandler {
	const {
		windowMs,
		max,
		devMax,
		message = "Too many requests, please try again later",
	} = config;
 
	// KV TTL must be at least 60s per Cloudflare's minimum
	const kvTtlSeconds = Math.max(60, Math.ceil(windowMs / 1000));
 
	return async (c, next) => {
		// Prune L1 occasionally (1% chance per request)
		if (Math.random() < 0.01) {
			pruneL1();
		}
 
		// Use higher limit in local/dev to accommodate parallel E2E test workers
		const env = c.env as CloudflareBindings & { ENVIRONMENT?: string };
		const isLocalDev =
			!env.ENVIRONMENT ||
			env.ENVIRONMENT === "local" ||
			env.ENVIRONMENT === "dev";
		const effectiveMax = isLocalDev && devMax !== undefined ? devMax : max;
 
		// Get client IP from Cloudflare headers
		const ip =
			c.req.header("cf-connecting-ip") ||
			c.req.header("x-forwarded-for")?.split(",")[0]?.trim() ||
			"unknown";
 
		const key = `${ip}:${c.req.path}`;
		const kvKey = `rl:${key}`;
		const now = Date.now();
 
		// Resolve KV binding (optional — degrades to L1-only without it)
		const kv = (c.env as CloudflareBindings).KV_CACHE;
 
		// --- Read current record ---
		let record = l1Store.get(key) ?? null;
 
		// If L1 record is expired, discard it
		if (record && now > record.resetTime) {
			l1Store.delete(key);
			record = null;
		}
 
		// If no L1 record, try L2
		if (!record && kv) {
			try {
				const kvRecord = await kv.get<RateLimitRecord>(kvKey, "json");
				if (kvRecord && now <= kvRecord.resetTime) {
					record = kvRecord;
					// Backfill L1
					l1Store.set(key, { ...record });
				}
			} catch {
				// KV read failure is non-fatal — fall through to create new record
			}
		}
 
		// --- Evaluate ---
		if (!record) {
			// First request in this window — create new record
			const newRecord: RateLimitRecord = {
				count: 1,
				resetTime: now + windowMs,
			};
			l1Store.set(key, newRecord);
 
			// Write to KV in background
			if (kv) {
				try {
					c.executionCtx.waitUntil(
						kv.put(kvKey, JSON.stringify(newRecord), {
							expirationTtl: kvTtlSeconds,
						}),
					);
				} catch {
					// Non-fatal
				}
			}
		} else if (record.count >= effectiveMax) {
			// Rate limit exceeded
			const retryAfter = Math.ceil((record.resetTime - now) / 1000);
			return c.json(
				{
					success: false,
					error: {
						code: "RATE_LIMIT_EXCEEDED",
						message,
					},
				},
				429,
				{
					"Retry-After": String(retryAfter),
					"X-RateLimit-Limit": String(effectiveMax),
					"X-RateLimit-Remaining": "0",
					"X-RateLimit-Reset": String(
						Math.ceil(record.resetTime / 1000),
					),
				},
			);
		} else {
			// Increment count
			record.count++;
			l1Store.set(key, record);
 
			// Update KV in background
			if (kv) {
				try {
					c.executionCtx.waitUntil(
						kv.put(kvKey, JSON.stringify(record), {
							expirationTtl: kvTtlSeconds,
						}),
					);
				} catch {
					// Non-fatal
				}
			}
		}
 
		// Add rate limit headers to response
		const currentRecord = l1Store.get(key);
		/* v8 ignore start -- V8 artifact: key was just set above, always exists */
		if (currentRecord) {
		/* v8 ignore stop */
			c.header("X-RateLimit-Limit", String(effectiveMax));
			c.header(
				"X-RateLimit-Remaining",
				String(Math.max(0, effectiveMax - currentRecord.count)),
			);
			c.header(
				"X-RateLimit-Reset",
				String(Math.ceil(currentRecord.resetTime / 1000)),
			);
		}
 
		await next();
	};
}
 
/**
 * Strict rate limiter for auth endpoints.
 * Production: 10/min per IP. Local/dev: 200/min to support parallel E2E test workers.
 */
export const authRateLimit = rateLimit({
	windowMs: 60 * 1000, // 1 minute
	max: 10,
	devMax: 200, // parallel E2E workers share "unknown" IP in local dev
	message: "Too many authentication attempts, please try again in a minute",
});
 
/**
 * General API rate limiter
 * 100 requests per minute per IP
 */
export const apiRateLimit = rateLimit({
	windowMs: 60 * 1000, // 1 minute
	max: 100,
	message: "Too many requests, please slow down",
});
 
/**
 * AI draft generation rate limiter
 * 10 requests per hour per user (resource-intensive operation)
 */
export const aiDraftRateLimit = rateLimit({
	windowMs: 60 * 60 * 1000, // 1 hour
	max: 10,
	message:
		"Too many AI draft generation requests. Please try again in an hour.",
});
 
/**
 * AI rewrite rate limiter
 * 20 requests per hour per user (moderately intensive operation)
 */
export const aiRewriteRateLimit = rateLimit({
	windowMs: 60 * 60 * 1000, // 1 hour
	max: 20,
	message: "Too many AI rewrite requests. Please try again in an hour.",
});
 
/**
 * AI metadata generation rate limiter
 * 30 requests per hour per user (lightweight operation)
 */
export const aiMetaRateLimit = rateLimit({
	windowMs: 60 * 60 * 1000, // 1 hour
	max: 30,
	message: "Too many AI metadata requests. Please try again in an hour.",
});
 
/**
 * AI topic suggestion rate limiter
 * 15 requests per hour per user
 */
export const aiTopicRateLimit = rateLimit({
	windowMs: 60 * 60 * 1000, // 1 hour
	max: 15,
	message:
		"Too many AI topic suggestion requests. Please try again in an hour.",
});
 
/**
 * Resource creation rate limiter
 * 30 creates per minute per IP (projects, leads, etc.)
 */
export const resourceCreationRateLimit = rateLimit({
	windowMs: 60 * 1000, // 1 minute
	max: 30,
	message: "Too many creation requests, please slow down",
});