|
| 1 | +import { Ratelimit } from "@upstash/ratelimit"; |
| 2 | +import { env } from "~/env.server"; |
| 3 | +import { createRedisRateLimitClient, RateLimiter } from "~/services/rateLimiter.server"; |
| 4 | +import { singleton } from "~/utils/singleton"; |
| 5 | + |
| 6 | +export const mfaRateLimiter = singleton("mfaRateLimiter", initializeMfaRateLimiter); |
| 7 | + |
| 8 | +function initializeMfaRateLimiter() { |
| 9 | + const redisClient = createRedisRateLimitClient({ |
| 10 | + port: env.RATE_LIMIT_REDIS_PORT, |
| 11 | + host: env.RATE_LIMIT_REDIS_HOST, |
| 12 | + username: env.RATE_LIMIT_REDIS_USERNAME, |
| 13 | + password: env.RATE_LIMIT_REDIS_PASSWORD, |
| 14 | + tlsDisabled: env.RATE_LIMIT_REDIS_TLS_DISABLED === "true", |
| 15 | + clusterMode: env.RATE_LIMIT_REDIS_CLUSTER_MODE_ENABLED === "1", |
| 16 | + }); |
| 17 | + |
| 18 | + return new RateLimiter({ |
| 19 | + redisClient, |
| 20 | + keyPrefix: "mfa:validation", |
| 21 | + limiter: Ratelimit.slidingWindow(10, "1 m"), // 10 attempts per minute |
| 22 | + logSuccess: false, // Don't log successful attempts for privacy |
| 23 | + logFailure: true, // Log rate limit violations for security monitoring |
| 24 | + }); |
| 25 | +} |
| 26 | + |
| 27 | +export class MfaRateLimitError extends Error { |
| 28 | + public readonly retryAfter: number; |
| 29 | + |
| 30 | + constructor(retryAfter: number) { |
| 31 | + super(`MFA validation rate limit exceeded.`); |
| 32 | + this.retryAfter = retryAfter; |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +/** |
| 37 | + * Check if the user can attempt MFA validation |
| 38 | + * @param userId - The user ID to rate limit |
| 39 | + * @throws {MfaRateLimitError} If rate limit is exceeded |
| 40 | + */ |
| 41 | +export async function checkMfaRateLimit(userId: string): Promise<void> { |
| 42 | + const result = await mfaRateLimiter.limit(userId); |
| 43 | + |
| 44 | + if (!result.success) { |
| 45 | + const retryAfter = new Date(result.reset).getTime() - Date.now(); |
| 46 | + throw new MfaRateLimitError(retryAfter); |
| 47 | + } |
| 48 | +} |
0 commit comments