120 lines
4.1 KiB
TypeScript
120 lines
4.1 KiB
TypeScript
import { createFixedWindowRateLimiter, type SharedStore } from "@hivegrid/shared-store";
|
|
import { getPseudonymousAuthBucketKey } from "~/services/auth/auth-rate-limit-key.server";
|
|
import { getSharedStore } from "~/shared-store.server";
|
|
import { createScopedLogger } from "~/utils/logger.server";
|
|
|
|
// Require the self-hosted CAPTCHA after this many failed password attempts for
|
|
// the same trusted-IP/identifier pair. The hard auth limiter remains the
|
|
// authoritative backstop when CAPTCHA is not configured.
|
|
export const LOGIN_CAPTCHA_AFTER_FAILURES = 3;
|
|
|
|
const FAILED_LOGIN_WINDOW_SECONDS = 15 * 60;
|
|
const FAILURE_COUNTER_PREFIX = "auth-login-failures";
|
|
// This ceiling protects integer arithmetic but is unreachable behind the hard
|
|
// login limiter. It also avoids an unbounded numeric counter during abuse.
|
|
const MAX_FAILURE_COUNT = 1_000_000;
|
|
|
|
type Identified = { request: Request; identifier?: string | null };
|
|
|
|
const captchaGateLogger = createScopedLogger("login-captcha-gate");
|
|
let storeFactory: () => SharedStore = () => getSharedStore();
|
|
|
|
function failedLoginKey({ request, identifier }: Identified): string {
|
|
return getPseudonymousAuthBucketKey({ request, action: "login", identifier });
|
|
}
|
|
|
|
function getCounter() {
|
|
const store = storeFactory();
|
|
const limiter = createFixedWindowRateLimiter({
|
|
store,
|
|
prefix: FAILURE_COUNTER_PREFIX,
|
|
windowSeconds: FAILED_LOGIN_WINDOW_SECONDS,
|
|
max: MAX_FAILURE_COUNT,
|
|
});
|
|
return { store, limiter };
|
|
}
|
|
|
|
function storageKey(key: string): string {
|
|
return `rl:fixed:${FAILURE_COUNTER_PREFIX}:${key}`;
|
|
}
|
|
|
|
/**
|
|
* Reads the replica-shared failure count. A store/configuration failure
|
|
* requires CAPTCHA instead of silently weakening the gate.
|
|
*/
|
|
export async function getFailedLoginCount(args: Identified): Promise<number> {
|
|
try {
|
|
const key = failedLoginKey(args);
|
|
const { store } = getCounter();
|
|
const raw = await store.get(storageKey(key));
|
|
if (raw === null) return 0;
|
|
const count = Number.parseInt(raw, 10);
|
|
if (!Number.isSafeInteger(count) || count < 0) {
|
|
captchaGateLogger.error(
|
|
{ event: "auth.captcha_failure_counter.invalid" },
|
|
"Login CAPTCHA failure counter was invalid; CAPTCHA required",
|
|
);
|
|
return LOGIN_CAPTCHA_AFTER_FAILURES;
|
|
}
|
|
return Math.min(count, MAX_FAILURE_COUNT);
|
|
} catch (error) {
|
|
captchaGateLogger.error(
|
|
{
|
|
event: "auth.captcha_failure_counter.read_failed",
|
|
errorName: error instanceof Error ? error.name : "UnknownError",
|
|
},
|
|
"Login CAPTCHA failure counter could not be read; CAPTCHA required",
|
|
);
|
|
return LOGIN_CAPTCHA_AFTER_FAILURES;
|
|
}
|
|
}
|
|
|
|
/** Atomically records a failed login and starts the bounded expiry window. */
|
|
export async function recordFailedLogin(args: Identified): Promise<number> {
|
|
try {
|
|
const key = failedLoginKey(args);
|
|
const { limiter } = getCounter();
|
|
const decision = await limiter.consume(key);
|
|
return decision.allowed ? MAX_FAILURE_COUNT - decision.remaining : MAX_FAILURE_COUNT;
|
|
} catch (error) {
|
|
captchaGateLogger.error(
|
|
{
|
|
event: "auth.captcha_failure_counter.write_failed",
|
|
errorName: error instanceof Error ? error.name : "UnknownError",
|
|
},
|
|
"Login CAPTCHA failure counter could not be updated; login denied",
|
|
);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/** Clears the shared gate after a successful primary authentication. */
|
|
export async function clearFailedLogins(args: Identified): Promise<void> {
|
|
try {
|
|
const key = failedLoginKey(args);
|
|
const { limiter } = getCounter();
|
|
await limiter.reset(key);
|
|
} catch (error) {
|
|
captchaGateLogger.error(
|
|
{
|
|
event: "auth.captcha_failure_counter.reset_failed",
|
|
errorName: error instanceof Error ? error.name : "UnknownError",
|
|
},
|
|
"Login CAPTCHA failure counter could not be reset; login denied",
|
|
);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export function loginRequiresCaptcha(failedCount: number): boolean {
|
|
return failedCount >= LOGIN_CAPTCHA_AFTER_FAILURES;
|
|
}
|
|
|
|
export function __setLoginCaptchaGateStoreForTests(store: SharedStore): void {
|
|
storeFactory = () => store;
|
|
}
|
|
|
|
export function __resetLoginCaptchaGateStoreForTests(): void {
|
|
storeFactory = () => getSharedStore();
|
|
}
|