245 lines
8.2 KiB
TypeScript
245 lines
8.2 KiB
TypeScript
import { createHmac } from "node:crypto";
|
|
|
|
import { getTrustedProxyClientIp } from "@hivegrid/foundation/trusted-client-ip";
|
|
import { createFixedWindowRateLimiter, type FixedWindowRateLimiter, type SharedStore } from "@hivegrid/shared-store";
|
|
import { getApiRuntimeConfig } from "../config.js";
|
|
import { getSharedStore } from "../shared-store.js";
|
|
|
|
export const LOGIN_RATE_LIMIT_WINDOW_MS = 60_000;
|
|
export const LOGIN_RATE_LIMIT_IP_ATTEMPTS = 10;
|
|
export const LOGIN_RATE_LIMIT_ACCOUNT_ATTEMPTS = 5;
|
|
|
|
const LOGIN_RATE_LIMIT_WINDOW_SECONDS = Math.ceil(LOGIN_RATE_LIMIT_WINDOW_MS / 1000);
|
|
const UNKNOWN_CLIENT_IP = "unknown";
|
|
const UNKNOWN_ACCOUNT_KEY = "unknown-account";
|
|
const FINGERPRINT_PREFIX = "acct_";
|
|
const UNAVAILABLE_ACCOUNT_FINGERPRINT = `${FINGERPRINT_PREFIX}unavailable`;
|
|
|
|
export type LoginRateLimitScope = "ip" | "account";
|
|
|
|
export type LoginRateLimitRequest = {
|
|
headers?: Headers | Record<string, string | string[] | undefined>;
|
|
remoteAddress?: string | null;
|
|
account?: unknown;
|
|
};
|
|
|
|
export type LoginRateLimitAllowed = {
|
|
allowed: true;
|
|
clientIp: string;
|
|
accountFingerprint: string;
|
|
};
|
|
|
|
export type LoginRateLimitBlocked = {
|
|
allowed: false;
|
|
scope: LoginRateLimitScope;
|
|
retryAfterSeconds: number;
|
|
clientIp: string;
|
|
accountFingerprint: string;
|
|
};
|
|
|
|
export type LoginRateLimitResult = LoginRateLimitAllowed | LoginRateLimitBlocked;
|
|
|
|
/**
|
|
* Lazy holder around the two fixed-window limiters. Built on first use
|
|
* so tests can swap the SharedStore via `__setLoginRateLimitStoreForTests`
|
|
* before any limiter is constructed.
|
|
*/
|
|
type Limiters = {
|
|
ip: FixedWindowRateLimiter;
|
|
account: FixedWindowRateLimiter;
|
|
store: SharedStore;
|
|
};
|
|
|
|
let limiters: Limiters | null = null;
|
|
let storeFactory: () => SharedStore = () => getSharedStore();
|
|
let keySecretFactory: () => string = defaultKeySecret;
|
|
|
|
function defaultKeySecret(): string {
|
|
const secret = getApiRuntimeConfig().jwtSecret?.trim();
|
|
if (!secret) {
|
|
throw new Error("API login rate-limit key secret is unavailable.");
|
|
}
|
|
return secret;
|
|
}
|
|
|
|
function pseudonymousBucketKey(scope: "account" | "ip", value: string): string {
|
|
return createHmac("sha256", keySecretFactory()).update(`v1\0${scope}\0${value}`).digest("hex");
|
|
}
|
|
|
|
function getLimiters(): Limiters {
|
|
if (limiters !== null) {
|
|
return limiters;
|
|
}
|
|
const store = storeFactory();
|
|
limiters = {
|
|
store,
|
|
ip: createFixedWindowRateLimiter({
|
|
store,
|
|
prefix: "login-rate-limit:ip",
|
|
windowSeconds: LOGIN_RATE_LIMIT_WINDOW_SECONDS,
|
|
max: LOGIN_RATE_LIMIT_IP_ATTEMPTS,
|
|
}),
|
|
account: createFixedWindowRateLimiter({
|
|
store,
|
|
prefix: "login-rate-limit:account",
|
|
windowSeconds: LOGIN_RATE_LIMIT_WINDOW_SECONDS,
|
|
max: LOGIN_RATE_LIMIT_ACCOUNT_ATTEMPTS,
|
|
}),
|
|
};
|
|
return limiters;
|
|
}
|
|
|
|
export async function checkLoginRateLimit(request: LoginRateLimitRequest): Promise<LoginRateLimitResult> {
|
|
const clientIp = deriveLoginRateLimitClientIp(request);
|
|
const accountKey = normalizeLoginRateLimitAccount(request.account);
|
|
try {
|
|
const accountFingerprint = createLoginRateLimitAccountFingerprint(accountKey);
|
|
const { ip, account } = getLimiters();
|
|
|
|
// Reserve before the expensive password comparison. Each consume is an
|
|
// atomic Lua operation, so a parallel burst cannot send every request
|
|
// through bcrypt. HMAC-derived bucket keys keep raw IPs and enumerable
|
|
// account identifiers out of Redis. Check IP first so an already-blocked
|
|
// source cannot poison arbitrary account buckets without reaching a
|
|
// verifier.
|
|
const ipReservation = await ip.consume(pseudonymousBucketKey("ip", clientIp));
|
|
if (!ipReservation.allowed) {
|
|
return {
|
|
allowed: false,
|
|
scope: "ip",
|
|
retryAfterSeconds: retryAfterSeconds(ipReservation.resetAt),
|
|
clientIp,
|
|
accountFingerprint,
|
|
};
|
|
}
|
|
|
|
const accountReservation = await account.consume(pseudonymousBucketKey("account", accountKey));
|
|
if (!accountReservation.allowed) {
|
|
return {
|
|
allowed: false,
|
|
scope: "account",
|
|
retryAfterSeconds: retryAfterSeconds(accountReservation.resetAt),
|
|
clientIp,
|
|
accountFingerprint,
|
|
};
|
|
}
|
|
|
|
return {
|
|
allowed: true,
|
|
clientIp,
|
|
accountFingerprint,
|
|
};
|
|
} catch {
|
|
// A missing secret or unavailable shared store must not silently remove
|
|
// brute-force protection. Return only a fixed non-PII diagnostic marker.
|
|
return {
|
|
allowed: false,
|
|
scope: "ip",
|
|
retryAfterSeconds: LOGIN_RATE_LIMIT_WINDOW_SECONDS,
|
|
clientIp: UNKNOWN_CLIENT_IP,
|
|
accountFingerprint: UNAVAILABLE_ACCOUNT_FINGERPRINT,
|
|
};
|
|
}
|
|
}
|
|
|
|
export async function recordFailedLoginAttempt(request: LoginRateLimitRequest): Promise<void> {
|
|
// The attempt was already reserved atomically by checkLoginRateLimit before
|
|
// password verification. Keep this compatibility hook while callers migrate;
|
|
// consuming again here would double-count every failed password.
|
|
void request;
|
|
}
|
|
|
|
export async function recordSuccessfulLogin(request: Pick<LoginRateLimitRequest, "account">): Promise<void> {
|
|
const { account } = getLimiters();
|
|
await account.reset(pseudonymousBucketKey("account", normalizeLoginRateLimitAccount(request.account)));
|
|
}
|
|
|
|
export async function resetLoginRateLimiterForTests(): Promise<void> {
|
|
// Drop any cached limiter pair and best-effort drain any keys the
|
|
// previous limiters wrote to the shared-store. Tests that need full
|
|
// isolation can also inject a fresh store via
|
|
// `__setLoginRateLimitStoreForTests`.
|
|
const previous = limiters;
|
|
limiters = null;
|
|
if (previous) {
|
|
try {
|
|
for await (const fullKey of previous.store.adapter.scan(`shared-store:${previous.store.namespace}:rl:fixed:login-rate-limit:*`)) {
|
|
// adapter keys are absolute (namespace already applied); strip the
|
|
// namespace prefix when calling store.del which re-applies it.
|
|
const prefix = `shared-store:${previous.store.namespace}:`;
|
|
if (fullKey.startsWith(prefix)) {
|
|
await previous.store.del(fullKey.slice(prefix.length));
|
|
}
|
|
}
|
|
} catch {
|
|
// Best-effort; isolated tests use the store seam instead.
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Test seam: inject a SharedStore that backs the limiters. */
|
|
export function __setLoginRateLimitStoreForTests(store: SharedStore): void {
|
|
limiters = null;
|
|
storeFactory = () => store;
|
|
}
|
|
|
|
/** Test seam: provide an isolated HMAC key without loading production config. */
|
|
export function __setLoginRateLimitKeySecretForTests(secret: string | null): void {
|
|
keySecretFactory = () => {
|
|
const normalized = secret?.trim();
|
|
if (!normalized) throw new Error("API login rate-limit key secret is unavailable.");
|
|
return normalized;
|
|
};
|
|
}
|
|
|
|
/** Test seam: revert to the default factory (real shared-store singleton). */
|
|
export function __resetLoginRateLimitStoreForTests(): void {
|
|
limiters = null;
|
|
storeFactory = () => getSharedStore();
|
|
keySecretFactory = defaultKeySecret;
|
|
}
|
|
|
|
export function deriveLoginRateLimitClientIp(request: Pick<LoginRateLimitRequest, "headers" | "remoteAddress">): string {
|
|
return getTrustedProxyClientIp((name) => readHeader(request.headers, name), request.remoteAddress) ?? UNKNOWN_CLIENT_IP;
|
|
}
|
|
|
|
export function createLoginRateLimitAccountFingerprint(account: unknown): string {
|
|
const normalized = normalizeLoginRateLimitAccount(account);
|
|
const digest = createHmac("sha256", keySecretFactory()).update(`v1\0account-log\0${normalized}`).digest("hex");
|
|
return `${FINGERPRINT_PREFIX}${digest.slice(0, 24)}`;
|
|
}
|
|
|
|
function normalizeLoginRateLimitAccount(account: unknown): string {
|
|
if (typeof account !== "string") {
|
|
return UNKNOWN_ACCOUNT_KEY;
|
|
}
|
|
|
|
const normalized = account.trim().toLowerCase();
|
|
return normalized || UNKNOWN_ACCOUNT_KEY;
|
|
}
|
|
|
|
function retryAfterSeconds(resetAt: Date): number {
|
|
return Math.max(1, Math.ceil((resetAt.getTime() - Date.now()) / 1000));
|
|
}
|
|
|
|
function readHeader(headers: LoginRateLimitRequest["headers"], name: string): string | undefined {
|
|
if (!headers) {
|
|
return undefined;
|
|
}
|
|
|
|
if (headers instanceof Headers) {
|
|
return headers.get(name) ?? undefined;
|
|
}
|
|
|
|
const lowerName = name.toLowerCase();
|
|
for (const [headerName, value] of Object.entries(headers)) {
|
|
if (headerName.toLowerCase() !== lowerName) {
|
|
continue;
|
|
}
|
|
|
|
return Array.isArray(value) ? value[0] : value;
|
|
}
|
|
|
|
return undefined;
|
|
}
|