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 | 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 8x 8x 8x 8x 8x 8x 8x | /**
* Redis-backed Rate Limiting (Upstash)
*
* Sliding window rate limiter using @upstash/ratelimit.
* Falls back to DB-based rate limiting if Redis is unavailable.
*/
import { Ratelimit } from '@upstash/ratelimit';
import { getRedisClient } from './client';
import { RATE_LIMIT_CONFIG } from '@/lib/auth/rate-limit';
type ConfigKey = keyof typeof RATE_LIMIT_CONFIG;
// Cache ratelimit instances per config key
const limiters = new Map<ConfigKey, Ratelimit>();
/**
* Get or create a Ratelimit instance for a given config key.
* Returns null if Redis is not available.
*/
export function getRateLimiter(configKey: ConfigKey): Ratelimit | null {
const redis = getRedisClient();
if (!redis) return null;
if (limiters.has(configKey)) {
return limiters.get(configKey)!;
}
const config = RATE_LIMIT_CONFIG[configKey];
const limiter = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(config.maxAttempts, `${config.windowMinutes} m`),
prefix: `ratelimit:${configKey}`,
analytics: true,
});
limiters.set(configKey, limiter);
return limiter;
}
export interface RedisRateLimitResult {
allowed: boolean;
remaining: number;
resetAt: Date;
}
/**
* Check rate limit via Redis.
* Returns null if Redis is unavailable (caller should fall back to DB).
*/
export async function checkRedisRateLimit(
identifier: string,
configKey: ConfigKey
): Promise<RedisRateLimitResult | null> {
const limiter = getRateLimiter(configKey);
if (!limiter) return null;
try {
const result = await limiter.limit(identifier);
return {
allowed: result.success,
remaining: result.remaining,
resetAt: new Date(result.reset),
};
} catch (error) {
console.error('Redis rate limit error, falling back to DB:', error);
return null;
}
}
/**
* Reset rate limit for an identifier (e.g., after successful auth).
* Returns false if Redis is unavailable.
*/
export async function resetRedisRateLimit(
identifier: string,
configKey: ConfigKey
): Promise<boolean> {
const redis = getRedisClient();
if (!redis) return false;
try {
// Delete the sliding window keys for this identifier
const prefix = `ratelimit:${configKey}`;
const keys = await redis.keys(`${prefix}:${identifier}*`);
if (keys.length > 0) {
await redis.del(...keys);
}
return true;
} catch (error) {
console.error('Redis rate limit reset error:', error);
return false;
}
}
|