Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/utils/auth/mfa/challenge-rate-limit.server.ts
T

156 lines
5.3 KiB
TypeScript

import {
createFixedWindowRateLimiter,
type FixedWindowRateLimiter,
type SharedStore,
} from "@hivegrid/shared-store";
import { getSharedStore } from "~/shared-store.server";
import { getTrustedClientIp } from "~/utils/server/IpUtils";
// Per (user, IP) throttle. The IP is derived from a trusted, proxy-set header
// so it cannot be rotated by forging X-Forwarded-For.
const MFA_CHALLENGE_LIMIT = 5;
const MFA_CHALLENGE_WINDOW_SECONDS = 5 * 60;
// Authoritative per-user throttle, independent of IP. This is what actually
// bounds a brute-force attack: the victim's userId is fixed, so an attacker
// cannot escape it by changing IPs. Generous enough that a real user retrying
// their TOTP a few times never hits it, tight enough that guessing a 6-digit
// code stays astronomically unlikely.
const MFA_CHALLENGE_USER_LIMIT = 15;
const MFA_CHALLENGE_USER_WINDOW_SECONDS = 15 * 60;
export type MfaChallengeRateLimitKey = {
/** Per-user key, independent of IP — the authoritative brute-force bound. */
userId: string;
/** Per (user, trusted-IP) key for finer-grained throttling. */
perIp: string;
};
export type MfaChallengeRateLimitResult =
| { allowed: true; remaining: number; resetAt: Date }
| { allowed: false; retryAfterSeconds: number; resetAt: Date };
type Limiters = {
perIp: FixedWindowRateLimiter;
perUser: FixedWindowRateLimiter;
store: SharedStore;
};
let cached: Limiters | null = null;
let storeFactory: () => SharedStore = () => getSharedStore();
function getLimiters(): Limiters {
if (cached !== null) return cached;
const store = storeFactory();
cached = {
store,
perIp: createFixedWindowRateLimiter({
store,
prefix: "mfa-challenge",
windowSeconds: MFA_CHALLENGE_WINDOW_SECONDS,
max: MFA_CHALLENGE_LIMIT,
}),
perUser: createFixedWindowRateLimiter({
store,
prefix: "mfa-challenge-user",
windowSeconds: MFA_CHALLENGE_USER_WINDOW_SECONDS,
max: MFA_CHALLENGE_USER_LIMIT,
}),
};
return cached;
}
export function mfaChallengeRateLimitKey(request: Request, userId: string): MfaChallengeRateLimitKey {
const ip = getTrustedClientIp(request);
return { userId, perIp: `${userId}:${ip}` };
}
export async function checkMfaChallengeRateLimit(key: MfaChallengeRateLimitKey, now: Date = new Date()): Promise<MfaChallengeRateLimitResult> {
const { perIp, perUser, store } = getLimiters();
// Reserve before TOTP/recovery-code verification. Read-then-consume permits
// every request in a parallel burst to observe the same old count.
const perIpReservation = await reserveWithCorruptionRecovery(
perIp,
store,
key.perIp,
`rl:fixed:mfa-challenge:${key.perIp}`,
);
if (!perIpReservation.allowed) {
return { allowed: false, retryAfterSeconds: MFA_CHALLENGE_WINDOW_SECONDS, resetAt: new Date(now.getTime() + MFA_CHALLENGE_WINDOW_SECONDS * 1000) };
}
const perUserReservation = await reserveWithCorruptionRecovery(
perUser,
store,
key.userId,
`rl:fixed:mfa-challenge-user:${key.userId}`,
);
if (!perUserReservation.allowed) {
return { allowed: false, retryAfterSeconds: MFA_CHALLENGE_USER_WINDOW_SECONDS, resetAt: new Date(now.getTime() + MFA_CHALLENGE_USER_WINDOW_SECONDS * 1000) };
}
return {
allowed: true,
remaining: Math.min(perIpReservation.remaining, perUserReservation.remaining),
resetAt: new Date(now.getTime() + MFA_CHALLENGE_WINDOW_SECONDS * 1000),
};
}
export async function recordFailedMfaChallengeAttempt(key: MfaChallengeRateLimitKey, _now: Date = new Date()): Promise<void> {
// checkMfaChallengeRateLimit already reserved this attempt before verification.
void key;
void _now;
}
async function reserveWithCorruptionRecovery(
limiter: FixedWindowRateLimiter,
store: SharedStore,
key: string,
storageKey: string,
) {
try {
return await limiter.consume(key);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (!/non-numeric|not an integer/i.test(message)) throw error;
await store.del(storageKey);
return limiter.consume(key);
}
}
export async function resetMfaChallengeRateLimit(key: MfaChallengeRateLimitKey): Promise<void> {
const { perIp, perUser } = getLimiters();
await Promise.all([perIp.reset(key.perIp), perUser.reset(key.userId)]);
}
export async function resetMfaChallengeRateLimiterForTests(): Promise<void> {
const previous = cached;
cached = null;
if (previous) {
try {
for await (const fullKey of previous.store.adapter.scan(
// Matches both the per-IP (mfa-challenge:*) and per-user
// (mfa-challenge-user:*) buckets.
`shared-store:${previous.store.namespace}:rl:fixed:mfa-challenge*`,
)) {
const prefix = `shared-store:${previous.store.namespace}:`;
if (fullKey.startsWith(prefix)) {
await previous.store.del(fullKey.slice(prefix.length));
}
}
} catch {
// Best-effort; isolated tests inject a fresh store via the seam.
}
}
}
/** Test seam: inject a custom SharedStore. */
export function __setMfaChallengeRateLimitStoreForTests(store: SharedStore): void {
cached = null;
storeFactory = () => store;
}
/** Test seam: revert to the default web shared-store. */
export function __resetMfaChallengeRateLimitStoreForTests(): void {
cached = null;
storeFactory = () => getSharedStore();
}