77 lines
2.3 KiB
TypeScript
77 lines
2.3 KiB
TypeScript
import { createFixedWindowRateLimiter, type FixedWindowRateLimiter, type SharedStore } from "@hivegrid/shared-store";
|
|
import { getSharedStore } from "~/shared-store.server";
|
|
|
|
const TOKEN_ATTEMPT_LIMIT = 5;
|
|
const TOKEN_WINDOW_SECONDS = 30 * 60;
|
|
const IP_ATTEMPT_LIMIT = 30;
|
|
const IP_WINDOW_SECONDS = 15 * 60;
|
|
|
|
type Limiters = {
|
|
readonly perToken: FixedWindowRateLimiter;
|
|
readonly perIp: FixedWindowRateLimiter;
|
|
};
|
|
|
|
export type SignatureOtpRateLimitDecision =
|
|
| { readonly allowed: true; readonly remaining: number }
|
|
| { readonly allowed: false; readonly retryAfterSeconds: number };
|
|
|
|
let cached: Limiters | null = null;
|
|
let storeFactory: () => SharedStore = () => getSharedStore();
|
|
|
|
function getLimiters(): Limiters {
|
|
if (cached) return cached;
|
|
const store = storeFactory();
|
|
cached = {
|
|
perToken: createFixedWindowRateLimiter({
|
|
store,
|
|
prefix: "signature-otp-token",
|
|
max: TOKEN_ATTEMPT_LIMIT,
|
|
windowSeconds: TOKEN_WINDOW_SECONDS,
|
|
}),
|
|
perIp: createFixedWindowRateLimiter({
|
|
store,
|
|
prefix: "signature-otp-ip",
|
|
max: IP_ATTEMPT_LIMIT,
|
|
windowSeconds: IP_WINDOW_SECONDS,
|
|
}),
|
|
};
|
|
return cached;
|
|
}
|
|
|
|
/**
|
|
* Reserves an OTP attempt before verification. The token bucket is the
|
|
* authoritative brute-force bound; the trusted-IP bucket additionally slows
|
|
* broad attacks across many leaked links. Store failures propagate so the
|
|
* signing endpoint fails closed instead of silently losing its protection.
|
|
*/
|
|
export async function reserveSignatureOtpAttempt(input: {
|
|
readonly tokenHash: string;
|
|
readonly trustedClientIp: string;
|
|
}): Promise<SignatureOtpRateLimitDecision> {
|
|
const { perToken, perIp } = getLimiters();
|
|
const tokenDecision = await perToken.consume(input.tokenHash);
|
|
if (!tokenDecision.allowed) {
|
|
return { allowed: false, retryAfterSeconds: TOKEN_WINDOW_SECONDS };
|
|
}
|
|
|
|
const ipDecision = await perIp.consume(input.trustedClientIp);
|
|
if (!ipDecision.allowed) {
|
|
return { allowed: false, retryAfterSeconds: IP_WINDOW_SECONDS };
|
|
}
|
|
|
|
return {
|
|
allowed: true,
|
|
remaining: Math.min(tokenDecision.remaining, ipDecision.remaining),
|
|
};
|
|
}
|
|
|
|
export function __setSignatureOtpRateLimitStoreForTests(store: SharedStore): void {
|
|
cached = null;
|
|
storeFactory = () => store;
|
|
}
|
|
|
|
export function __resetSignatureOtpRateLimitStoreForTests(): void {
|
|
cached = null;
|
|
storeFactory = () => getSharedStore();
|
|
}
|