Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+101
-32
@@ -1,50 +1,119 @@
|
||||
import { createHash } from "node:crypto";
|
||||
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";
|
||||
|
||||
import { cache } from "~/utils/cache.server";
|
||||
import { getClientIPAddress } from "~/utils/server/IpUtils";
|
||||
|
||||
// Brute-Force-Soft-Gate fuer den Login (R-P2a): ab dem N-ten FEHLversuch (pro IP+Email)
|
||||
// wird ein mCaptcha verlangt, bevor der Passwort-Check ueberhaupt laeuft. Freundlicher als
|
||||
// ein harter Lockout und bremst automatisierte Versuche. Der separate Failure-Counter
|
||||
// (nur Hochzaehlen bei Fehlschlag, Reset bei Erfolg) ergaenzt den generischen Rate-Limiter,
|
||||
// der weiterhin als harter Backstop dient.
|
||||
// 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;
|
||||
|
||||
// Zeitfenster, in dem Fehlversuche zusammengezaehlt werden (gleitend, Reset bei Erfolg).
|
||||
const FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1000;
|
||||
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 FailedLoginEntry = { count: number; resetAt: number };
|
||||
type Identified = { request: Request; identifier?: string | null };
|
||||
|
||||
function failedLoginKey({ request, identifier }: Identified) {
|
||||
const ipAddress = getClientIPAddress(request.headers)?.toString() ?? "unknown";
|
||||
const normalizedIdentifier = identifier?.trim().toLowerCase() ?? "";
|
||||
const digest = createHash("sha256").update(`login-failures:${ipAddress}:${normalizedIdentifier}`).digest("hex");
|
||||
return `auth-login-failures:${digest}`;
|
||||
const captchaGateLogger = createScopedLogger("login-captcha-gate");
|
||||
let storeFactory: () => SharedStore = () => getSharedStore();
|
||||
|
||||
function failedLoginKey({ request, identifier }: Identified): string {
|
||||
return getPseudonymousAuthBucketKey({ request, action: "login", identifier });
|
||||
}
|
||||
|
||||
export function getFailedLoginCount(args: Identified): number {
|
||||
const entry = cache.get(failedLoginKey(args))?.value as FailedLoginEntry | undefined;
|
||||
if (!entry || entry.resetAt <= Date.now()) {
|
||||
return 0;
|
||||
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;
|
||||
}
|
||||
return entry.count;
|
||||
}
|
||||
|
||||
export function recordFailedLogin(args: Identified): number {
|
||||
const key = failedLoginKey(args);
|
||||
const now = Date.now();
|
||||
const entry = cache.get(key)?.value as FailedLoginEntry | undefined;
|
||||
const current = entry && entry.resetAt > now ? entry : { count: 0, resetAt: now + FAILED_LOGIN_WINDOW_MS };
|
||||
const count = current.count + 1;
|
||||
cache.set(key, { value: { count, resetAt: current.resetAt }, metadata: { createdTime: now } }, { ttl: Math.max(1, current.resetAt - now) });
|
||||
return count;
|
||||
/** 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;
|
||||
}
|
||||
}
|
||||
|
||||
export function clearFailedLogins(args: Identified): void {
|
||||
cache.delete(failedLoginKey(args));
|
||||
/** 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();
|
||||
}
|
||||
Reference in new issue
Block a user