136 lines
5.0 KiB
TypeScript
136 lines
5.0 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 { store } = getLimiters();
|
|
const [perIpCount, perUserCount] = await Promise.all([
|
|
peekCount(store, `rl:fixed:mfa-challenge:${key.perIp}`),
|
|
peekCount(store, `rl:fixed:mfa-challenge-user:${key.userId}`),
|
|
]);
|
|
// Block as soon as either bound is reached. The per-user window is longer, so
|
|
// report its reset when it is the binding constraint.
|
|
if (perUserCount >= MFA_CHALLENGE_USER_LIMIT) {
|
|
return { allowed: false, retryAfterSeconds: MFA_CHALLENGE_USER_WINDOW_SECONDS, resetAt: new Date(now.getTime() + MFA_CHALLENGE_USER_WINDOW_SECONDS * 1000) };
|
|
}
|
|
if (perIpCount >= MFA_CHALLENGE_LIMIT) {
|
|
return { allowed: false, retryAfterSeconds: MFA_CHALLENGE_WINDOW_SECONDS, resetAt: new Date(now.getTime() + MFA_CHALLENGE_WINDOW_SECONDS * 1000) };
|
|
}
|
|
return {
|
|
allowed: true,
|
|
remaining: Math.min(MFA_CHALLENGE_LIMIT - perIpCount, MFA_CHALLENGE_USER_LIMIT - perUserCount),
|
|
resetAt: new Date(now.getTime() + MFA_CHALLENGE_WINDOW_SECONDS * 1000),
|
|
};
|
|
}
|
|
|
|
async function peekCount(store: SharedStore, suffix: string): Promise<number> {
|
|
const raw = await store.get(suffix);
|
|
return raw === null ? 0 : Number.parseInt(raw, 10) || 0;
|
|
}
|
|
|
|
export async function recordFailedMfaChallengeAttempt(key: MfaChallengeRateLimitKey, _now: Date = new Date()): Promise<void> {
|
|
const { perIp, perUser } = getLimiters();
|
|
await Promise.all([perIp.consume(key.perIp), perUser.consume(key.userId)]);
|
|
}
|
|
|
|
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();
|
|
}
|