Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,4 +1,8 @@
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;
@@ -9,6 +13,7 @@ const LOGIN_RATE_LIMIT_WINDOW_SECONDS = Math.ceil(LOGIN_RATE_LIMIT_WINDOW_MS / 1
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";
@@ -47,6 +52,19 @@ type Limiters = {
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) {
@@ -74,53 +92,66 @@ function getLimiters(): Limiters {
export async function checkLoginRateLimit(request: LoginRateLimitRequest): Promise<LoginRateLimitResult> {
const clientIp = deriveLoginRateLimitClientIp(request);
const accountKey = normalizeLoginRateLimitAccount(request.account);
const accountFingerprint = createLoginRateLimitAccountFingerprint(accountKey);
const { ip, account, store } = getLimiters();
try {
const accountFingerprint = createLoginRateLimitAccountFingerprint(accountKey);
const { ip, account } = getLimiters();
const ipState = await readCounter(store, "login-rate-limit:ip", clientIp);
if (ipState.count >= LOGIN_RATE_LIMIT_IP_ATTEMPTS) {
// 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: Math.max(1, ipState.ttlSeconds),
clientIp,
accountFingerprint,
retryAfterSeconds: LOGIN_RATE_LIMIT_WINDOW_SECONDS,
clientIp: UNKNOWN_CLIENT_IP,
accountFingerprint: UNAVAILABLE_ACCOUNT_FINGERPRINT,
};
}
const accountState = await readCounter(store, "login-rate-limit:account", accountKey);
if (accountState.count >= LOGIN_RATE_LIMIT_ACCOUNT_ATTEMPTS) {
return {
allowed: false,
scope: "account",
retryAfterSeconds: Math.max(1, accountState.ttlSeconds),
clientIp,
accountFingerprint,
};
}
// Silence unused-var: the limiter objects are kept on the cached `Limiters`
// because `recordFailedLoginAttempt` consumes them on the write path.
void ip;
void account;
return {
allowed: true,
clientIp,
accountFingerprint,
};
}
export async function recordFailedLoginAttempt(request: LoginRateLimitRequest): Promise<void> {
const { ip, account } = getLimiters();
const clientIp = deriveLoginRateLimitClientIp(request);
const accountKey = normalizeLoginRateLimitAccount(request.account);
await Promise.all([ip.consume(clientIp), account.consume(accountKey)]);
// 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(normalizeLoginRateLimitAccount(request.account));
await account.reset(pseudonymousBucketKey("account", normalizeLoginRateLimitAccount(request.account)));
}
export async function resetLoginRateLimiterForTests(): Promise<void> {
@@ -152,39 +183,30 @@ export function __setLoginRateLimitStoreForTests(store: SharedStore): void {
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;
}
// Trusted, proxy-set headers only. The leftmost X-Forwarded-For value is
// client-controlled, so keying the login throttle on it let an attacker reset
// their bucket by rotating the header (credential-stuffing bypass).
const TRUSTED_LOGIN_IP_HEADERS = ["cf-connecting-ip", "true-client-ip", "x-real-ip"] as const;
export function deriveLoginRateLimitClientIp(request: Pick<LoginRateLimitRequest, "headers" | "remoteAddress">): string {
for (const headerName of TRUSTED_LOGIN_IP_HEADERS) {
const value = readHeader(request.headers, headerName)?.trim();
if (value) {
return value;
}
}
const remoteAddress = request.remoteAddress?.trim();
return remoteAddress || UNKNOWN_CLIENT_IP;
return getTrustedProxyClientIp((name) => readHeader(request.headers, name), request.remoteAddress) ?? UNKNOWN_CLIENT_IP;
}
export function createLoginRateLimitAccountFingerprint(account: unknown): string {
const normalized = normalizeLoginRateLimitAccount(account);
let hash = 0x811c9dc5;
for (let index = 0; index < normalized.length; index += 1) {
hash ^= normalized.charCodeAt(index);
hash = Math.imul(hash, 0x01000193) >>> 0;
}
return `${FINGERPRINT_PREFIX}${hash.toString(16).padStart(8, "0")}`;
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 {
@@ -196,22 +218,8 @@ function normalizeLoginRateLimitAccount(account: unknown): string {
return normalized || UNKNOWN_ACCOUNT_KEY;
}
/**
* Peek at the current counter and remaining TTL without incrementing.
* The shared-store fixed-window helper only exposes `consume()` (which
* always increments) and `reset()`, so we read the underlying key
* directly to keep `checkLoginRateLimit` side-effect-free.
*/
async function readCounter(store: SharedStore, prefix: string, key: string): Promise<{ count: number; ttlSeconds: number }> {
const suffix = `rl:fixed:${prefix}:${key}`;
const raw = await store.get(suffix);
const count = raw === null ? 0 : Number.parseInt(raw, 10) || 0;
// The memory adapter does not expose a `ttl` helper, so derive a
// best-effort retry window from the configured window length. Redis
// counter TTL is enforced by the limiter on `consume`, so a fresh
// request entering the window gets the full window-seconds back.
const ttlSeconds = count > 0 ? LOGIN_RATE_LIMIT_WINDOW_SECONDS : 0;
return { count, ttlSeconds };
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 {