Files

54 lines
1.7 KiB
TypeScript

import { createHmac } from "node:crypto";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { getTrustedClientIp } from "~/utils/server/IpUtils";
export type AuthThrottleAction =
| "login"
| "forgot-password"
| "reset-password"
| "mfa"
| "register"
| "registration-resend"
| "registration-verify"
| "invitation-view"
| "invitation-accept"
| "workspace-create-attempt"
| "workspace-create"
| "workspace-create-replay"
| "booking-submit"
| "lead-capture"
| "form-submit"
| "plugin-install"
| "plugin-settings"
| "oauth-register"
| "oauth-token"
| "oauth-revoke";
export type AuthThrottleKeyScope = "client" | "identifier" | "pair";
function getKeySecret(): string {
const { cryptoSecret, sessionSecret } = loadRequiredWebConfig();
const secret = cryptoSecret || sessionSecret;
if (!secret) {
throw new Error("Auth rate-limit key secret is unavailable.");
}
return secret;
}
/**
* Produces a stable HMAC bucket key without exposing enumerable identifiers or
* client addresses in Redis keys, metrics, or diagnostic snapshots.
*/
export function getPseudonymousAuthBucketKey(input: {
request: Request;
action: AuthThrottleAction;
identifier?: string | null;
scope?: AuthThrottleKeyScope;
}): string {
const scope = input.scope ?? "pair";
const ipAddress = scope === "identifier" ? "" : getTrustedClientIp(input.request) || "unknown";
const identifier = scope === "client" ? "" : input.identifier;
const normalizedIdentifier = identifier?.trim().toLowerCase() ?? "";
return createHmac("sha256", getKeySecret()).update(`v1\0${input.action}\0${scope}\0${ipAddress}\0${normalizedIdentifier}`).digest("hex");
}