All files / lib rate-limit.ts

82.6% Statements 19/23
70% Branches 7/10
100% Functions 2/2
81.81% Lines 18/22

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                            1x     1x 1x     17x 17x                                   1x         17x   17x 17x     17x 8x 8x 8x       9x 3x       6x 6x           1x                    
/**
 * Simple in-memory rate limiting for API routes
 * @see JCN-25
 *
 * Note: This is a simple implementation that resets on deploy.
 * For production at scale, consider using Redis-based rate limiting via Upstash.
 */
 
interface RateLimitRecord {
  count: number;
  resetAt: number;
}
 
// In-memory store for rate limit tracking
const requests = new Map<string, RateLimitRecord>();
 
// Clean up expired entries periodically (every 5 minutes)
const CLEANUP_INTERVAL = 5 * 60 * 1000;
let lastCleanup = Date.now();
 
function cleanup() {
  const now = Date.now();
  Eif (now - lastCleanup < CLEANUP_INTERVAL) return;
 
  lastCleanup = now;
  for (const [key, record] of requests.entries()) {
    if (now > record.resetAt) {
      requests.delete(key);
    }
  }
}
 
/**
 * Check if a request is within rate limits
 *
 * @param key - Unique identifier for the rate limit (e.g., userId + endpoint)
 * @param limit - Maximum number of requests allowed
 * @param windowMs - Time window in milliseconds
 * @returns true if within limits, false if rate limited
 */
export function checkRateLimit(
  key: string,
  limit: number,
  windowMs: number
): { allowed: boolean; remaining: number; resetAt: number } {
  cleanup();
 
  const now = Date.now();
  const record = requests.get(key);
 
  // First request or window expired
  if (!record || now > record.resetAt) {
    const newRecord = { count: 1, resetAt: now + windowMs };
    requests.set(key, newRecord);
    return { allowed: true, remaining: limit - 1, resetAt: newRecord.resetAt };
  }
 
  // Within window - check if limit exceeded
  if (record.count >= limit) {
    return { allowed: false, remaining: 0, resetAt: record.resetAt };
  }
 
  // Increment count
  record.count++;
  return { allowed: true, remaining: limit - record.count, resetAt: record.resetAt };
}
 
/**
 * Rate limit configurations for different endpoints
 */
export const RATE_LIMITS = {
  // Invitations: 10 per hour per user
  invitation: { limit: 10, windowMs: 60 * 60 * 1000 },
 
  // Password reset: 5 per hour per email
  passwordReset: { limit: 5, windowMs: 60 * 60 * 1000 },
 
  // Email verification resend: 5 per hour per user
  resendVerification: { limit: 5, windowMs: 60 * 60 * 1000 },
};