All files / middleware rate-limit.middleware.ts

98.79% Statements 82/83
91.52% Branches 54/59
100% Functions 10/10
100% Lines 76/76

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 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346                                          6x     6x       135x             2x 10000x           21x 2x 2x 10000x 5000x       2x 1x 1x 1x 101x 100x 100x                                                         64x     64x   64x   152x 21x       152x   152x     152x       152x       152x 152x 152x     152x     152x     152x 2x 2x       152x 8x 8x 7x 2x   2x               152x   129x       129x     129x 6x 6x                 23x   12x 12x                                                       11x 11x       140x       140x 140x       140x           140x                                         18x 18x 115x 115x         114x 114x     114x     115x   115x 114x 3x         111x             13x               6x                                     101x                 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;
	// When set, key on `${ip}:${keyPrefix}` instead of `${ip}:${c.req.path}`.
	// Use for aggregate scrape protection across a route group with path params
	// (e.g. marketplace) where per-path bucketing would let attackers iterate IDs.
	keyPrefix?: 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 L1. KV is written ONLY when a new window is created,
 *    not on every increment — see the else-branch comment for the cost rationale.
 *
 * Race condition note: KV doesn't support atomic increments, so under high
 * concurrency a few extra requests may slip through. Combined with L1-only
 * increments (KV seeded once per window), cross-isolate counts under-count
 * slightly. 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",
		keyPrefix,
	} = 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}:${keyPrefix ?? 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 in L1 only.
			//
			// Deliberately NO KV write here. KV bills per write ($5/M, 10x reads)
			// and only durably persists 1 write/sec per key — writing on every
			// request inside a window is pure cost with no benefit. We seed the
			// cross-isolate window once on creation (above); subsequent increments
			// stay L1-local. Cross-isolate counts under-count slightly within a
			// window, which is acceptable for 10-100 req/min abuse limits (see the
			// approximate-counting note in the function doc).
			record.count++;
			l1Store.set(key, record);
		}
 
		// 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();
	};
}
 
/**
 * Rate limiter backed by Cloudflare's native Rate Limiting binding.
 *
 * Counters live at the edge (per-colo) — zero KV, zero DB, zero per-op billing.
 * Limit + period are fixed in wrangler.jsonc (`ratelimits`), not here.
 *
 * No binding present (local dev / unit tests) → skip limiting. The native limiter
 * is deployed-only; locally there's nothing to abuse and E2E workers would
 * otherwise trip a shared-IP bucket.
 *
 * ponytail: per-colo counts, not global. Fine for abuse limits; if a single
 * attacker spread across colos ever matters, move to a Durable Object counter.
 */
function cfRateLimit(
	pick: (env: CloudflareBindings) => RateLimit | undefined,
	opts: { keyPrefix?: string; message?: string } = {},
): MiddlewareHandler {
	const message = opts.message ?? "Too many requests, please try again later";
	return async (c, next) => {
		const limiter = pick(c.env as CloudflareBindings);
		if (!limiter) return next();
 
		// Skip in local dev: Wrangler simulates the native Rate Limiting binding,
		// but all local requests share IP key "unknown", so parallel E2E workers
		// throttle each other. Deployed dev/preview/prod use real per-IP edge buckets.
		const cfEnv = c.env as CloudflareBindings & { ENVIRONMENT?: string };
		Iif (!cfEnv.ENVIRONMENT || cfEnv.ENVIRONMENT === "local") return next();
 
		const ip =
			c.req.header("cf-connecting-ip") ||
			c.req.header("x-forwarded-for")?.split(",")[0]?.trim() ||
			"unknown";
		const key = `${ip}:${opts.keyPrefix ?? c.req.path}`;
 
		const { success } = await limiter.limit({ key });
		if (!success) {
			return c.json(
				{ success: false, error: { code: "RATE_LIMIT_EXCEEDED", message } },
				429,
			);
		}
		await next();
	};
}
 
/**
 * Strict rate limiter for auth endpoints. 10/min per IP (RL_AUTH binding).
 */
export const authRateLimit = cfRateLimit((e) => e.RL_AUTH, {
	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,
	devMax: 1000, // parallel E2E workers share "unknown" IP in local/dev
	message: "Too many requests, please slow down",
});
 
/**
 * Marketplace API rate limiter (RL_MARKETPLACE binding) — aggregates across the
 * whole /api/marketplace route group via a fixed keyPrefix so per-path-param URLs
 * (e.g. /pros/:id, /projects/:id, /blogs/:slug) share one bucket per IP. Prevents
 * scraping by iterating IDs through endpoints that miss the edge cache.
 * 100 req/min per IP (configured in wrangler.jsonc).
 *
 * NOTE: NOT currently mounted (removed from routes/marketplace/index.ts).
 * Keying on cf-connecting-ip throttled first-party SSR (the API is fetched
 * worker-to-worker, so the visitor IP is erased) rather than real abusers.
 * Kept here for easy re-enable; see the explanation in marketplace/index.ts.
 */
export const marketplaceRateLimit = cfRateLimit((e) => e.RL_MARKETPLACE, {
	keyPrefix: "marketplace",
	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 (RL_RESOURCE binding).
 * 30 creates per minute per IP (projects, leads, etc.) — keyed per IP:path.
 */
export const resourceCreationRateLimit = cfRateLimit((e) => e.RL_RESOURCE, {
	message: "Too many creation requests, please slow down",
});