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

@@ -2,11 +2,20 @@ import { describe, expect, it } from "vitest";
import {
AdminFallbackLoginRejected,
assertAdminFallbackLoginAllowed,
assertAdminFallbackLoginAllowedForIdentity,
evaluateAdminFallbackLogin,
isCompletedAdminFallbackLoginResponse,
isAdminFallbackUiVisible,
readAdminFallbackPolicy,
} from "./admin-fallback.server";
const localFallbackEnv = {
NODE_ENV: "development",
LOCAL_DEV_CREDENTIALS: "1",
ADMIN_APP_HOST: "admin.localhost:3000",
DATABASE_URL: "postgresql://postgres:postgres@127.0.0.1:5432/hivegrid",
};
describe("readAdminFallbackPolicy", () => {
it("returns disabled+empty by default", () => {
expect(readAdminFallbackPolicy({})).toEqual({ enabled: false, allowlist: [] });
@@ -15,6 +24,7 @@ describe("readAdminFallbackPolicy", () => {
it("parses ADMIN_FALLBACK_LOGIN_EMAILS comma-separated, lowercased", () => {
expect(
readAdminFallbackPolicy({
...localFallbackEnv,
ADMIN_FALLBACK_LOGIN_ENABLED: "true",
ADMIN_FALLBACK_LOGIN_EMAILS: " Bootstrap@example.test , ops@example.test , ",
})
@@ -26,10 +36,20 @@ describe("readAdminFallbackPolicy", () => {
it("accepts common truthy values", () => {
for (const value of ["1", "true", "yes", "on", "TRUE"]) {
expect(readAdminFallbackPolicy({ ADMIN_FALLBACK_LOGIN_ENABLED: value }).enabled).toBe(true);
expect(readAdminFallbackPolicy({ ...localFallbackEnv, ADMIN_FALLBACK_LOGIN_ENABLED: value }).enabled).toBe(true);
}
});
it("fails closed outside the disposable local development contract", () => {
expect(
readAdminFallbackPolicy({
...localFallbackEnv,
NODE_ENV: "production",
ADMIN_FALLBACK_LOGIN_ENABLED: "true",
}).enabled
).toBe(false);
});
it("rejects non-truthy values", () => {
for (const value of ["0", "false", "no", "", "off", "maybe"]) {
expect(readAdminFallbackPolicy({ ADMIN_FALLBACK_LOGIN_ENABLED: value }).enabled).toBe(false);
@@ -71,7 +91,9 @@ describe("assertAdminFallbackLoginAllowed", () => {
});
it("throws AdminFallbackLoginRejected when not in allowlist", () => {
expect(() => assertAdminFallbackLoginAllowed("nobody@example.test", { enabled: true, allowlist: ["other@example.test"] })).toThrowError(AdminFallbackLoginRejected);
expect(() => assertAdminFallbackLoginAllowed("nobody@example.test", { enabled: true, allowlist: ["other@example.test"] })).toThrowError(
AdminFallbackLoginRejected
);
});
it("passes silently when both conditions are met", () => {
@@ -79,10 +101,62 @@ describe("assertAdminFallbackLoginAllowed", () => {
});
});
describe("assertAdminFallbackLoginAllowedForIdentity", () => {
it("does not apply the emergency admin policy to tenant identities", () => {
expect(() => assertAdminFallbackLoginAllowedForIdentity({ email: "tenant@example.test", admin: null }, { enabled: false, allowlist: [] })).not.toThrow();
});
it("requires both emergency gates for an AdminUser on every host", () => {
expect(() =>
assertAdminFallbackLoginAllowedForIdentity(
{ email: "admin@example.test", admin: { userId: "admin_1" } },
{ enabled: false, allowlist: ["admin@example.test"] }
)
).toThrowError(AdminFallbackLoginRejected);
expect(() =>
assertAdminFallbackLoginAllowedForIdentity(
{ email: "admin@example.test", admin: { userId: "admin_1" } },
{ enabled: true, allowlist: ["admin@example.test"] }
)
).not.toThrow();
});
});
describe("isAdminFallbackUiVisible", () => {
it("reflects enabled flag only (allowlist intentionally ignored at UI layer)", () => {
expect(isAdminFallbackUiVisible({ ADMIN_FALLBACK_LOGIN_ENABLED: "true" })).toBe(true);
expect(isAdminFallbackUiVisible({ ADMIN_FALLBACK_LOGIN_ENABLED: "false" })).toBe(false);
expect(isAdminFallbackUiVisible({ ...localFallbackEnv, ADMIN_FALLBACK_LOGIN_ENABLED: "true" })).toBe(true);
expect(isAdminFallbackUiVisible({ ...localFallbackEnv, ADMIN_FALLBACK_LOGIN_ENABLED: "false" })).toBe(false);
expect(isAdminFallbackUiVisible({})).toBe(false);
});
});
describe("isCompletedAdminFallbackLoginResponse", () => {
it("accepts only a redirect carrying the completed login session cookie", () => {
expect(
isCompletedAdminFallbackLoginResponse(
new Response(null, {
status: 302,
headers: { Location: "/dashboard", "Set-Cookie": "__Host-hivegrid_admin_session=signed; Path=/; HttpOnly; Secure" },
})
)
).toBe(true);
});
it("rejects credential errors, MFA-pending responses, and redirects without a session", () => {
expect(isCompletedAdminFallbackLoginResponse(Response.json({ error: "invalid" }, { status: 400 }))).toBe(false);
expect(
isCompletedAdminFallbackLoginResponse(
Response.json({ requiresMfa: true }, { status: 200, headers: { "Set-Cookie": "hivegrid_session=pending; Path=/; HttpOnly" } })
)
).toBe(false);
expect(isCompletedAdminFallbackLoginResponse(new Response(null, { status: 302, headers: { Location: "/login" } }))).toBe(false);
expect(
isCompletedAdminFallbackLoginResponse(
new Response(null, { status: 302, headers: { "Set-Cookie": "__Host-hivegrid_app_session=signed; Path=/; Secure" } })
)
).toBe(false);
expect(
isCompletedAdminFallbackLoginResponse(new Response(null, { status: 302, headers: { "Set-Cookie": "hivegrid_session=legacy-parent-domain; Path=/" } }))
).toBe(false);
});
});
@@ -11,6 +11,7 @@
* invoke `assertAdminFallbackLoginAllowed` before validating credentials
* and audit-log every fallback attempt via the admin-sso audit helper.
*/
import { assertLocalCredentialsEnvironment } from "~/utils/db/seed/localCredentialsEnvironment.server";
const TRUE_VALUES = new Set(["1", "true", "yes", "on"]);
@@ -21,7 +22,14 @@ export type AdminFallbackPolicy = {
export function readAdminFallbackPolicy(env: Record<string, string | undefined> = process.env): AdminFallbackPolicy {
const rawEnabled = (env.ADMIN_FALLBACK_LOGIN_ENABLED ?? "").trim().toLowerCase();
const enabled = TRUE_VALUES.has(rawEnabled);
let localEnvironmentAllowed = false;
try {
assertLocalCredentialsEnvironment(env);
localEnvironmentAllowed = true;
} catch {
localEnvironmentAllowed = false;
}
const enabled = TRUE_VALUES.has(rawEnabled) && localEnvironmentAllowed;
const rawList = env.ADMIN_FALLBACK_LOGIN_EMAILS ?? "";
const allowlist = rawList
.split(",")
@@ -34,10 +42,7 @@ export type FallbackEvaluation =
| { readonly ok: true; readonly policy: AdminFallbackPolicy }
| { readonly ok: false; readonly reason: "disabled" | "email-not-allowlisted" };
export function evaluateAdminFallbackLogin(
email: string,
policy: AdminFallbackPolicy = readAdminFallbackPolicy()
): FallbackEvaluation {
export function evaluateAdminFallbackLogin(email: string, policy: AdminFallbackPolicy = readAdminFallbackPolicy()): FallbackEvaluation {
if (!policy.enabled) {
return { ok: false, reason: "disabled" };
}
@@ -68,6 +73,20 @@ export function assertAdminFallbackLoginAllowed(email: string, policy?: AdminFal
}
}
/**
* Enforce the emergency fallback policy only when the resolved identity is an
* admin. Keeping this identity-aware guard in one place prevents app-host
* login paths from accidentally bypassing the explicit emergency policy.
*/
export function assertAdminFallbackLoginAllowedForIdentity(
identity: { readonly email: string; readonly admin?: unknown | null },
policy?: AdminFallbackPolicy
): void {
if (identity.admin) {
assertAdminFallbackLoginAllowed(identity.email, policy);
}
}
/**
* UI-side helper: true iff the admin login page should reveal the
* fallback toggle at all. The actual email-allowlist check happens
@@ -76,3 +95,11 @@ export function assertAdminFallbackLoginAllowed(email: string, policy?: AdminFal
export function isAdminFallbackUiVisible(env: Record<string, string | undefined> = process.env): boolean {
return readAdminFallbackPolicy(env).enabled;
}
export function isCompletedAdminFallbackLoginResponse(response: Response): boolean {
if (response.status < 300 || response.status >= 400) {
return false;
}
const setCookie = response.headers.get("set-cookie") ?? "";
return ["__Host-hivegrid_admin_session=", "hivegrid_admin_session="].some((name) => setCookie.includes(name));
}
@@ -1,150 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
import { getUserSession } from "~/utils/session.server";
import { getUser, getUserTotpStatus } from "~/utils/db/users.db.server";
import { writeAdminSsoAuditEvent } from "~/modules/admin-sso/audit.server";
import {
requireAdminMfaForAction,
SENSITIVE_ADMIN_ACTIONS,
isSensitiveAdminAction,
} from "./admin-mfa-gate.server";
vi.mock("@hivegrid/config", () => ({
loadRequiredWebConfig: vi.fn(() => ({ routing: { appUrl: "https://app.example.test" } })),
}));
vi.mock("~/utils/auth/mfa/enforcement.server", () => ({
enforceAdminMfa: vi.fn(),
}));
vi.mock("~/utils/auth/mfa/step-up.server", () => ({
checkMfaStepUpState: vi.fn(),
}));
vi.mock("~/utils/app/CrossHostUrls", () => ({
absoluteAppRootPath: vi.fn(() => "https://app.example.test"),
}));
vi.mock("~/utils/session.server", () => ({
getUserSession: vi.fn(),
}));
vi.mock("~/utils/db/users.db.server", () => ({
getUser: vi.fn(),
getUserTotpStatus: vi.fn(),
}));
vi.mock("~/modules/admin-sso/audit.server", () => ({
writeAdminSsoAuditEvent: vi.fn(),
}));
const enforceAdminMfaMock = vi.mocked(enforceAdminMfa);
const checkMfaStepUpStateMock = vi.mocked(checkMfaStepUpState);
const getUserSessionMock = vi.mocked(getUserSession);
const getUserMock = vi.mocked(getUser);
const getUserTotpStatusMock = vi.mocked(getUserTotpStatus);
const writeAdminSsoAuditEventMock = vi.mocked(writeAdminSsoAuditEvent);
beforeEach(() => {
vi.clearAllMocks();
getUserSessionMock.mockResolvedValue({ get: vi.fn() } as never);
getUserMock.mockResolvedValue({ id: "user_1", admin: true } as never);
getUserTotpStatusMock.mockResolvedValue({ enabled: true } as never);
checkMfaStepUpStateMock.mockReturnValue({
verified: true,
state: { userId: "user_1", method: "totp", verifiedAt: "2026-05-25T12:00:00.000Z" },
ageMs: 1000,
});
enforceAdminMfaMock.mockReturnValue({ allowed: true, reason: "allowed", redirectTo: "/admin" });
writeAdminSsoAuditEventMock.mockResolvedValue(undefined);
});
describe("SENSITIVE_ADMIN_ACTIONS taxonomy", () => {
it("includes the spec-required actions", () => {
expect(SENSITIVE_ADMIN_ACTIONS).toContain("impersonation.start");
expect(SENSITIVE_ADMIN_ACTIONS).toContain("tenant.delete");
expect(SENSITIVE_ADMIN_ACTIONS).toContain("permission.grant");
expect(SENSITIVE_ADMIN_ACTIONS).toContain("audit.export");
expect(SENSITIVE_ADMIN_ACTIONS).toContain("data.export");
});
it("typeguard accepts known actions and rejects unknown", () => {
expect(isSensitiveAdminAction("impersonation.start")).toBe(true);
expect(isSensitiveAdminAction("tenant.delete")).toBe(true);
expect(isSensitiveAdminAction("totally-random")).toBe(false);
expect(isSensitiveAdminAction("")).toBe(false);
});
});
describe("requireAdminMfaForAction", () => {
it("returns the actor and writes success audit when MFA enforcement allows the action", async () => {
const request = new Request("https://admin.example.test/admin/accounts");
await expect(requireAdminMfaForAction(request, "tenant.delete", "user_1")).resolves.toEqual({
userId: "user_1",
action: "tenant.delete",
});
expect(getUserSessionMock).toHaveBeenCalledWith(request);
expect(getUserMock).toHaveBeenCalledWith("user_1");
expect(getUserTotpStatusMock).toHaveBeenCalledWith("user_1");
expect(enforceAdminMfaMock).toHaveBeenCalledWith(
expect.objectContaining({
requestUrl: request.url,
userId: "user_1",
isAdmin: true,
redirectMode: "host-aware",
appFallbackPath: "https://app.example.test",
}),
);
expect(writeAdminSsoAuditEventMock).toHaveBeenCalledWith(
expect.objectContaining({
action: "admin.mfa.app.challenge.success",
actorAdminUserId: "user_1",
request,
meta: { action: "tenant.delete" },
}),
);
});
it("audits and throws a redirect response when enforcement returns a Response", async () => {
const request = new Request("https://admin.example.test/admin/accounts");
const redirectResponse = new Response(null, {
status: 302,
headers: { Location: "/admin/security/mfa-challenge" },
});
enforceAdminMfaMock.mockReturnValue(redirectResponse as never);
await expect(requireAdminMfaForAction(request, "audit.export", "user_1")).rejects.toBe(redirectResponse);
expect(writeAdminSsoAuditEventMock).toHaveBeenCalledWith(
expect.objectContaining({
action: "admin.mfa.app.challenge.failure",
actorAdminUserId: "user_1",
request,
meta: { action: "audit.export", reason: "redirect-response" },
}),
);
});
it("audits denied enforcement and throws a redirect to the challenge path", async () => {
const request = new Request("https://admin.example.test/admin/accounts");
enforceAdminMfaMock.mockReturnValue({
allowed: false,
reason: "step-up-missing",
redirectTo: "/admin/security/mfa-challenge?redirectTo=%2Fadmin%2Faccounts",
});
await expect(requireAdminMfaForAction(request, "permission.grant", "user_1")).rejects.toMatchObject({
status: 302,
});
expect(writeAdminSsoAuditEventMock).toHaveBeenCalledWith(
expect.objectContaining({
action: "admin.mfa.app.challenge.failure",
actorAdminUserId: "user_1",
request,
meta: { action: "permission.grant", reason: "step-up-missing" },
}),
);
});
});
@@ -1,94 +0,0 @@
/**
* Phase 09 Task #82 — App-MFA gate for sensitive admin actions.
*
* Wrapper on top of the existing `enforceAdminMfa` helper (Phase 01 #26
* consolidated otpauth TOTP). Adds an action-keyed taxonomy so callers
* inside admin route handlers can declare intent without re-implementing
* the step-up plumbing.
*
* The wrapper itself does NOT touch the database or generate new TOTP
* secrets — that is owned by the existing /admin/security/mfa-* routes.
* Calling it just (a) checks the step-up cache, (b) throws a Response
* redirect when challenge is required.
*/
import { redirect } from "react-router";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
import { getUserSession } from "~/utils/session.server";
import { getUser, getUserTotpStatus } from "~/utils/db/users.db.server";
import { writeAdminSsoAuditEvent } from "~/modules/admin-sso/audit.server";
/**
* Canonical taxonomy of sensitive admin actions. Kept as a closed union
* so a typo in a caller surfaces as a TS error rather than silently
* skipping the gate.
*/
export const SENSITIVE_ADMIN_ACTIONS = [
"impersonation.start",
"tenant.delete",
"permission.grant",
"audit.export",
"data.export",
] as const;
export type SensitiveAdminAction = (typeof SENSITIVE_ADMIN_ACTIONS)[number];
export function isSensitiveAdminAction(value: string): value is SensitiveAdminAction {
return (SENSITIVE_ADMIN_ACTIONS as readonly string[]).includes(value);
}
export type AdminMfaGateResult = {
readonly userId: string;
readonly action: SensitiveAdminAction;
};
/**
* Throws a Response (redirect to /admin/security/mfa-challenge or to
* /admin/security/mfa-enroll) when step-up is missing/stale; otherwise
* returns the actor user id for downstream audit logging.
*/
export async function requireAdminMfaForAction(
request: Request,
action: SensitiveAdminAction,
actorUserId: string,
): Promise<AdminMfaGateResult> {
const session = await getUserSession(request);
const actor = await getUser(actorUserId);
const totpStatus = actor ? await getUserTotpStatus(actor.id) : null;
const enforcement = enforceAdminMfa({
requestUrl: request.url,
userId: actor?.id,
isAdmin: Boolean(actor?.admin),
totpStatus,
stepUp: actor ? checkMfaStepUpState(session, actor.id) : { verified: false, reason: "missing" },
redirectMode: "host-aware",
appFallbackPath: absoluteAppRootPath(loadRequiredWebConfig().routing),
});
if (enforcement instanceof Response) {
await writeAdminSsoAuditEvent({
action: "admin.mfa.app.challenge.failure",
actorAdminUserId: actorUserId,
request,
meta: { action, reason: "redirect-response" },
});
throw enforcement;
}
if (!enforcement.allowed) {
await writeAdminSsoAuditEvent({
action: "admin.mfa.app.challenge.failure",
actorAdminUserId: actorUserId,
request,
meta: { action, reason: enforcement.reason ?? "denied" },
});
throw redirect(enforcement.redirectTo);
}
await writeAdminSsoAuditEvent({
action: "admin.mfa.app.challenge.success",
actorAdminUserId: actorUserId,
request,
meta: { action },
});
return { userId: actorUserId, action };
}
@@ -0,0 +1,50 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("~/utils/db/users.db.server", () => ({ getUserTotpStatus: vi.fn() }));
vi.mock("~/utils/session.server", () => ({ commitPendingMfaLoginCookie: vi.fn() }));
import { getUserTotpStatus } from "~/utils/db/users.db.server";
import { commitPendingMfaLoginCookie } from "~/utils/session.server";
import { beginAlternativeLoginMfa } from "./alternative-login-mfa.server";
const request = new Request("https://app.example.test/auth/callback");
describe("alternative login MFA transition", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(commitPendingMfaLoginCookie).mockResolvedValue("hivegrid_session=pending; HttpOnly");
});
it("creates pending state whenever TOTP is enabled", async () => {
vi.mocked(getUserTotpStatus).mockResolvedValue({ enabled: true } as never);
await expect(
beginAlternativeLoginMfa({ request, userId: "user_1", redirectTo: "/acme/dashboard", primaryMethod: "magic-link" }),
).resolves.toEqual({ required: true, setCookie: "hivegrid_session=pending; HttpOnly" });
expect(commitPendingMfaLoginCookie).toHaveBeenCalledWith(request, {
userId: "user_1",
redirectTo: "/acme/dashboard",
primaryMethod: "magic-link",
});
});
it("allows the primary flow to finish only when TOTP is explicitly disabled", async () => {
vi.mocked(getUserTotpStatus).mockResolvedValue({ enabled: false } as never);
await expect(
beginAlternativeLoginMfa({ request, userId: "user_1", redirectTo: "/", primaryMethod: "admin-sso" }),
).resolves.toEqual({ required: false });
expect(commitPendingMfaLoginCookie).not.toHaveBeenCalled();
});
it("fails closed when MFA status cannot be resolved", async () => {
vi.mocked(getUserTotpStatus).mockResolvedValue(null);
await expect(
beginAlternativeLoginMfa({ request, userId: "user_1", redirectTo: "/", primaryMethod: "invitation" }),
).rejects.toThrow("MFA status is unavailable");
expect(commitPendingMfaLoginCookie).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,38 @@
import { getUserTotpStatus } from "~/utils/db/users.db.server";
import { commitPendingMfaLoginCookie, type PendingMfaPrimaryMethod } from "~/utils/session.server";
export const LOGIN_MFA_CHALLENGE_PATH = "/login-mfa";
export type AlternativeLoginMfaResult =
| { required: false }
| { required: true; setCookie: string };
/**
* Alternative primary factors without a separately verified upstream MFA
* assurance must not silently satisfy a configured second factor. Trusted
* device bypass is intentionally excluded from these flows: an enabled TOTP
* configuration always transitions to the pending MFA state.
*/
export async function beginAlternativeLoginMfa({
request,
userId,
redirectTo,
primaryMethod,
}: {
request: Request;
userId: string;
redirectTo: string;
primaryMethod: PendingMfaPrimaryMethod;
}): Promise<AlternativeLoginMfaResult> {
const status = await getUserTotpStatus(userId);
if (!status) {
throw new Error("MFA status is unavailable for the authenticated identity");
}
if (!status.enabled) {
return { required: false };
}
return {
required: true,
setCookie: await commitPendingMfaLoginCookie(request, { userId, redirectTo, primaryMethod }),
};
}
@@ -0,0 +1,57 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const { getTrustedClientIp, loadRequiredWebConfig } = vi.hoisted(() => ({
getTrustedClientIp: vi.fn(),
loadRequiredWebConfig: vi.fn(),
}));
vi.mock("@hivegrid/config", () => ({ loadRequiredWebConfig }));
vi.mock("~/utils/server/IpUtils", () => ({ getTrustedClientIp }));
import { getPseudonymousAuthBucketKey } from "./auth-rate-limit-key.server";
describe("pseudonymous auth rate-limit keys", () => {
beforeEach(() => {
vi.clearAllMocks();
loadRequiredWebConfig.mockReturnValue({ cryptoSecret: "crypto-secret", sessionSecret: "session-secret" });
getTrustedClientIp.mockReturnValue("203.0.113.10");
});
it("normalizes identifiers and keeps the pair bucket pseudonymous", () => {
const request = new Request("https://app.example.test/login");
const first = getPseudonymousAuthBucketKey({ request, action: "login", identifier: " Ada@Example.test " });
const second = getPseudonymousAuthBucketKey({ request, action: "login", identifier: "ada@example.test" });
expect(first).toBe(second);
expect(first).toMatch(/^[a-f0-9]{64}$/);
expect(first).not.toContain("ada@example.test");
expect(first).not.toContain("203.0.113.10");
});
it("separates client-only and identifier-only dimensions", () => {
const request = new Request("https://app.example.test/login");
const client = getPseudonymousAuthBucketKey({ request, action: "login", identifier: "ada@example.test", scope: "client" });
const clientWithOtherIdentifier = getPseudonymousAuthBucketKey({ request, action: "login", identifier: "other@example.test", scope: "client" });
const identifier = getPseudonymousAuthBucketKey({ request, action: "login", identifier: "ada@example.test", scope: "identifier" });
getTrustedClientIp.mockReturnValue(null);
const identifierFromUnknownClient = getPseudonymousAuthBucketKey({
request,
action: "login",
identifier: "ada@example.test",
scope: "identifier",
});
expect(client).toBe(clientWithOtherIdentifier);
expect(identifier).toBe(identifierFromUnknownClient);
expect(client).not.toBe(identifier);
});
it("falls back to the session secret and rejects a missing key", () => {
const request = new Request("https://app.example.test/login");
loadRequiredWebConfig.mockReturnValueOnce({ cryptoSecret: "", sessionSecret: "session-secret" });
expect(getPseudonymousAuthBucketKey({ request, action: "login" })).toMatch(/^[a-f0-9]{64}$/);
loadRequiredWebConfig.mockReturnValueOnce({ cryptoSecret: "", sessionSecret: "" });
expect(() => getPseudonymousAuthBucketKey({ request, action: "login" })).toThrow("Auth rate-limit key secret is unavailable.");
});
});
@@ -0,0 +1,53 @@
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");
}
@@ -1,65 +1,266 @@
import { MemoryAdapter, createSharedStore } from "@hivegrid/shared-store";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cache } from "~/utils/cache.server";
import { checkAuthRateLimit, getAuthRateLimitKey } from "./auth-rate-limit.server";
vi.mock("@hivegrid/config", async () => {
const actual = await vi.importActual<typeof import("@hivegrid/config")>("@hivegrid/config");
return {
...actual,
loadRequiredWebConfig: () => ({ cryptoSecret: "test-auth-rate-limit-secret", sessionSecret: "test-session-secret" }),
};
});
import { __resetAuthRateLimitStoreForTests, __setAuthRateLimitStoreForTests, checkAuthRateLimit, getAuthRateLimitKey } from "./auth-rate-limit.server";
function cloudflareHeaders(clientIp: string) {
return { "cf-connecting-ip": clientIp, "x-forwarded-for": `${clientIp}, 173.245.48.10` };
}
describe("auth rate limiting", () => {
let adapter: MemoryAdapter;
beforeEach(() => {
cache.clear();
vi.spyOn(Date, "now").mockReturnValue(new Date("2026-05-25T12:00:00.000Z").getTime());
adapter = new MemoryAdapter();
__setAuthRateLimitStoreForTests(createSharedStore({ namespace: "auth-rate-test", adapter }));
});
afterEach(() => {
__resetAuthRateLimitStoreForTests();
vi.restoreAllMocks();
cache.clear();
});
it("builds stable keys from action, client ip, and normalized identifier", () => {
it("builds stable pseudonymous keys from action, trusted client ip, and normalized identifier", () => {
const request = new Request("https://example.test/login", {
headers: { "cf-connecting-ip": "203.0.113.10" },
headers: cloudflareHeaders("203.0.113.10"),
});
expect(getAuthRateLimitKey({ request, action: "login", identifier: " Ada@Example.COM " })).toBe(
getAuthRateLimitKey({ request, action: "login", identifier: "ada@example.com" })
);
expect(getAuthRateLimitKey({ request, action: "login", identifier: "ada@example.com" })).not.toBe(
getAuthRateLimitKey({ request, action: "forgot-password", identifier: "ada@example.com" })
const normalized = getAuthRateLimitKey({ request, action: "login", identifier: "ada@example.com" });
expect(getAuthRateLimitKey({ request, action: "login", identifier: " Ada@Example.COM " })).toBe(normalized);
expect(getAuthRateLimitKey({ request, action: "forgot-password", identifier: "ada@example.com" })).not.toBe(normalized);
expect(normalized).toMatch(/^[a-f0-9]{64}$/);
expect(normalized).not.toContain("ada@example.com");
expect(normalized).not.toContain("203.0.113.10");
});
it("keeps registration verification capabilities and client IPs out of rate-limit keys", () => {
const verificationToken = "raw-registration-verification-capability";
const clientIp = "203.0.113.27";
const request = new Request("https://example.test/verify/token", {
headers: cloudflareHeaders(clientIp),
});
const key = getAuthRateLimitKey({ request, action: "registration-verify", identifier: verificationToken });
expect(key).toMatch(/^[a-f0-9]{64}$/u);
expect(key).not.toContain(verificationToken);
expect(key).not.toContain(clientIp);
});
it("keeps invitation capabilities out of view and acceptance bucket keys", async () => {
const invitationToken = "raw-workspace-invitation-capability";
const request = new Request(`https://example.test/invitation/${invitationToken}`, {
headers: cloudflareHeaders("203.0.113.41"),
});
for (const action of ["invitation-view", "invitation-accept"] as const) {
const key = getAuthRateLimitKey({ request, action, identifier: invitationToken });
expect(key).toMatch(/^[a-f0-9]{64}$/u);
expect(key).not.toContain(invitationToken);
await expect(checkAuthRateLimit({ request, action, identifier: invitationToken, limit: 2, windowMs: 30_000 })).resolves.toEqual({ allowed: true });
}
const storedKeys = [];
for await (const key of adapter.scan("*")) storedKeys.push(key);
expect(JSON.stringify(storedKeys)).not.toContain(invitationToken);
});
it("does not key on a spoofed leftmost X-Forwarded-For or X-Client-IP", () => {
const first = new Request("https://example.test/login", {
headers: { "x-forwarded-for": "9.9.9.9, 198.51.100.7", "x-client-ip": "8.8.8.8" },
});
const rotated = new Request("https://example.test/login", {
headers: { "x-forwarded-for": "4.4.4.4, 198.51.100.7", "x-client-ip": "1.1.1.1" },
});
expect(getAuthRateLimitKey({ request: first, action: "login", identifier: "ada@example.com" })).toBe(
getAuthRateLimitKey({ request: rotated, action: "login", identifier: "ada@example.com" }),
);
});
it("does not key on a spoofable X-Forwarded-For / X-Client-IP", () => {
// Both spoofable headers must be ignored, so a forged value cannot move the
// request into a fresh rate-limit bucket. Both requests collapse to the same
// (untrusted -> "unknown") key.
const forged = new Request("https://example.test/login", { headers: { "x-forwarded-for": "9.9.9.9", "x-client-ip": "8.8.8.8" } });
const bare = new Request("https://example.test/login", {});
expect(getAuthRateLimitKey({ request: forged, action: "login", identifier: "ada@example.com" })).toBe(
getAuthRateLimitKey({ request: bare, action: "login", identifier: "ada@example.com" })
);
});
it("allows requests up to the limit and returns retry timing after the limit", () => {
it("allows requests up to the atomic limit and returns retry timing after the limit", async () => {
const request = new Request("https://example.test/login", {
headers: { "cf-connecting-ip": "203.0.113.10" },
headers: cloudflareHeaders("203.0.113.10"),
});
const options = { request, action: "login" as const, identifier: "ada@example.com", limit: 2, windowMs: 30_000 };
expect(checkAuthRateLimit(options)).toEqual({ allowed: true });
expect(checkAuthRateLimit(options)).toEqual({ allowed: true });
expect(checkAuthRateLimit(options)).toEqual({ allowed: false, retryAfterSeconds: 30 });
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: true });
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: true });
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: false, retryAfterSeconds: 30 });
});
it("starts a new window after the cached counter expires", () => {
it("shares reservations between replicas using the same backing adapter", async () => {
const request = new Request("https://example.test/login", { headers: cloudflareHeaders("203.0.113.10") });
const options = { request, action: "login" as const, identifier: "ada@example.com", limit: 1, windowMs: 30_000 };
const replicaA = createSharedStore({ namespace: "auth-rate-replicas", adapter });
const replicaB = createSharedStore({ namespace: "auth-rate-replicas", adapter });
__setAuthRateLimitStoreForTests(replicaA);
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: true });
__setAuthRateLimitStoreForTests(replicaB);
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: false, retryAfterSeconds: 30 });
});
it("permits exactly the configured number during a parallel burst", async () => {
const request = new Request("https://example.test/login", { headers: cloudflareHeaders("203.0.113.10") });
const options = { request, action: "login" as const, identifier: "ada@example.com", limit: 5, windowMs: 30_000 };
const decisions = await Promise.all(Array.from({ length: 20 }, () => checkAuthRateLimit(options)));
expect(decisions.filter((decision) => decision.allowed)).toHaveLength(5);
expect(decisions.filter((decision) => !decision.allowed)).toHaveLength(15);
});
it("bounds one identifier across rotating trusted client addresses", async () => {
const decisions = [];
for (let index = 1; index <= 4; index += 1) {
decisions.push(
await checkAuthRateLimit({
request: new Request("https://example.test/login", { headers: cloudflareHeaders(`203.0.113.${index}`) }),
action: "login",
identifier: "ada@example.com",
limit: 1,
windowMs: 30_000,
})
);
}
expect(decisions.map((decision) => decision.allowed)).toEqual([true, true, true, false]);
});
it("honors an explicit global identifier cap across rotating trusted client addresses", async () => {
const decisions = [];
for (let index = 1; index <= 3; index += 1) {
decisions.push(
await checkAuthRateLimit({
request: new Request("https://example.test/register", { headers: cloudflareHeaders(`203.0.113.${index}`) }),
action: "register",
identifier: " Ada@Example.COM ",
limit: 5,
identifierLimit: 2,
windowMs: 60 * 60 * 1000,
})
);
}
expect(decisions.map((decision) => decision.allowed)).toEqual([true, true, false]);
const storedKeys = [];
for await (const key of adapter.scan("*")) storedKeys.push(key);
expect(JSON.stringify(storedKeys)).not.toContain("ada@example.com");
});
it("can disable the global identifier bucket while retaining client and pair limits", async () => {
const requestFor = (lastOctet: number) =>
new Request("https://example.test/register", {
headers: cloudflareHeaders(`203.0.113.${lastOctet}`),
});
const baseOptions = {
action: "register" as const,
identifier: "victim@example.test",
limit: 1,
identifierLimit: null,
windowMs: 60 * 60 * 1000,
};
await expect(checkAuthRateLimit({ ...baseOptions, request: requestFor(1) })).resolves.toEqual({ allowed: true });
await expect(checkAuthRateLimit({ ...baseOptions, request: requestFor(2) })).resolves.toEqual({ allowed: true });
await expect(checkAuthRateLimit({ ...baseOptions, request: requestFor(3) })).resolves.toEqual({ allowed: true });
await expect(checkAuthRateLimit({ ...baseOptions, request: requestFor(1) })).resolves.toEqual({
allowed: false,
retryAfterSeconds: 60 * 60,
});
const storedKeys = [];
for await (const key of adapter.scan("*")) storedKeys.push(key);
expect(storedKeys.some((key) => key.includes(":identifier:"))).toBe(false);
});
it("caps identifier churn per trusted client to bound live Redis keys", async () => {
const decisions = [];
for (let index = 1; index <= 11; index += 1) {
decisions.push(
await checkAuthRateLimit({
request: new Request("https://example.test/login", { headers: cloudflareHeaders("203.0.113.10") }),
action: "login",
identifier: `generated-${index}@example.com`,
limit: 1,
windowMs: 30_000,
})
);
}
expect(decisions.map((decision) => decision.allowed)).toEqual([true, true, true, true, true, true, true, true, true, true, false]);
});
it("starts a new window after the shared counter expires", async () => {
const request = new Request("https://example.test/mfa", {
headers: { "cf-connecting-ip": "203.0.113.10" },
headers: cloudflareHeaders("203.0.113.10"),
});
const options = { request, action: "mfa" as const, identifier: "ada@example.com", limit: 1, windowMs: 10_000 };
expect(checkAuthRateLimit(options)).toEqual({ allowed: true });
expect(checkAuthRateLimit(options)).toEqual({ allowed: false, retryAfterSeconds: 10 });
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: true });
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: false, retryAfterSeconds: 10 });
vi.mocked(Date.now).mockReturnValue(new Date("2026-05-25T12:00:11.000Z").getTime());
expect(checkAuthRateLimit(options)).toEqual({ allowed: true });
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: true });
});
it("fails closed with a bounded retry interval when the shared store fails", async () => {
vi.spyOn(adapter, "eval").mockRejectedValueOnce(new Error("redis unavailable"));
const request = new Request("https://example.test/login");
await expect(checkAuthRateLimit({ request, action: "login", identifier: "ada@example.com", limit: 2, windowMs: 30_000 })).resolves.toEqual({
allowed: false,
retryAfterSeconds: 30,
});
});
it("fails closed before an invitation lookup when the shared throttle store is unavailable", async () => {
vi.spyOn(adapter, "eval").mockRejectedValueOnce(new Error("redis unavailable"));
const invitationToken = "raw-workspace-invitation-capability";
const request = new Request(`https://example.test/invitation/${invitationToken}`);
await expect(
checkAuthRateLimit({
request,
action: "invitation-view",
identifier: invitationToken,
limit: 30,
windowMs: 15 * 60 * 1000,
})
).resolves.toEqual({ allowed: false, retryAfterSeconds: 15 * 60 });
});
it("fails closed for invalid limits and windows with bounded retry values", async () => {
const request = new Request("https://example.test/login");
await expect(checkAuthRateLimit({ request, action: "login", limit: 0, windowMs: 30_000 })).resolves.toEqual({
allowed: false,
retryAfterSeconds: 30,
});
await expect(checkAuthRateLimit({ request, action: "login", limit: 1, windowMs: Number.NaN })).resolves.toEqual({
allowed: false,
retryAfterSeconds: 1,
});
await expect(checkAuthRateLimit({ request, action: "login", limit: 10_001, windowMs: 24 * 60 * 60 * 1000 + 1 })).resolves.toEqual({
allowed: false,
retryAfterSeconds: 86_400,
});
});
it("uses the configured window when the store returns an invalid TTL", async () => {
vi.spyOn(adapter, "eval").mockResolvedValueOnce([0, 0, 3]);
await expect(
checkAuthRateLimit({ request: new Request("https://example.test/login"), action: "login", identifier: null, limit: 2, windowMs: 30_000 })
).resolves.toEqual({ allowed: false, retryAfterSeconds: 30 });
});
});
@@ -1,41 +1,167 @@
import { createHash } from "node:crypto";
import { cache } from "~/utils/cache.server";
import { getTrustedClientIp } from "~/utils/server/IpUtils";
import { MemoryAdapter, type SharedStore } from "@hivegrid/shared-store";
import { getPseudonymousAuthBucketKey, type AuthThrottleAction } from "~/services/auth/auth-rate-limit-key.server";
import { getSharedStore } from "~/shared-store.server";
import { createScopedLogger } from "~/utils/logger.server";
type AuthRateLimitOptions = {
request: Request;
action: "login" | "forgot-password" | "reset-password" | "mfa";
action: AuthThrottleAction;
identifier?: string | null;
limit: number;
windowMs: number;
/** Optional hard cap shared by all trusted clients for one identifier. Null
* keeps the per-client and client/identifier pair buckets while disabling
* the globally poisonable identifier bucket for unauthenticated input. */
identifierLimit?: number | null;
/** Optional hard cap for one trusted client across identifier churn. */
clientLimit?: number;
};
type AuthRateLimitResult =
| { allowed: true }
| { allowed: false; retryAfterSeconds: number };
type AuthRateLimitResult = { allowed: true } | { allowed: false; retryAfterSeconds: number };
export function getAuthRateLimitKey({ request, action, identifier }: Omit<AuthRateLimitOptions, "limit" | "windowMs">) {
// Trusted proxy-set header only; leftmost X-Forwarded-For / X-Client-IP are
// client-spoofable and would let an attacker reset this per-IP auth throttle.
const ipAddress = getTrustedClientIp(request) || "unknown";
const normalizedIdentifier = identifier?.trim().toLowerCase() ?? "";
const digest = createHash("sha256").update(`${action}:${ipAddress}:${normalizedIdentifier}`).digest("hex");
return `auth-rate-limit:${action}:${digest}`;
}
const authRateLimitLogger = createScopedLogger("auth-rate-limit");
const MAX_WINDOW_MS = 24 * 60 * 60 * 1000;
const MAX_LIMIT = 10_000;
const PER_CLIENT_LIMIT_FACTOR = 10;
const PER_IDENTIFIER_LIMIT_FACTOR = 3;
export function checkAuthRateLimit(options: AuthRateLimitOptions): AuthRateLimitResult {
const key = getAuthRateLimitKey(options);
const now = Date.now();
const entry = cache.get(key)?.value as { count: number; resetAt: number } | undefined;
const current = entry && entry.resetAt > now ? entry : { count: 0, resetAt: now + options.windowMs };
const count = current.count + 1;
const AUTH_RATE_LIMIT_SCRIPT = `
local window = tonumber(ARGV[1])
local clientMax = tonumber(ARGV[2])
local identifierMax = tonumber(ARGV[3])
local pairMax = tonumber(ARGV[4])
local hasIdentifier = ARGV[5] == '1'
cache.set(key, { value: { count, resetAt: current.resetAt }, metadata: { createdTime: now } }, { ttl: Math.max(1, current.resetAt - now) });
local function reserve(key)
local current = redis.call('INCR', key)
if current == 1 then
redis.call('EXPIRE', key, window)
end
local ttl = redis.call('TTL', key)
if ttl <= 0 then ttl = window end
return current, ttl
end
if (count > options.limit) {
return { allowed: false, retryAfterSeconds: Math.max(1, Math.ceil((current.resetAt - now) / 1000)) };
local clientCurrent, clientTtl = reserve(KEYS[1])
if clientCurrent > clientMax then
return { 0, clientTtl, 1 }
end
if hasIdentifier then
local identifierCurrent, identifierTtl = reserve(KEYS[2])
if identifierCurrent > identifierMax then
return { 0, identifierTtl, 2 }
end
end
local pairCurrent, pairTtl = reserve(KEYS[3])
if pairCurrent > pairMax then
return { 0, pairTtl, 3 }
end
return { 1, pairTtl, 0 }
`;
MemoryAdapter.registerScript(AUTH_RATE_LIMIT_SCRIPT, async (adapter, keys, args) => {
const windowSeconds = Number.parseInt(args[0] ?? "0", 10);
const clientMax = Number.parseInt(args[1] ?? "0", 10);
const identifierMax = Number.parseInt(args[2] ?? "0", 10);
const pairMax = Number.parseInt(args[3] ?? "0", 10);
const hasIdentifier = args[4] === "1";
const reserve = async (key: string) => {
const current = await adapter.incr(key);
if (current === 1) await adapter.expire(key, windowSeconds);
return current;
};
const clientCurrent = await reserve(keys[0]);
if (clientCurrent > clientMax) return [0, windowSeconds, 1];
if (hasIdentifier) {
const identifierCurrent = await reserve(keys[1]);
if (identifierCurrent > identifierMax) return [0, windowSeconds, 2];
}
const pairCurrent = await reserve(keys[2]);
if (pairCurrent > pairMax) return [0, windowSeconds, 3];
return [1, windowSeconds, 0];
});
return { allowed: true };
let storeFactory: () => SharedStore = () => getSharedStore();
function normalizeWindowSeconds(windowMs: number): number {
if (!Number.isSafeInteger(windowMs) || windowMs <= 0 || windowMs > MAX_WINDOW_MS) {
throw new Error("Auth rate-limit window is outside the supported range.");
}
return Math.ceil(windowMs / 1000);
}
function validateLimit(limit: number): void {
if (!Number.isSafeInteger(limit) || limit <= 0 || limit > MAX_LIMIT) {
throw new Error("Auth rate-limit maximum is outside the supported range.");
}
}
/**
* Returns a stable, pseudonymous bucket key. The HMAC keeps enumerable email
* addresses and client IPs out of Redis keys and diagnostic snapshots.
*/
export function getAuthRateLimitKey({ request, action, identifier }: Omit<AuthRateLimitOptions, "limit" | "windowMs">) {
return getPseudonymousAuthBucketKey({ request, action, identifier });
}
/**
* Atomically reserves an auth attempt in the shared store. Store and
* configuration failures deny the request: losing the distributed throttle
* must never silently turn into an unlimited authentication endpoint.
*/
export async function checkAuthRateLimit(options: AuthRateLimitOptions): Promise<AuthRateLimitResult> {
const safeRetryAfterSeconds = Math.max(1, Math.ceil(Math.min(Math.max(options.windowMs || 0, 1000), MAX_WINDOW_MS) / 1000));
try {
validateLimit(options.limit);
if (options.identifierLimit !== undefined && options.identifierLimit !== null) validateLimit(options.identifierLimit);
if (options.clientLimit !== undefined) validateLimit(options.clientLimit);
const windowSeconds = normalizeWindowSeconds(options.windowMs);
const store = storeFactory();
const normalizedIdentifier = options.identifier?.trim().toLowerCase() ?? "";
const keyPrefix = `rl:auth:v1:${options.action}:${options.limit}:${windowSeconds}`;
const clientKey = getPseudonymousAuthBucketKey({ ...options, scope: "client" });
const identifierKey = getPseudonymousAuthBucketKey({ ...options, scope: "identifier" });
const pairKey = getPseudonymousAuthBucketKey({ ...options, scope: "pair" });
const clientLimit = options.clientLimit ?? Math.min(MAX_LIMIT, options.limit * PER_CLIENT_LIMIT_FACTOR);
const identifierLimit = options.identifierLimit ?? Math.min(MAX_LIMIT, options.limit * PER_IDENTIFIER_LIMIT_FACTOR);
const reserveIdentifierBucket = normalizedIdentifier.length > 0 && options.identifierLimit !== null;
const result = (await store.eval(
AUTH_RATE_LIMIT_SCRIPT,
[`${keyPrefix}:client:${clientKey}`, `${keyPrefix}:identifier:${identifierKey}`, `${keyPrefix}:pair:${pairKey}`],
[String(windowSeconds), String(clientLimit), String(identifierLimit), String(options.limit), reserveIdentifierBucket ? "1" : "0"]
)) as [number | string, number | string, number | string] | undefined;
const allowed = Number(result?.[0]) === 1;
const ttl = Number(result?.[1]);
if (!allowed) {
return {
allowed: false,
retryAfterSeconds: Number.isFinite(ttl) && ttl > 0 ? Math.ceil(ttl) : windowSeconds,
};
}
return { allowed: true };
} catch (error) {
authRateLimitLogger.error(
{
event: "auth.rate_limit.store_unavailable",
action: options.action,
errorName: error instanceof Error ? error.name : "UnknownError",
},
"Auth rate-limit reservation failed; request denied"
);
return { allowed: false, retryAfterSeconds: safeRetryAfterSeconds };
}
}
export function __setAuthRateLimitStoreForTests(store: SharedStore): void {
storeFactory = () => store;
}
export function __resetAuthRateLimitStoreForTests(): void {
storeFactory = () => getSharedStore();
}
@@ -1,7 +1,9 @@
import { beforeEach, describe, expect, it } from "vitest";
import { MemoryAdapter, createSharedStore } from "@hivegrid/shared-store";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cache } from "~/utils/cache.server";
import {
__resetLoginCaptchaGateStoreForTests,
__setLoginCaptchaGateStoreForTests,
clearFailedLogins,
getFailedLoginCount,
LOGIN_CAPTCHA_AFTER_FAILURES,
@@ -10,20 +12,35 @@ import {
} from "./login-captcha-gate.server";
function req() {
return new Request("https://example.test/login");
return new Request("https://example.test/login", { headers: { "cf-connecting-ip": "203.0.113.10" } });
}
describe("login-captcha-gate", () => {
let adapter: MemoryAdapter;
beforeEach(() => {
cache.clear();
adapter = new MemoryAdapter();
__setLoginCaptchaGateStoreForTests(createSharedStore({ namespace: "login-captcha-test", adapter }));
});
it("starts at zero and increments per recorded failure", () => {
afterEach(() => {
__resetLoginCaptchaGateStoreForTests();
vi.restoreAllMocks();
});
it("starts at zero and atomically increments each recorded failure", async () => {
const request = req();
expect(getFailedLoginCount({ request, identifier: "ada@example.test" })).toBe(0);
expect(recordFailedLogin({ request, identifier: "ada@example.test" })).toBe(1);
expect(recordFailedLogin({ request, identifier: "ada@example.test" })).toBe(2);
expect(getFailedLoginCount({ request, identifier: "ada@example.test" })).toBe(2);
await expect(getFailedLoginCount({ request, identifier: "ada@example.test" })).resolves.toBe(0);
await expect(recordFailedLogin({ request, identifier: "ada@example.test" })).resolves.toBe(1);
await expect(recordFailedLogin({ request, identifier: "ada@example.test" })).resolves.toBe(2);
await expect(getFailedLoginCount({ request, identifier: "ada@example.test" })).resolves.toBe(2);
});
it("serializes concurrent failure reservations without losing increments", async () => {
const args = { request: req(), identifier: "ada@example.test" };
const counts = await Promise.all(Array.from({ length: 12 }, () => recordFailedLogin(args)));
expect([...counts].sort((a, b) => a - b)).toEqual(Array.from({ length: 12 }, (_, index) => index + 1));
await expect(getFailedLoginCount(args)).resolves.toBe(12);
});
it("requires a captcha only from the configured failure threshold", () => {
@@ -33,21 +50,74 @@ describe("login-captcha-gate", () => {
expect(loginRequiresCaptcha(LOGIN_CAPTCHA_AFTER_FAILURES + 2)).toBe(true);
});
it("clears the counter on a successful login", () => {
const request = req();
recordFailedLogin({ request, identifier: "ada@example.test" });
recordFailedLogin({ request, identifier: "ada@example.test" });
clearFailedLogins({ request, identifier: "ada@example.test" });
expect(getFailedLoginCount({ request, identifier: "ada@example.test" })).toBe(0);
it("shares failures and successful reset across replicas", async () => {
const args = { request: req(), identifier: "ada@example.test" };
const replicaA = createSharedStore({ namespace: "login-captcha-replicas", adapter });
const replicaB = createSharedStore({ namespace: "login-captcha-replicas", adapter });
__setLoginCaptchaGateStoreForTests(replicaA);
await recordFailedLogin(args);
await recordFailedLogin(args);
await recordFailedLogin(args);
__setLoginCaptchaGateStoreForTests(replicaB);
await expect(getFailedLoginCount(args)).resolves.toBe(3);
await clearFailedLogins(args);
__setLoginCaptchaGateStoreForTests(replicaA);
await expect(getFailedLoginCount(args)).resolves.toBe(0);
});
it("keys per identifier so a different email does not inherit the captcha gate", () => {
it("expires the bounded failure state after its fixed window", async () => {
const startedAt = new Date("2026-05-25T12:00:00.000Z").getTime();
vi.spyOn(Date, "now").mockReturnValue(startedAt);
adapter = new MemoryAdapter();
__setLoginCaptchaGateStoreForTests(createSharedStore({ namespace: "login-captcha-expiry", adapter }));
const args = { request: req(), identifier: "ada@example.test" };
await recordFailedLogin(args);
vi.mocked(Date.now).mockReturnValue(startedAt + 15 * 60 * 1000 + 1);
await expect(getFailedLoginCount(args)).resolves.toBe(0);
});
it("keys per identifier so a different email does not inherit the captcha gate", async () => {
const request = req();
recordFailedLogin({ request, identifier: "ada@example.test" });
recordFailedLogin({ request, identifier: "ada@example.test" });
recordFailedLogin({ request, identifier: "ada@example.test" });
expect(loginRequiresCaptcha(getFailedLoginCount({ request, identifier: "ada@example.test" }))).toBe(true);
expect(getFailedLoginCount({ request, identifier: "mallory@example.test" })).toBe(0);
expect(loginRequiresCaptcha(getFailedLoginCount({ request, identifier: "mallory@example.test" }))).toBe(false);
await recordFailedLogin({ request, identifier: "ada@example.test" });
await recordFailedLogin({ request, identifier: "ada@example.test" });
await recordFailedLogin({ request, identifier: "ada@example.test" });
expect(loginRequiresCaptcha(await getFailedLoginCount({ request, identifier: "ada@example.test" }))).toBe(true);
await expect(getFailedLoginCount({ request, identifier: "mallory@example.test" })).resolves.toBe(0);
});
it("fails closed by requiring captcha when the shared count cannot be read", async () => {
vi.spyOn(adapter, "get").mockRejectedValueOnce(new Error("redis unavailable"));
const count = await getFailedLoginCount({ request: req(), identifier: "ada@example.test" });
expect(loginRequiresCaptcha(count)).toBe(true);
});
it("fails closed when the persisted counter is malformed or negative", async () => {
vi.spyOn(adapter, "get").mockResolvedValueOnce("not-a-number").mockResolvedValueOnce("-1");
await expect(getFailedLoginCount({ request: req(), identifier: "ada@example.test" })).resolves.toBe(LOGIN_CAPTCHA_AFTER_FAILURES);
await expect(getFailedLoginCount({ request: req(), identifier: "ada@example.test" })).resolves.toBe(LOGIN_CAPTCHA_AFTER_FAILURES);
});
it("handles non-Error read failures without leaking the store payload", async () => {
vi.spyOn(adapter, "get").mockRejectedValueOnce("redis-secret");
await expect(getFailedLoginCount({ request: req(), identifier: "ada@example.test" })).resolves.toBe(LOGIN_CAPTCHA_AFTER_FAILURES);
});
it("propagates failed atomic writes so login cannot continue unthrottled", async () => {
vi.spyOn(adapter, "eval").mockRejectedValueOnce("write-secret");
await expect(recordFailedLogin({ request: req(), identifier: "ada@example.test" })).rejects.toBe("write-secret");
});
it("propagates failed resets so a successful login cannot claim the gate was cleared", async () => {
vi.spyOn(adapter, "del").mockRejectedValueOnce("reset-secret");
await expect(clearFailedLogins({ request: req(), identifier: "ada@example.test" })).rejects.toBe("reset-secret");
});
});
@@ -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();
}
@@ -0,0 +1,70 @@
import { loadRequiredWebConfig } from "@hivegrid/config";
import { getAuthUserWithoutPasswordById, getLoginUserByEmail } from "@hivegrid/db/auth-boundary.server";
import { getTranslations } from "~/locale/i18next.server";
import { writeAdminSsoAuditEvent } from "~/modules/admin-sso/audit.server";
import { checkAuthRateLimit } from "~/services/auth/auth-rate-limit.server";
import { AdminFallbackLoginRejected, assertAdminFallbackLoginAllowedForIdentity } from "~/services/auth/admin-fallback.server";
import { issueMagicLink } from "~/services/auth/magic-link.server";
import { validateCSRFToken } from "~/utils/session.server";
import { createScopedLogger } from "~/utils/logger.server";
const MAGIC_LINK_RESPONSE_FLOOR_MS = 1200;
const magicLinkLogger = createScopedLogger("auth.magic-link");
async function waitForMagicLinkResponseFloor(startedAt: number): Promise<void> {
const remaining = MAGIC_LINK_RESPONSE_FLOOR_MS - (Date.now() - startedAt);
if (remaining > 0) {
await new Promise((resolve) => setTimeout(resolve, remaining));
}
}
export async function handleMagicLinkLogin(request: Request, form: FormData): Promise<Response> {
await validateCSRFToken(request, { formData: form });
const email = (form.get("email") ?? "").toString().toLowerCase().trim();
if (!email) {
const { t } = await getTranslations(request);
return Response.json({ magicLinkRequest: true, fieldErrors: { email: t("account.login.magicLinkEmailRequired"), password: undefined } }, { status: 400 });
}
const rateLimit = await checkAuthRateLimit({ request, action: "login", identifier: email, limit: 5, windowMs: 15 * 60 * 1000 });
if (!rateLimit.allowed) {
return Response.json({ magicLinkSent: true, magicLinkEmail: email }, { headers: { "Retry-After": String(rateLimit.retryAfterSeconds) } });
}
const startedAt = Date.now();
if (loadRequiredWebConfig().magicLink.enabled) {
const loginUser = await getLoginUserByEmail(email);
const user = loginUser ? await getAuthUserWithoutPasswordById(loginUser.id) : null;
let identityAllowed = Boolean(user);
if (user) {
try {
assertAdminFallbackLoginAllowedForIdentity(user);
} catch (error) {
if (!(error instanceof AdminFallbackLoginRejected)) {
throw error;
}
identityAllowed = false;
await writeAdminSsoAuditEvent({
action: "admin.login.fallback.failure",
actorAdminUserId: user.admin?.userId,
request,
meta: { reason: error.reason, email, method: "magic-link", stage: "issue" },
});
}
}
if (loginUser && identityAllowed) {
try {
await issueMagicLink({ request, userId: loginUser.id, email, purpose: "login" });
} catch (error) {
// Token issuance and mail delivery are best-effort here. The generic
// response must not reveal whether the account exists.
magicLinkLogger.error({ errorName: error instanceof Error ? error.name : "UnknownError" }, "magic-link issuance failed");
}
}
}
// Apply the same minimum response time to disabled, unknown, denied, and
// successful identities so neither account nor AdminUser status leaks.
await waitForMagicLinkResponseFloor(startedAt);
return Response.json({ magicLinkSent: true, magicLinkEmail: email });
}
@@ -1,12 +1,24 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { consumeMagicLinkToken, createSignedMagicLinkToken, issueMagicLink, verifySignedMagicLinkToken } from "./magic-link.server";
import {
consumeMagicLinkToken,
createSignedMagicLinkToken,
issueMagicLink,
MagicLinkDisabledError,
verifySignedMagicLinkToken,
} from "./magic-link.server";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { getMailTranslator, getMailTranslatorFromRequest } from "~/locale/mail-translator.server";
import { queueTransactionalEmail } from "~/modules/emails/services/TransactionalEmailQueue.server";
import { db } from "~/utils/db.server";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
vi.mock("@hivegrid/config", () => ({
loadRequiredWebConfig: vi.fn(() => ({ cryptoSecret: "test-secret", sessionSecret: "session-secret" })),
loadRequiredWebConfig: vi.fn(() => ({
cryptoSecret: "test-secret",
sessionSecret: "session-secret",
magicLink: { enabled: true },
})),
}));
vi.mock("~/utils/db.server", () => ({
@@ -14,7 +26,7 @@ vi.mock("~/utils/db.server", () => ({
magicLinkToken: {
create: vi.fn(),
findUnique: vi.fn(),
update: vi.fn(),
updateMany: vi.fn(),
},
user: {
findUnique: vi.fn(),
@@ -45,11 +57,17 @@ const getMailTranslatorFromRequestMock = vi.mocked(getMailTranslatorFromRequest)
const queueTransactionalEmailMock = vi.mocked(queueTransactionalEmail);
const magicLinkTokenCreateMock = vi.mocked(db.magicLinkToken.create);
const magicLinkTokenFindUniqueMock = vi.mocked(db.magicLinkToken.findUnique);
const magicLinkTokenUpdateMock = vi.mocked(db.magicLinkToken.update);
const magicLinkTokenUpdateManyMock = vi.mocked(db.magicLinkToken.updateMany);
const userFindUniqueMock = vi.mocked(db.user.findUnique);
const loadRequiredWebConfigMock = vi.mocked(loadRequiredWebConfig);
beforeEach(() => {
vi.clearAllMocks();
loadRequiredWebConfigMock.mockReturnValue({
cryptoSecret: "test-secret",
sessionSecret: "session-secret",
magicLink: { enabled: true },
} as ReturnType<typeof loadRequiredWebConfig>);
getAppConfigurationMock.mockResolvedValue({
app: { name: "Acme Portal" },
email: { fromName: "Acme Support", supportEmail: "support@acme.test" },
@@ -57,7 +75,28 @@ beforeEach(() => {
} as Awaited<ReturnType<typeof getAppConfiguration>>);
getMailTranslatorMock.mockResolvedValue({
locale: "de",
t: (key, vars) => (key === "magicLink.subject" ? `Dein Anmeldelink für ${vars?.productName}` : key),
t: (key, vars) => {
const copy: Record<string, string> = {
"magicLink.subject": `Dein Anmeldelink für ${vars?.productName}`,
"magicLink.previewText": `Sicher bei ${vars?.productName} anmelden`,
"magicLink.eyebrow": "Anmeldelink",
"magicLink.title_named": `Hallo, ${vars?.name}!`,
"magicLink.title": "Hallo!",
"magicLink.intro": `Nutze diesen Link, um dich bei deinem ${vars?.productName}-Konto anzumelden.`,
"magicLink.actionLabel": "Anmelden",
"magicLink.ignoreIfUnrequested": "Wenn du diesen Anmeldelink nicht angefordert hast, kannst du diese E-Mail ignorieren.",
"magicLink.outro": `Dieser Link läuft in ${vars?.expiresInMinutes} Minuten ab und kann nur einmal verwendet werden.`,
"common.signoff.thanks": "Danke,",
"common.legal.privacyLabel": "Datenschutz",
"common.legal.termsLabel": "AGB",
"common.legal.imprintLabel": "Impressum",
"common.legal.unsubscribeLabel": "Abmelden",
"common.support.htmlBefore": "Bei Fragen kannst du uns gerne",
"common.support.emailLinkLabel": "eine E-Mail schreiben",
"common.support.htmlAfter": ".",
};
return copy[key] ?? key;
},
});
getMailTranslatorFromRequestMock.mockResolvedValue({
locale: "en",
@@ -66,11 +105,30 @@ beforeEach(() => {
queueTransactionalEmailMock.mockResolvedValue({ enqueued: true, jobId: "job_1" });
magicLinkTokenCreateMock.mockResolvedValue({ id: "token_1" } as Awaited<ReturnType<typeof db.magicLinkToken.create>>);
magicLinkTokenFindUniqueMock.mockResolvedValue(null);
magicLinkTokenUpdateMock.mockResolvedValue({ id: "token_1" } as Awaited<ReturnType<typeof db.magicLinkToken.update>>);
magicLinkTokenUpdateManyMock.mockResolvedValue({ count: 1 });
userFindUniqueMock.mockResolvedValue({ locale: "de" } as Awaited<ReturnType<typeof db.user.findUnique>>);
});
describe("issueMagicLink", () => {
it("does not persist or send a token while the provider is disabled", async () => {
loadRequiredWebConfigMock.mockReturnValue({
cryptoSecret: "test-secret",
sessionSecret: "session-secret",
magicLink: { enabled: false },
} as ReturnType<typeof loadRequiredWebConfig>);
await expect(
issueMagicLink({
request: new Request("https://example.com/login"),
userId: "user_1",
email: "ada@example.com",
})
).rejects.toBeInstanceOf(MagicLinkDisabledError);
expect(magicLinkTokenCreateMock).not.toHaveBeenCalled();
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
});
it("queues a magic-link mail rendered through the React-Email pipeline", async () => {
const result = await issueMagicLink({
request: new Request("https://example.com/forgot-password"),
@@ -81,7 +139,7 @@ describe("issueMagicLink", () => {
});
expect(result.token).toMatch(/\./);
// Translator is resolved against the user's locale for the subject.
// Translator is resolved against the user's locale for the complete mail.
expect(getMailTranslatorMock).toHaveBeenCalledWith("de");
expect(getMailTranslatorFromRequestMock).not.toHaveBeenCalled();
expect(queueTransactionalEmailMock).toHaveBeenCalledOnce();
@@ -101,11 +159,32 @@ describe("issueMagicLink", () => {
);
const queued = queueTransactionalEmailMock.mock.calls[0]?.[0];
expect(queued?.body).toContain("Click the button below to sign in to your Acme Portal account. No password required.");
expect(queued?.body).toContain("Sign in");
expect(queued?.body).toContain("This link expires in 15 minutes");
expect(queued?.body).toContain("Nutze diesen Link, um dich bei deinem Acme Portal-Konto anzumelden.");
expect(queued?.body).toContain("Anmelden");
expect(queued?.body).toContain("Dieser Link läuft in 15 Minuten ab");
expect(queued?.body).toContain("Datenschutz");
expect(queued?.body).toContain('<html lang="de">');
expect(queued?.body).not.toContain("Click the button below");
expect(queued?.body).not.toContain("This link expires");
expect(queued?.body).not.toContain("{i18nT(");
});
it("reuses an already-bound matching user RLS context", async () => {
magicLinkTokenCreateMock.mockImplementationOnce(async () => {
expect(getRlsExecutionContext()).toEqual({ userId: "user_1" });
return { id: "token_1" } as Awaited<ReturnType<typeof db.magicLinkToken.create>>;
});
await runWithRlsContext({ userId: "user_1" }, () =>
issueMagicLink({
request: new Request("https://example.com/login"),
userId: "user_1",
email: "ada@example.com",
}),
);
expect(getRlsExecutionContext()).toBeNull();
});
});
describe("signed magic-link tokens", () => {
@@ -130,6 +209,19 @@ describe("signed magic-link tokens", () => {
});
describe("consumeMagicLinkToken", () => {
it("does not read or consume outstanding tokens while the provider is disabled", async () => {
const issued = createSignedMagicLinkToken({ userId: "user_1", tokenId: "token_1" });
loadRequiredWebConfigMock.mockReturnValue({
cryptoSecret: "test-secret",
sessionSecret: "session-secret",
magicLink: { enabled: false },
} as ReturnType<typeof loadRequiredWebConfig>);
await expect(consumeMagicLinkToken(issued.token, { expectedPurpose: "login" })).resolves.toEqual({ ok: false, reason: "invalid" });
expect(magicLinkTokenFindUniqueMock).not.toHaveBeenCalled();
expect(magicLinkTokenUpdateManyMock).not.toHaveBeenCalled();
});
it("consumes a valid matching token exactly once", async () => {
const now = new Date("2026-05-19T12:00:00.000Z");
const issued = createSignedMagicLinkToken({ userId: "user_1", tokenId: "token_1", now, purpose: "login" });
@@ -147,19 +239,47 @@ describe("consumeMagicLinkToken", () => {
tokenId: "token_1",
purpose: "login",
});
expect(magicLinkTokenUpdateMock).toHaveBeenCalledWith({
where: { id: "token_1" },
expect(magicLinkTokenUpdateManyMock).toHaveBeenCalledWith({
where: {
id: "token_1",
userId: "user_1",
tokenHash: issued.tokenHash,
consumedAt: null,
expiresAt: { gt: now },
},
data: { consumedAt: now },
});
});
it("allows only one winner when concurrent requests race to consume the same token", async () => {
const now = new Date("2026-05-19T12:00:00.000Z");
const issued = createSignedMagicLinkToken({ userId: "user_1", tokenId: "token_1", now });
magicLinkTokenFindUniqueMock.mockResolvedValue({
id: "token_1",
userId: "user_1",
tokenHash: issued.tokenHash,
expiresAt: issued.expiresAt,
consumedAt: null,
} as Awaited<ReturnType<typeof db.magicLinkToken.findUnique>>);
magicLinkTokenUpdateManyMock.mockResolvedValueOnce({ count: 1 }).mockResolvedValueOnce({ count: 0 });
const results = await Promise.all([consumeMagicLinkToken(issued.token, { now }), consumeMagicLinkToken(issued.token, { now })]);
expect(results).toEqual(
expect.arrayContaining([
{ ok: true, userId: "user_1", tokenId: "token_1", purpose: "login" },
{ ok: false, reason: "replayed" },
])
);
});
it("rejects unknown or mismatched stored tokens without consuming them", async () => {
const now = new Date("2026-05-19T12:00:00.000Z");
const issued = createSignedMagicLinkToken({ userId: "user_1", tokenId: "token_1", now });
magicLinkTokenFindUniqueMock.mockResolvedValue(null);
await expect(consumeMagicLinkToken(issued.token, { now })).resolves.toEqual({ ok: false, reason: "not-found" });
expect(magicLinkTokenUpdateMock).not.toHaveBeenCalled();
expect(magicLinkTokenUpdateManyMock).not.toHaveBeenCalled();
});
it("rejects expired signed payloads before reading the database", async () => {
@@ -169,7 +289,7 @@ describe("consumeMagicLinkToken", () => {
await expect(consumeMagicLinkToken(issued.token, { now })).resolves.toEqual({ ok: false, reason: "expired" });
expect(magicLinkTokenFindUniqueMock).not.toHaveBeenCalled();
expect(magicLinkTokenUpdateMock).not.toHaveBeenCalled();
expect(magicLinkTokenUpdateManyMock).not.toHaveBeenCalled();
});
it("rejects stored tokens that expired after a valid signed payload was issued", async () => {
@@ -189,7 +309,7 @@ describe("consumeMagicLinkToken", () => {
} as Awaited<ReturnType<typeof db.magicLinkToken.findUnique>>);
await expect(consumeMagicLinkToken(issued.token, { now })).resolves.toEqual({ ok: false, reason: "expired" });
expect(magicLinkTokenUpdateMock).not.toHaveBeenCalled();
expect(magicLinkTokenUpdateManyMock).not.toHaveBeenCalled();
});
it("rejects replayed tokens before writing a new consumedAt", async () => {
@@ -204,7 +324,7 @@ describe("consumeMagicLinkToken", () => {
} as Awaited<ReturnType<typeof db.magicLinkToken.findUnique>>);
await expect(consumeMagicLinkToken(issued.token, { now })).resolves.toEqual({ ok: false, reason: "replayed" });
expect(magicLinkTokenUpdateMock).not.toHaveBeenCalled();
expect(magicLinkTokenUpdateManyMock).not.toHaveBeenCalled();
});
it("rejects purpose mismatches without consuming the token", async () => {
@@ -219,6 +339,6 @@ describe("consumeMagicLinkToken", () => {
} as Awaited<ReturnType<typeof db.magicLinkToken.findUnique>>);
await expect(consumeMagicLinkToken(issued.token, { now, expectedPurpose: "login" })).resolves.toEqual({ ok: false, reason: "purpose-mismatch" });
expect(magicLinkTokenUpdateMock).not.toHaveBeenCalled();
expect(magicLinkTokenUpdateManyMock).not.toHaveBeenCalled();
});
});
@@ -7,10 +7,25 @@ import { getAbsoluteUrl } from "~/utils/url.server";
import { queueTransactionalEmail } from "~/modules/emails/services/TransactionalEmailQueue.server";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { getMailTranslator, getMailTranslatorFromRequest } from "~/locale/mail-translator.server";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { localizedMailChrome } from "~/modules/emails/utils/LocalizedMailChrome";
export const MAGIC_LINK_TOKEN_TTL_MINUTES = 15;
const MAGIC_LINK_TOKEN_VERSION = "v1";
export class MagicLinkDisabledError extends Error {
constructor() {
super("Magic-link authentication is disabled.");
this.name = "MagicLinkDisabledError";
}
}
function assertMagicLinkEnabled(): void {
if (!loadRequiredWebConfig().magicLink.enabled) {
throw new MagicLinkDisabledError();
}
}
export type MagicLinkPurpose = "login" | "invitation" | "reset";
type MagicLinkPayload = {
@@ -158,6 +173,29 @@ export async function issueMagicLink({
redirectPath?: string;
now?: Date;
purpose?: MagicLinkPurpose;
}) {
// Keep the provider flag at the side-effect boundary as defense in depth:
// no caller can create a token or enqueue mail while the provider is off.
assertMagicLinkEnabled();
return withUserRlsContext(userId, () => issueMagicLinkScoped({ request, userId, email, name, redirectPath, now, purpose }));
}
async function issueMagicLinkScoped({
request,
userId,
email,
name,
redirectPath,
now,
purpose,
}: {
request: Request;
userId: string;
email: string;
name?: string | null;
redirectPath: string;
now: Date;
purpose: MagicLinkPurpose;
}) {
const token = createSignedMagicLinkToken({ userId, now, purpose });
await db.magicLinkToken.create({
@@ -174,19 +212,35 @@ export async function issueMagicLink({
const mailTranslator = await getMagicLinkMailTranslator(request, userId);
const appConfiguration = await getAppConfiguration({ request });
const brand = buildBrand(resolveTransactionalBrandTokens(toBrandConfiguration(appConfiguration)));
const { html } = renderTransactionalEmail("magic-link", {
const copyVariables = {
productName: brand.productName,
name: name ?? "",
expiresInMinutes: MAGIC_LINK_TOKEN_TTL_MINUTES,
};
const { html, text } = renderTransactionalEmail("magic-link", {
brand,
...localizedMailChrome(mailTranslator.t, mailTranslator.locale),
recipientName: name ?? undefined,
actionUrl,
expiresInMinutes: MAGIC_LINK_TOKEN_TTL_MINUTES,
subject: mailTranslator.t("magicLink.subject", copyVariables),
previewText: mailTranslator.t("magicLink.previewText", copyVariables),
eyebrow: mailTranslator.t("magicLink.eyebrow", copyVariables),
title: mailTranslator.t(name ? "magicLink.title_named" : "magicLink.title", copyVariables),
intro: mailTranslator.t("magicLink.intro", copyVariables),
actionLabel: mailTranslator.t("magicLink.actionLabel", copyVariables),
outro: mailTranslator.t("magicLink.ignoreIfUnrequested", copyVariables),
expiresText: mailTranslator.t("magicLink.outro", copyVariables),
signoffThanks: mailTranslator.t("common.signoff.thanks"),
});
const subject = mailTranslator.t("magicLink.subject", { productName: brand.productName });
const subject = mailTranslator.t("magicLink.subject", copyVariables);
await queueTransactionalEmail({
to: email,
alias: "magic-link",
subject,
body: html,
text,
userId,
data: emailData,
priorityOverride: "critical",
@@ -199,6 +253,11 @@ export async function issueMagicLink({
}
export async function consumeMagicLinkToken(token: string, options: { now?: Date; expectedPurpose?: MagicLinkPurpose } = {}): Promise<MagicLinkConsumeResult> {
// Disabled providers must not consume outstanding tokens. Returning the
// generic invalid reason avoids leaking runtime configuration to clients.
if (!loadRequiredWebConfig().magicLink.enabled) {
return { ok: false, reason: "invalid" };
}
const now = options.now ?? new Date();
const payload = verifySignedMagicLinkToken(token);
if (!payload) {
@@ -208,6 +267,15 @@ export async function consumeMagicLinkToken(token: string, options: { now?: Date
return { ok: false, reason: "expired" };
}
return runWithRlsContext({ userId: payload.sub }, () => consumeMagicLinkTokenScoped(token, payload, now, options));
}
async function consumeMagicLinkTokenScoped(
token: string,
payload: MagicLinkPayload,
now: Date,
options: { expectedPurpose?: MagicLinkPurpose }
): Promise<MagicLinkConsumeResult> {
const tokenHash = hashToken(token);
const storedToken = await db.magicLinkToken.findUnique({ where: { id: payload.jti } });
if (!storedToken || storedToken.userId !== payload.sub || storedToken.tokenHash !== tokenHash) {
@@ -227,10 +295,26 @@ export async function consumeMagicLinkToken(token: string, options: { now?: Date
return { ok: false, reason: "purpose-mismatch" };
}
await db.magicLinkToken.update({
where: { id: payload.jti },
const consumed = await db.magicLinkToken.updateMany({
where: {
id: payload.jti,
userId: payload.sub,
tokenHash,
consumedAt: null,
expiresAt: { gt: now },
},
data: { consumedAt: now },
});
if (consumed.count !== 1) {
return { ok: false, reason: "replayed" };
}
return { ok: true, userId: payload.sub, tokenId: payload.jti, purpose: actualPurpose };
}
function withUserRlsContext<T>(userId: string, operation: () => T): T {
if (getRlsExecutionContext()?.userId) {
return operation();
}
return runWithRlsContext({ userId }, operation);
}
@@ -12,7 +12,7 @@
// AuthService.loginFromRequest after validatePassword runs in
// non-throwing mode against the plaintext the user just submitted.
// 2. A cookie `pwPolicyRemindAfter=<unix-millis>` that the "Remind me
// in 7 days" button sets via the api.password-policy-remind resource
// in 7 days" button sets via the auth.password-policy-remind resource
// route. While the timestamp is still in the future the banner stays
// hidden even when the session flag is on.
//
@@ -1,13 +1,7 @@
// @vitest-environment node
import { createHash } from "node:crypto";
import { describe, expect, test, vi } from "vitest";
import {
assertPasswordPolicy,
isPasswordPwned,
loadPasswordPolicy,
validatePassword,
validatePasswordPolicy,
} from "./password-policy.server.js";
import { assertPasswordPolicy, isPasswordPwned, loadPasswordPolicy, validatePassword, validatePasswordPolicy } from "./password-policy.server.js";
function sha1Upper(value: string): string {
return createHash("sha1").update(value).digest("hex").toUpperCase();
@@ -123,6 +117,19 @@ describe("validatePassword", () => {
expect(result.hibpBypassed).toBe(true);
});
test("HIBP requests have a real abort signal, reject redirects and bound response bodies", async () => {
const fetcher = vi.fn<typeof fetch>(async () => new Response("x".repeat(128 * 1024 + 1)));
const policy = { ...ALL_FLAGS_OFF, hibpCheck: true };
const result = await validatePassword("Long-Enough-Password", {}, { policy, fetcher });
expect(result.hibpBypassed).toBe(true);
expect(fetcher).toHaveBeenCalledWith(
expect.stringMatching(/^https:\/\/api\.pwnedpasswords\.com\/range\//u),
expect.objectContaining({ redirect: "error", signal: expect.any(AbortSignal) })
);
});
test("Unicode passwords are length-counted by JS string length (sufficient for the policy)", async () => {
const policy = { ...ALL_FLAGS_OFF, minLength: 8 };
const result = await validatePassword("Pässwört✓123", {}, { policy });
@@ -10,7 +10,8 @@ import { createHash } from "node:crypto";
const HIBP_API_BASE = "https://api.pwnedpasswords.com/range/";
const HIBP_TIMEOUT_MS = 3000;
const ABSOLUTE_MAX_LENGTH = 1024;
const HIBP_RESPONSE_MAX_BYTES = 128 * 1024;
export const PASSWORD_ABSOLUTE_MAX_LENGTH = 1024;
export type PasswordPolicyConfig = {
minLength: number;
@@ -88,8 +89,8 @@ export async function validatePassword(
if (plain.length < policy.minLength) {
errors.push({ code: "auth.password.errors.tooShort", args: { minLength: policy.minLength } });
}
if (plain.length > ABSOLUTE_MAX_LENGTH) {
errors.push({ code: "auth.password.errors.tooLong", args: { maxLength: ABSOLUTE_MAX_LENGTH } });
if (plain.length > PASSWORD_ABSOLUTE_MAX_LENGTH) {
errors.push({ code: "auth.password.errors.tooLong", args: { maxLength: PASSWORD_ABSOLUTE_MAX_LENGTH } });
}
if (policy.requireUpper && !/[A-Z]/.test(plain)) {
errors.push({ code: "auth.password.errors.missingUpper" });
@@ -136,7 +137,14 @@ async function checkHibp(plain: string, maxOccurrences: number, fetcher?: typeof
let response: Response;
try {
response = await withTimeout(usedFetcher(url, { headers: { "Add-Padding": "true" } }), HIBP_TIMEOUT_MS);
response = await withTimeout(
usedFetcher(url, {
headers: { "Add-Padding": "true" },
redirect: "error",
signal: AbortSignal.timeout(HIBP_TIMEOUT_MS),
}),
HIBP_TIMEOUT_MS
);
} catch {
return "bypassed";
}
@@ -144,7 +152,7 @@ async function checkHibp(plain: string, maxOccurrences: number, fetcher?: typeof
let body: string;
try {
body = await response.text();
body = await readLimitedText(response, HIBP_RESPONSE_MAX_BYTES);
} catch {
return "bypassed";
}
@@ -159,6 +167,37 @@ async function checkHibp(plain: string, maxOccurrences: number, fetcher?: typeof
return "clean";
}
async function readLimitedText(response: Response, maxBytes: number): Promise<string> {
const contentLength = response.headers.get("content-length");
if (contentLength && /^\d+$/u.test(contentLength) && Number(contentLength) > maxBytes) {
await response.body?.cancel().catch(() => undefined);
throw new Error("hibp_response_too_large");
}
if (!response.body) return "";
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let totalBytes = 0;
while (true) {
const chunk = await reader.read();
if (chunk.done) break;
totalBytes += chunk.value.byteLength;
if (totalBytes > maxBytes) {
await reader.cancel().catch(() => undefined);
throw new Error("hibp_response_too_large");
}
chunks.push(chunk.value);
}
const bytes = new Uint8Array(totalBytes);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
return new TextDecoder().decode(bytes);
}
async function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<T>((_, reject) => {
@@ -0,0 +1,74 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const config = {
nodeEnv: "test",
routing: { appBaseDomain: "example.test", protocol: "https" },
sessionSecret: "registration-recovery-test-secret-0123456789",
};
vi.mock("@hivegrid/config", async () => {
const actual = await vi.importActual<typeof import("@hivegrid/config")>("@hivegrid/config");
return { ...actual, loadRequiredWebConfig: () => config };
});
import {
clearRegistrationResendRecovery,
commitRegistrationResendRecovery,
readRegistrationResendRecovery,
REGISTRATION_RESEND_RECOVERY_COOKIE,
REGISTRATION_RESEND_RECOVERY_TTL_MS,
} from "./registration-resend-recovery.server";
const CREATION_REQUEST_KEY = "d7077797-054b-497a-b1ce-8e4f36257a96";
const NOW = Date.parse("2026-07-15T12:00:00.000Z");
describe("registration resend recovery cookie", () => {
beforeEach(() => {
config.sessionSecret = "registration-recovery-test-secret-0123456789";
});
it("survives reloads and tabs as a signed HttpOnly host-only 24-hour binding", async () => {
const setCookie = await commitRegistrationResendRecovery({ email: " Ada@Example.TEST ", creationRequestKey: CREATION_REQUEST_KEY }, NOW);
const cookie = setCookie.split(";", 1)[0];
const request = new Request("https://example.test/register", { headers: { Cookie: cookie } });
await expect(readRegistrationResendRecovery(request, NOW + 1_000)).resolves.toEqual({
email: "ada@example.test",
creationRequestKey: CREATION_REQUEST_KEY,
issuedAt: NOW,
});
expect(setCookie).toContain(`${REGISTRATION_RESEND_RECOVERY_COOKIE}=`);
expect(setCookie).toContain("HttpOnly");
expect(setCookie).toContain("SameSite=Lax");
expect(setCookie).toContain("Secure");
expect(setCookie).toContain("Path=/");
expect(setCookie).toContain("Max-Age=86400");
});
it("rejects tampering, another signing key, and an expired server-side timestamp", async () => {
const setCookie = await commitRegistrationResendRecovery({ email: "ada@example.test", creationRequestKey: CREATION_REQUEST_KEY }, NOW);
const cookie = setCookie.split(";", 1)[0]!;
const tampered = `${cookie.slice(0, -1)}${cookie.endsWith("a") ? "b" : "a"}`;
await expect(readRegistrationResendRecovery(new Request("https://example.test/register", { headers: { Cookie: tampered } }), NOW)).resolves.toBeNull();
config.sessionSecret = "another-registration-recovery-secret-012345678";
await expect(readRegistrationResendRecovery(new Request("https://example.test/register", { headers: { Cookie: cookie } }), NOW)).resolves.toBeNull();
config.sessionSecret = "registration-recovery-test-secret-0123456789";
await expect(
readRegistrationResendRecovery(new Request("https://example.test/register", { headers: { Cookie: cookie } }), NOW + REGISTRATION_RESEND_RECOVERY_TTL_MS)
).resolves.toBeNull();
});
it("expires the same host-only cookie when recovery completes or restarts", async () => {
const cleared = await clearRegistrationResendRecovery();
expect(cleared).toContain(`${REGISTRATION_RESEND_RECOVERY_COOKIE}=`);
expect(cleared).toContain("Max-Age=0");
expect(cleared).toContain("HttpOnly");
expect(cleared).toContain("SameSite=Lax");
expect(cleared).toContain("Secure");
expect(cleared).toContain("Path=/");
});
});
@@ -0,0 +1,94 @@
import { createCookie } from "react-router";
import { loadRequiredWebConfig, resolveHostOnlyCookiePolicy } from "@hivegrid/config";
import { isSignupCreationRequestKey } from "~/domain/tenant-bootstrap/signupCreationRequestKey.server";
export const REGISTRATION_RESEND_RECOVERY_TTL_MS = 24 * 60 * 60 * 1000;
export const REGISTRATION_RESEND_RECOVERY_COOKIE = "__Host-hivegrid_registration_resend";
export const LOCAL_REGISTRATION_RESEND_RECOVERY_COOKIE = "hivegrid_registration_resend";
const CLOCK_SKEW_MS = 60 * 1000;
const MAX_EMAIL_LENGTH = 320;
export type RegistrationResendRecovery = {
email: string;
creationRequestKey: string;
issuedAt: number;
};
function getRecoveryCookie() {
const config = loadRequiredWebConfig();
if (!config.sessionSecret) {
throw new Error("SESSION_SECRET is required for registration resend recovery cookies");
}
const policy = resolveHostOnlyCookiePolicy({
nodeEnv: config.nodeEnv,
routing: config.routing,
secureName: REGISTRATION_RESEND_RECOVERY_COOKIE,
localName: LOCAL_REGISTRATION_RESEND_RECOVERY_COOKIE,
maxAge: Math.ceil(REGISTRATION_RESEND_RECOVERY_TTL_MS / 1000),
});
return createCookie(policy.name, {
httpOnly: policy.httpOnly,
sameSite: policy.sameSite,
path: policy.path,
secure: policy.secure,
maxAge: policy.maxAge,
secrets: [config.sessionSecret],
});
}
export async function readRegistrationResendRecovery(request: Request, now = Date.now()): Promise<RegistrationResendRecovery | null> {
try {
const parsed: unknown = await getRecoveryCookie().parse(request.headers.get("Cookie"));
if (!isRecoveryPayload(parsed, now)) return null;
return {
email: normalizeEmail(parsed.email),
creationRequestKey: parsed.creationRequestKey,
issuedAt: parsed.issuedAt,
};
} catch {
return null;
}
}
export async function commitRegistrationResendRecovery(
input: Pick<RegistrationResendRecovery, "email" | "creationRequestKey">,
now = Date.now()
): Promise<string> {
const email = normalizeEmail(input.email);
if (!isValidEmailBinding(email) || !isSignupCreationRequestKey(input.creationRequestKey)) {
throw new Error("Registration resend recovery payload is invalid");
}
return await getRecoveryCookie().serialize({
email,
creationRequestKey: input.creationRequestKey,
issuedAt: now,
} satisfies RegistrationResendRecovery);
}
export async function clearRegistrationResendRecovery(): Promise<string> {
return await getRecoveryCookie().serialize("", { maxAge: 0 });
}
function isRecoveryPayload(value: unknown, now: number): value is RegistrationResendRecovery {
if (!value || typeof value !== "object") return false;
const payload = value as Partial<RegistrationResendRecovery>;
const email = typeof payload.email === "string" ? normalizeEmail(payload.email) : "";
return (
isValidEmailBinding(email) &&
typeof payload.creationRequestKey === "string" &&
isSignupCreationRequestKey(payload.creationRequestKey) &&
typeof payload.issuedAt === "number" &&
Number.isFinite(payload.issuedAt) &&
payload.issuedAt <= now + CLOCK_SKEW_MS &&
now - payload.issuedAt < REGISTRATION_RESEND_RECOVERY_TTL_MS
);
}
function normalizeEmail(value: string): string {
return value.trim().toLowerCase();
}
function isValidEmailBinding(value: string): boolean {
return value.length > 0 && value.length <= MAX_EMAIL_LENGTH && value.includes("@");
}
@@ -0,0 +1,200 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createSharedStore, MemoryAdapter } from "@hivegrid/shared-store";
import { createHash } from "node:crypto";
vi.mock("@hivegrid/config", async (importOriginal) => {
const actual = await importOriginal<typeof import("@hivegrid/config")>();
return {
...actual,
loadRequiredWebConfig: vi.fn(() => ({
routing: {
protocol: "https",
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
apiHost: "api.example.test",
appBaseDomain: "example.test",
},
})),
};
});
vi.mock("~/shared-store.server", () => ({ getSharedStore: vi.fn() }));
vi.mock("~/utils/session.server", () => ({ createUserSession: vi.fn() }));
import { createUserSession } from "~/utils/session.server";
import {
__resetSessionHandoffStoreForTests,
__setSessionHandoffStoreForTests,
consumeSessionHandoff,
createSessionHandoffRedirect,
} from "./session-handoff.server";
const userAgent = "HiveGrid security test browser";
const session = {
userId: "target-user-1",
lightOrDarkMode: "dark",
lng: "de",
cookies: [],
impersonatingFromAdminUserId: "admin-user-1",
impersonatingFromAdminEmail: "admin@example.test",
impersonatingStartedAt: "2026-07-12T06:00:00.000Z",
};
let store: ReturnType<typeof createSharedStore>;
function request(url: string, agent = userAgent) {
return new Request(url, { headers: { "user-agent": agent } });
}
function codeFrom(response: Response) {
return new URL(response.headers.get("Location")!).searchParams.get("code")!;
}
beforeEach(() => {
vi.clearAllMocks();
store = createSharedStore({ namespace: "session-handoff-test", adapter: new MemoryAdapter() });
__setSessionHandoffStoreForTests(store);
vi.mocked(createUserSession).mockResolvedValue(
new Response(null, {
status: 302,
headers: {
Location: "https://app.example.test/acme/dashboard",
"Set-Cookie": "__Host-hivegrid_app_session=signed; Path=/; Secure; HttpOnly",
},
}) as never
);
});
afterEach(() => {
vi.useRealTimers();
__resetSessionHandoffStoreForTests();
});
describe("cross-host session handoff", () => {
it("uses a short opaque code and consumes it once on the app host", async () => {
const issued = await createSessionHandoffRedirect({
request: request("https://admin.example.test/accounts/users"),
session,
redirectTo: "https://app.example.test/acme/dashboard",
});
const location = issued.headers.get("Location")!;
const code = codeFrom(issued);
expect(location).toMatch(/^https:\/\/app\.example\.test\/auth\/session-handoff\?code=[A-Za-z0-9_-]{43}$/);
expect(location).not.toContain(session.userId);
expect(location).not.toContain(session.impersonatingFromAdminUserId);
expect(location).not.toContain(session.impersonatingFromAdminEmail);
expect(issued.headers.get("Cache-Control")).toBe("no-store");
expect(issued.headers.get("Referrer-Policy")).toBe("no-referrer");
const completed = await consumeSessionHandoff(request(`https://app.example.test/auth/session-handoff?code=${code}`), code);
expect(completed?.headers.get("Set-Cookie")).toContain("__Host-hivegrid_app_session=");
expect(completed?.headers.get("Cache-Control")).toBe("no-store");
expect(completed?.headers.get("Referrer-Policy")).toBe("no-referrer");
expect(createUserSession).toHaveBeenCalledWith(
expect.objectContaining({
userId: "target-user-1",
impersonatingFromAdminUserId: "admin-user-1",
impersonatingFromAdminEmail: "admin@example.test",
}),
"https://app.example.test/acme/dashboard",
{ request: expect.any(Request), rotate: true }
);
await expect(consumeSessionHandoff(request("https://app.example.test/auth/session-handoff"), code)).resolves.toBeNull();
});
it("allows exactly one winner under concurrent consumption", async () => {
const issued = await createSessionHandoffRedirect({
request: request("https://admin.example.test/accounts/users"),
session,
redirectTo: "https://app.example.test/acme/dashboard",
});
const code = codeFrom(issued);
const results = await Promise.all([
consumeSessionHandoff(request("https://app.example.test/auth/session-handoff"), code),
consumeSessionHandoff(request("https://app.example.test/auth/session-handoff"), code),
]);
expect(results.filter(Boolean)).toHaveLength(1);
expect(createUserSession).toHaveBeenCalledTimes(1);
});
it("consumes and rejects a code presented by a different browser", async () => {
const issued = await createSessionHandoffRedirect({
request: request("https://admin.example.test/accounts/users"),
session,
redirectTo: "https://app.example.test/acme/dashboard",
});
const code = codeFrom(issued);
await expect(consumeSessionHandoff(request("https://app.example.test/auth/session-handoff", "different-browser"), code)).resolves.toBeNull();
await expect(consumeSessionHandoff(request("https://app.example.test/auth/session-handoff"), code)).resolves.toBeNull();
expect(createUserSession).not.toHaveBeenCalled();
});
it("binds consumption to the canonical app origin without burning the code on another host", async () => {
const issued = await createSessionHandoffRedirect({
request: request("https://admin.example.test/accounts/users"),
session,
redirectTo: "https://app.example.test/acme/dashboard",
});
const code = codeFrom(issued);
await expect(consumeSessionHandoff(request("https://admin.example.test/auth/session-handoff"), code)).resolves.toBeNull();
await expect(consumeSessionHandoff(request("https://app.example.test/auth/session-handoff"), code)).resolves.toBeInstanceOf(Response);
expect(createUserSession).toHaveBeenCalledTimes(1);
});
it("rejects a Redis payload whose HMAC envelope was tampered with", async () => {
const issued = await createSessionHandoffRedirect({
request: request("https://admin.example.test/accounts/users"),
session,
redirectTo: "https://app.example.test/acme/dashboard",
});
const code = codeFrom(issued);
const hash = createHash("sha256").update(code).digest("hex");
await store.set(
`auth:session-handoff:${hash}`,
JSON.stringify({
payload: JSON.stringify({ ...session, userId: "attacker-selected-user" }),
signature: "forged-signature",
}),
{ ttlSeconds: 60 }
);
await expect(consumeSessionHandoff(request("https://app.example.test/auth/session-handoff"), code)).resolves.toBeNull();
expect(createUserSession).not.toHaveBeenCalled();
});
it("fails closed for expired codes and non-app redirect targets", async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-07-12T06:00:00.000Z"));
const issued = await createSessionHandoffRedirect({
request: request("https://admin.example.test/accounts/users"),
session,
redirectTo: "https://app.example.test/acme/dashboard",
});
const code = codeFrom(issued);
vi.advanceTimersByTime(60_000);
await expect(consumeSessionHandoff(request("https://app.example.test/auth/session-handoff"), code)).resolves.toBeNull();
await expect(
createSessionHandoffRedirect({
request: request("https://admin.example.test/accounts/users"),
session,
redirectTo: "https://evil.example/phish",
})
).rejects.toThrow("canonical app-host redirect");
});
it("fails closed without emitting a redirect when the shared store is unavailable", async () => {
vi.spyOn(store, "set").mockRejectedValueOnce(new Error("redis unavailable"));
await expect(
createSessionHandoffRedirect({
request: request("https://admin.example.test/accounts/users"),
session,
redirectTo: "https://app.example.test/acme/dashboard",
})
).rejects.toThrow("redis unavailable");
expect(createUserSession).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,192 @@
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { MemoryAdapter, type SharedStore } from "@hivegrid/shared-store";
import { redirect } from "react-router";
import { getSharedStore } from "~/shared-store.server";
import { absolutePublicAppPath } from "~/utils/app/CrossHostUrls";
import { safeSessionRedirectTarget } from "~/utils/app/SessionRedirectSafety.server";
import { getHostRoutingContext, getRequestRoutingHost } from "~/utils/app/HostRouting.server";
import { createUserSession, type UserSession } from "~/utils/session.server";
import { loadRequiredWebConfig } from "@hivegrid/config";
export const SESSION_HANDOFF_TTL_SECONDS = 60;
export const SESSION_HANDOFF_PATH = "/auth/session-handoff";
const CONSUME_SCRIPT = `
local value = redis.call('GET', KEYS[1])
if value then
redis.call('DEL', KEYS[1])
end
return value
`;
MemoryAdapter.registerScript(CONSUME_SCRIPT, async (adapter, keys) => {
const key = keys[0];
if (!key) return null;
const value = await adapter.get(key);
if (value !== null) await adapter.del(key);
return value;
});
type SessionHandoffPayload = {
createdAt: number;
userAgentHash: string;
redirectTo: string;
session: UserSession;
};
let storeFactory: () => SharedStore = () => getSharedStore();
let memoryConsumeQueue: Promise<void> = Promise.resolve();
function codeKey(code: string) {
return `auth:session-handoff:${createHash("sha256").update(code).digest("hex")}`;
}
function signPayload(code: string, payload: string) {
return createHmac("sha256", code).update(payload).digest("base64url");
}
function safeSignatureMatch(actual: string, expected: string) {
const actualBytes = Buffer.from(actual);
const expectedBytes = Buffer.from(expected);
return actualBytes.length === expectedBytes.length && timingSafeEqual(actualBytes, expectedBytes);
}
function userAgentHash(request: Request) {
return createHash("sha256")
.update(request.headers.get("user-agent") ?? "")
.digest("hex");
}
function transferableSession(session: UserSession): UserSession {
return {
userId: session.userId,
lightOrDarkMode: session.lightOrDarkMode,
lng: session.lng,
// The destination host receives a fresh CSRF token from its root loader;
// never carry the admin-host token across the trust boundary.
csrf: undefined,
cookies: session.cookies,
metrics: session.metrics,
impersonatingFromUserId: session.impersonatingFromUserId,
impersonatingFromAdminUserId: session.impersonatingFromAdminUserId,
impersonatingFromAdminEmail: session.impersonatingFromAdminEmail,
impersonatingStartedAt: session.impersonatingStartedAt,
theme: session.theme,
passwordPolicyOutdated: session.passwordPolicyOutdated,
};
}
export async function createSessionHandoffRedirect({
request,
session,
redirectTo,
}: {
request: Request;
session: UserSession;
redirectTo: string;
}): Promise<Response> {
const routing = loadRequiredWebConfig().routing;
const safeRedirectTo = safeSessionRedirectTarget(redirectTo, routing);
const appOrigin = new URL(`${routing.protocol}://${routing.webAppHost}`).origin;
if (!safeRedirectTo.startsWith(`${appOrigin}/`)) {
throw new Error("Session handoff requires a canonical app-host redirect target");
}
const code = randomBytes(32).toString("base64url");
const payload: SessionHandoffPayload = {
createdAt: Date.now(),
userAgentHash: userAgentHash(request),
redirectTo: safeRedirectTo,
session: transferableSession(session),
};
const serializedPayload = JSON.stringify(payload);
const stored = await storeFactory().set(codeKey(code), JSON.stringify({ payload: serializedPayload, signature: signPayload(code, serializedPayload) }), {
ttlSeconds: SESSION_HANDOFF_TTL_SECONDS,
nx: true,
});
if (!stored) {
throw new Error("Could not reserve one-time session handoff code");
}
const target = new URL(absolutePublicAppPath(routing, SESSION_HANDOFF_PATH));
target.searchParams.set("code", code);
return redirect(target.toString(), {
headers: {
"Cache-Control": "no-store",
"Referrer-Policy": "no-referrer",
},
});
}
export async function consumeSessionHandoff(request: Request, code: string | null | undefined): Promise<Response | null> {
if (!code || !/^[A-Za-z0-9_-]{43}$/.test(code)) {
return null;
}
const routing = loadRequiredWebConfig().routing;
const requestUrl = new URL(request.url);
if (getHostRoutingContext(getRequestRoutingHost(request, requestUrl, routing), routing) !== "app") {
return null;
}
const store = storeFactory();
const consume = () => store.adapter.eval(CONSUME_SCRIPT, [store.key(codeKey(code))], []);
let raw: unknown;
if (store.adapter instanceof MemoryAdapter) {
// Redis runs the Lua script atomically. Serialize the development/test
// adapter too so concurrent consumers observe the same single-use rule.
const queued = memoryConsumeQueue.then(consume);
memoryConsumeQueue = queued.then(
() => undefined,
() => undefined
);
raw = await queued;
} else {
raw = await consume();
}
if (typeof raw !== "string") {
return null;
}
let payload: SessionHandoffPayload;
try {
const envelope = JSON.parse(raw) as { payload?: unknown; signature?: unknown };
if (
typeof envelope.payload !== "string" ||
typeof envelope.signature !== "string" ||
!safeSignatureMatch(envelope.signature, signPayload(code, envelope.payload))
) {
return null;
}
payload = JSON.parse(envelope.payload) as SessionHandoffPayload;
} catch {
return null;
}
const ageMs = Date.now() - payload.createdAt;
if (
!Number.isFinite(payload.createdAt) ||
ageMs < 0 ||
ageMs >= SESSION_HANDOFF_TTL_SECONDS * 1000 ||
payload.userAgentHash !== userAgentHash(request) ||
typeof payload.redirectTo !== "string" ||
!payload.session ||
typeof payload.session.userId !== "string"
) {
return null;
}
const response = await createUserSession(payload.session, payload.redirectTo, { request, rotate: true });
const headers = new Headers(response.headers);
headers.set("Cache-Control", "no-store");
headers.set("Referrer-Policy", "no-referrer");
return new Response(response.body, { status: response.status, headers });
}
export function __setSessionHandoffStoreForTests(store: SharedStore): void {
storeFactory = () => store;
}
export function __resetSessionHandoffStoreForTests(): void {
storeFactory = () => getSharedStore();
memoryConsumeQueue = Promise.resolve();
}
@@ -4,6 +4,28 @@ const storeMock = vi.hoisted(() => ({
createUserSession: vi.fn(),
revokeSessionByToken: vi.fn(),
}));
const adminStoreMock = vi.hoisted(() => ({
createAdminSession: vi.fn(),
revokeAdminSessionByToken: vi.fn(),
}));
vi.mock("@hivegrid/config", async (importOriginal) => {
const actual = await importOriginal<typeof import("@hivegrid/config")>();
return {
...actual,
loadRequiredWebConfig: () => ({
routing: {
appBaseDomain: "example.test",
protocol: "https",
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
},
}),
};
});
vi.mock("@hivegrid/db/admin-sessions.server", () => ({
createAdminSession: (...args: unknown[]) => adminStoreMock.createAdminSession(...args),
revokeAdminSessionByToken: (...args: unknown[]) => adminStoreMock.revokeAdminSessionByToken(...args),
}));
vi.mock("./sessionStore.server", () => ({
createUserSession: (...args: unknown[]) => storeMock.createUserSession(...args),
revokeSessionByToken: (...args: unknown[]) => storeMock.revokeSessionByToken(...args),
@@ -22,6 +44,10 @@ function requestWith(headers: Record<string, string>) {
return new Request("https://example.test/login", { headers });
}
function adminRequestWith(headers: Record<string, string>) {
return new Request("https://admin.example.test/login", { headers });
}
beforeEach(() => {
vi.clearAllMocks();
geoMock.lookupCountry.mockResolvedValue({ countryCode: "DE", countryName: "Germany" });
@@ -29,7 +55,13 @@ beforeEach(() => {
describe("buildSessionDeviceContext (AD-22)", () => {
it("hashes the IP and resolves the country, never exposing the raw IP", async () => {
const ctx = await buildSessionDeviceContext(requestWith({ "user-agent": "Safari", "x-forwarded-for": "9.9.9.9" }));
const ctx = await buildSessionDeviceContext(
requestWith({
"user-agent": "Safari",
"cf-connecting-ip": "9.9.9.9",
"x-forwarded-for": "198.51.100.9, 173.245.48.10",
}),
);
expect(ctx.ipHash).toBe("HASHED");
expect(ctx.userAgent).toBe("Safari");
expect(ctx.approxLocation).toBe("Germany");
@@ -48,10 +80,45 @@ describe("buildSessionDeviceContext (AD-22)", () => {
describe("startServerSession", () => {
it("creates a session row with the pseudonymized device context and returns the raw token", async () => {
storeMock.createUserSession.mockResolvedValue({ session: { id: "s1" }, rawToken: "tok-123" });
const token = await startServerSession({ request: requestWith({ "user-agent": "Safari", "x-forwarded-for": "1.2.3.4" }), userId: "u1" });
const token = await startServerSession({
request: requestWith({
"user-agent": "Safari",
"cf-connecting-ip": "1.2.3.4",
"x-forwarded-for": "198.51.100.4, 173.245.48.10",
}),
userId: "u1",
});
expect(token).toBe("tok-123");
expect(storeMock.createUserSession).toHaveBeenCalledWith({ userId: "u1", ipHash: "HASHED", userAgent: "Safari", approxLocation: "Germany" });
});
it("creates a dedicated eight-hour AdminSession only with Authentik MFA assurance", async () => {
const mfaAssuredAt = new Date("2026-07-24T18:00:00.000Z");
adminStoreMock.createAdminSession.mockResolvedValue({ session: { id: "as1" }, rawToken: "admin-token" });
const token = await startServerSession({
request: adminRequestWith({ "user-agent": "Safari" }),
userId: "admin-1",
adminAuthenticationMethods: ["pwd", "mfa"],
adminMfaAssuredAt: mfaAssuredAt,
});
expect(token).toBe("admin-token");
expect(adminStoreMock.createAdminSession).toHaveBeenCalledWith({
adminUserId: "admin-1",
authenticationMethods: ["pwd", "mfa"],
mfaAssuredAt,
ipHash: null,
userAgent: "Safari",
approxLocation: null,
});
expect(storeMock.createUserSession).not.toHaveBeenCalled();
});
it("fails closed on the admin host without MFA assurance", async () => {
await expect(startServerSession({ request: adminRequestWith({}), userId: "admin-1" })).rejects.toThrow(
"Admin server session requires Authentik MFA assurance"
);
expect(adminStoreMock.createAdminSession).not.toHaveBeenCalled();
});
});
describe("endServerSession", () => {
@@ -60,4 +127,12 @@ describe("endServerSession", () => {
await endServerSession("tok-123");
expect(storeMock.revokeSessionByToken).toHaveBeenCalledWith("tok-123");
});
it("revokes only the dedicated AdminSession on the admin host", async () => {
adminStoreMock.revokeAdminSessionByToken.mockResolvedValue(true);
const request = adminRequestWith({});
await endServerSession("admin-token", request);
expect(adminStoreMock.revokeAdminSessionByToken).toHaveBeenCalledWith("admin-token");
expect(storeMock.revokeSessionByToken).not.toHaveBeenCalled();
});
});
@@ -1,5 +1,8 @@
import { hashIp, lookupCountry } from "~/modules/ipAddress/services/geoip.server";
import { getClientIPAddress } from "~/utils/server/IpUtils";
import { getTrustedClientIpOrNull } from "~/utils/server/IpUtils";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { createAdminSession, revokeAdminSessionByToken } from "@hivegrid/db/admin-sessions.server";
import { getHostRoutingContext, getRequestRoutingHost } from "~/utils/app/HostRouting.server";
import { createUserSession as createServerSessionRow, revokeSessionByToken } from "./sessionStore.server";
@@ -8,7 +11,7 @@ import { createUserSession as createServerSessionRow, revokeSessionByToken } fro
// gefuehrt, damit Geraeteliste, Revoke und "ueberall abmelden" greifen.
export function extractRawClientIp(request: Request): string | null {
return getClientIPAddress(request.headers)?.toString() ?? null;
return getTrustedClientIpOrNull(request);
}
// AD-22: persistiert KEINE Klartext-IP. Die IP wird gehasht (hashIp, Wiedererkennung "gleiches
@@ -23,15 +26,46 @@ export async function buildSessionDeviceContext(request: Request): Promise<{ ipH
};
}
// Beim Login/Signup aufgerufen: legt die Session-Zeile mit (pseudonymisiertem) Geraete-Kontext an und
// liefert den rohen Token zurueck, der ins Cookie wandert. Best-effort: ein Store-Fehler darf den Login
// nicht verhindern (Cookie ist Source-of-Truth fuer die Identitaet).
export async function startServerSession({ request, userId }: { request: Request; userId: string }): Promise<string | null> {
// Every authenticated cookie is backed by this row. Store failures propagate
// so callers cannot issue an unrevocable fallback cookie.
export async function startServerSession({
request,
userId,
adminAuthenticationMethods,
adminMfaAssuredAt,
}: {
request: Request;
userId: string;
adminAuthenticationMethods?: readonly string[];
adminMfaAssuredAt?: Date;
}): Promise<string> {
const context = await buildSessionDeviceContext(request);
const routing = loadRequiredWebConfig().routing;
const host = getRequestRoutingHost(request, new URL(request.url), routing);
if (getHostRoutingContext(host, routing) === "admin") {
if (!adminAuthenticationMethods || !adminMfaAssuredAt) {
throw new Error("Admin server session requires Authentik MFA assurance");
}
const { rawToken } = await createAdminSession({
adminUserId: userId,
authenticationMethods: adminAuthenticationMethods,
mfaAssuredAt: adminMfaAssuredAt,
...context,
});
return rawToken;
}
const { rawToken } = await createServerSessionRow({ userId, ...context });
return rawToken;
}
export async function endServerSession(rawToken: string | undefined | null): Promise<void> {
export async function endServerSession(rawToken: string | undefined | null, request?: Request): Promise<void> {
if (request) {
const routing = loadRequiredWebConfig().routing;
const host = getRequestRoutingHost(request, new URL(request.url), routing);
if (getHostRoutingContext(host, routing) === "admin") {
await revokeAdminSessionByToken(rawToken);
return;
}
}
await revokeSessionByToken(rawToken);
}
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
const dbMock = vi.hoisted(() => ({
userSession: {
@@ -10,11 +11,13 @@ const dbMock = vi.hoisted(() => ({
updateMany: vi.fn(),
},
}));
const resolveUserSessionRlsIdentityMock = vi.hoisted(() => vi.fn());
vi.mock("~/utils/db.server", () => ({ db: dbMock, dbRead: dbMock }));
vi.mock("@hivegrid/db/rls-resolvers.server", () => ({
resolveUserSessionRlsIdentity: resolveUserSessionRlsIdentityMock,
}));
vi.mock("~/utils/cache.server", () => ({
// Cache als Pass-through: getFreshValue direkt aufrufen, clearCacheKey als Spy.
cachified: vi.fn(async (opts: { getFreshValue: () => Promise<unknown> }) => opts.getFreshValue()),
clearCacheKey: vi.fn(),
}));
@@ -27,6 +30,7 @@ import {
listActiveUserSessions,
markSessionTrusted,
revokeAllUserSessionsExcept,
revokeAllUserSessionsForUser,
revokeSessionByToken,
revokeUserSession,
} from "./sessionStore.server";
@@ -42,6 +46,7 @@ function pastDate(msAgo = 60_000) {
beforeEach(() => {
vi.clearAllMocks();
resolveUserSessionRlsIdentityMock.mockResolvedValue({ resourceId: "s1", userId: "u1" });
});
describe("session token hashing", () => {
@@ -71,6 +76,7 @@ describe("createUserSession", () => {
expect(data.ipHash).toBe("deadbeef");
expect(data.trustedAt).toBeNull();
});
});
describe("getActiveSessionByToken", () => {
@@ -80,19 +86,71 @@ describe("getActiveSessionByToken", () => {
});
it("returns the session when active", async () => {
dbMock.userSession.findUnique.mockResolvedValue({ id: "s1", revokedAt: null, expiresAt: futureDate() });
dbMock.userSession.findUnique.mockResolvedValue({
id: "s1",
revokedAt: null,
expiresAt: futureDate(),
user: { active: true, pendingDeletion: false, pseudonymized: false },
});
expect(await getActiveSessionByToken("raw")).toMatchObject({ id: "s1" });
expect(dbMock.userSession.findUnique).toHaveBeenCalledWith(
expect.objectContaining({ include: { user: { select: expect.objectContaining({ active: true, pendingDeletion: true, pseudonymized: true }) } } })
);
});
it("fails closed when the bootstrap resolver cannot prove the token owner", async () => {
resolveUserSessionRlsIdentityMock.mockResolvedValueOnce(null).mockResolvedValueOnce(null);
await expect(getActiveSessionByToken("unknown")).resolves.toBeNull();
await expect(revokeSessionByToken("unknown")).resolves.toBe(false);
expect(dbMock.userSession.findUnique).not.toHaveBeenCalled();
});
it("checks the source of truth on every cross-request validation", async () => {
dbMock.userSession.findUnique.mockResolvedValue({
id: "s1",
revokedAt: null,
expiresAt: futureDate(),
user: { active: true, pendingDeletion: false, pseudonymized: false },
});
await getActiveSessionByToken("raw");
await getActiveSessionByToken("raw");
expect(dbMock.userSession.findUnique).toHaveBeenCalledTimes(2);
});
it("returns null for a revoked session", async () => {
dbMock.userSession.findUnique.mockResolvedValue({ id: "s1", revokedAt: pastDate(), expiresAt: futureDate() });
dbMock.userSession.findUnique.mockResolvedValue({
id: "s1",
revokedAt: pastDate(),
expiresAt: futureDate(),
user: { active: true, pendingDeletion: false, pseudonymized: false },
});
expect(await getActiveSessionByToken("raw")).toBeNull();
});
it("returns null for an expired session", async () => {
dbMock.userSession.findUnique.mockResolvedValue({ id: "s1", revokedAt: null, expiresAt: pastDate() });
dbMock.userSession.findUnique.mockResolvedValue({
id: "s1",
revokedAt: null,
expiresAt: pastDate(),
user: { active: true, pendingDeletion: false, pseudonymized: false },
});
expect(await getActiveSessionByToken("raw")).toBeNull();
});
it.each([
{ active: false, pendingDeletion: false, pseudonymized: false },
{ active: true, pendingDeletion: true, pseudonymized: false },
{ active: true, pendingDeletion: false, pseudonymized: true },
])("returns null when the session owner is unavailable ($active/$pendingDeletion/$pseudonymized)", async (user) => {
dbMock.userSession.findUnique.mockResolvedValue({ id: "s1", revokedAt: null, expiresAt: futureDate(), user });
expect(await getActiveSessionByToken("raw")).toBeNull();
});
});
describe("listActiveUserSessions", () => {
@@ -104,6 +162,17 @@ describe("listActiveUserSessions", () => {
expect(where.revokedAt).toBeNull();
expect(where.expiresAt).toHaveProperty("gt");
});
it("reuses an already-bound matching user RLS context", async () => {
dbMock.userSession.findMany.mockImplementationOnce(async () => {
expect(getRlsExecutionContext()).toEqual({ userId: "u1" });
return [];
});
await runWithRlsContext({ userId: "u1" }, () => listActiveUserSessions("u1"));
expect(getRlsExecutionContext()).toBeNull();
});
});
describe("revokeUserSession", () => {
@@ -149,6 +218,22 @@ describe("revokeAllUserSessionsExcept", () => {
});
});
describe("revokeAllUserSessionsForUser", () => {
it("revokes every active row after an external authorization change", async () => {
dbMock.userSession.findMany.mockResolvedValue([{ tokenHash: "h1" }, { tokenHash: "h2" }]);
dbMock.userSession.updateMany.mockResolvedValue({ count: 2 });
await expect(revokeAllUserSessionsForUser("u1")).resolves.toBe(2);
expect(dbMock.userSession.updateMany).toHaveBeenCalledWith({
where: { userId: "u1", revokedAt: null, expiresAt: { gt: expect.any(Date) } },
data: { revokedAt: expect.any(Date) },
});
expect(clearCacheKeyMock).toHaveBeenCalledWith("user-session:h1");
expect(clearCacheKeyMock).toHaveBeenCalledWith("user-session:h2");
});
});
describe("revokeSessionByToken", () => {
it("returns false for a missing token without touching the DB", async () => {
expect(await revokeSessionByToken(undefined)).toBe(false);
@@ -1,7 +1,9 @@
import { createHash, randomBytes } from "node:crypto";
import { cachified, clearCacheKey } from "~/utils/cache.server";
import { clearCacheKey } from "~/utils/cache.server";
import { db } from "~/utils/db.server";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { resolveUserSessionRlsIdentity } from "@hivegrid/db/rls-resolvers.server";
// R-P2a S4 — serverseitige Sessions. Postgres ist Source-of-Truth (Tabelle UserSession),
// davor ein kurzlebiger Cache (LRU heute, Redis-swappable per cache.server, AD-4). Das
@@ -9,10 +11,25 @@ import { db } from "~/utils/db.server";
const SESSION_TOKEN_BYTES = 32;
const DEFAULT_SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 Tage, deckt das Cookie-Max-Age
const SESSION_CACHE_TTL_MS = 60 * 1000; // kurzer Cache vor dem Postgres-SoT
const TOUCH_THROTTLE_MS = 5 * 60 * 1000; // lastSeenAt hoechstens alle 5min fortschreiben
export type UserSessionRow = Awaited<ReturnType<typeof db.userSession.create>>;
export type ActiveUserSessionOwner = {
id: string;
email: string;
firstName: string;
lastName: string;
avatar: string | null;
phone: string | null;
defaultTenantId: string | null;
createdAt: Date;
locale: string | null;
lightOrDarkMode: string | null;
active: boolean;
pendingDeletion: boolean;
pseudonymized: boolean;
};
export type ActiveUserSessionRow = UserSessionRow & { user: ActiveUserSessionOwner };
type Identified = { userId: string; sessionId: string };
@@ -47,13 +64,18 @@ export type CreateSessionInput = {
};
export async function createUserSession(input: CreateSessionInput): Promise<{ session: UserSessionRow; rawToken: string }> {
return withUserRlsContext(input.userId, () => createUserSessionScoped(input));
}
async function createUserSessionScoped(input: CreateSessionInput): Promise<{ session: UserSessionRow; rawToken: string }> {
const rawToken = input.rawToken ?? generateSessionToken();
const now = Date.now();
const expiresAt = input.expiresAt ?? new Date(now + DEFAULT_SESSION_TTL_MS);
const session = await db.userSession.create({
data: {
userId: input.userId,
tokenHash: hashSessionToken(rawToken),
expiresAt: input.expiresAt ?? new Date(now + DEFAULT_SESSION_TTL_MS),
expiresAt,
ipHash: input.ipHash ?? null,
userAgent: input.userAgent ?? null,
deviceLabel: input.deviceLabel ?? null,
@@ -65,22 +87,52 @@ export async function createUserSession(input: CreateSessionInput): Promise<{ se
return { session, rawToken };
}
// Liefert die aktive Session zum Cookie-Token oder null (revoked/abgelaufen/unbekannt). Der
// Cache wird bei Revoke gezielt invalidiert; die Ablauf-Pruefung laeuft zusaetzlich live gegen now.
export async function getActiveSessionByToken(rawToken: string | undefined | null): Promise<UserSessionRow | null> {
// Authorization reads always hit the source of truth. Positive cross-request
// caching would leave revoked sessions usable until the cache TTL elapsed.
export async function getActiveSessionByToken(rawToken: string | undefined | null): Promise<ActiveUserSessionRow | null> {
if (!rawToken) {
return null;
}
const tokenHash = hashSessionToken(rawToken);
const session = await cachified<UserSessionRow | null>({
key: sessionCacheKey(tokenHash),
ttl: SESSION_CACHE_TTL_MS,
getFreshValue: async () => db.userSession.findUnique({ where: { tokenHash } }),
});
if (!isActive(session)) {
const identity = await resolveUserSessionRlsIdentity(tokenHash);
if (!identity) {
return null;
}
return session;
return runWithRlsContext({ userId: identity.userId }, () => getActiveSessionByTokenScoped(tokenHash, identity.resourceId));
}
async function getActiveSessionByTokenScoped(tokenHash: string, expectedSessionId: string): Promise<ActiveUserSessionRow | null> {
const session = await db.userSession.findUnique({
where: { tokenHash },
include: {
user: {
select: {
id: true,
email: true,
firstName: true,
lastName: true,
avatar: true,
phone: true,
defaultTenantId: true,
createdAt: true,
locale: true,
lightOrDarkMode: true,
active: true,
pendingDeletion: true,
pseudonymized: true,
},
},
},
});
if (!session || session.id !== expectedSessionId || !isActive(session)) {
return null;
}
// Existing sessions must stop authorizing immediately when the account is
// disabled, enters deletion, or has already been pseudonymized.
if (!session.user.active || session.user.pendingDeletion || session.user.pseudonymized) {
return null;
}
return session as ActiveUserSessionRow;
}
// Schreibt lastSeenAt fort, aber gedrosselt (hoechstens alle TOUCH_THROTTLE_MS), um den
@@ -95,15 +147,21 @@ export async function touchSession(session: Pick<UserSessionRow, "id" | "lastSee
}
export async function listActiveUserSessions(userId: string): Promise<UserSessionRow[]> {
return db.userSession.findMany({
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
orderBy: { lastSeenAt: "desc" },
});
return withUserRlsContext(userId, () =>
db.userSession.findMany({
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
orderBy: { lastSeenAt: "desc" },
}),
);
}
// Revoke einzeln (Geraete-Liste). Verifiziert die Eigentuemerschaft ueber userId, damit ein
// Nutzer nur eigene Sessions beenden kann, und invalidiert den Cache.
export async function revokeUserSession({ userId, sessionId }: Identified): Promise<boolean> {
return withUserRlsContext(userId, () => revokeUserSessionScoped({ userId, sessionId }));
}
async function revokeUserSessionScoped({ userId, sessionId }: Identified): Promise<boolean> {
const session = await db.userSession.findFirst({ where: { id: sessionId, userId }, select: { id: true, tokenHash: true, revokedAt: true } });
if (!session || session.revokedAt !== null) {
return false;
@@ -115,6 +173,10 @@ export async function revokeUserSession({ userId, sessionId }: Identified): Prom
// "Ueberall abmelden": alle aktiven Sessions des Nutzers ausser der aktuellen beenden.
export async function revokeAllUserSessionsExcept({ userId, sessionId }: Identified): Promise<number> {
return withUserRlsContext(userId, () => revokeAllUserSessionsExceptScoped({ userId, sessionId }));
}
async function revokeAllUserSessionsExceptScoped({ userId, sessionId }: Identified): Promise<number> {
const sessions = await db.userSession.findMany({
where: { userId, revokedAt: null, id: { not: sessionId } },
select: { id: true, tokenHash: true },
@@ -133,14 +195,46 @@ export async function revokeAllUserSessionsExcept({ userId, sessionId }: Identif
return sessions.length;
}
// Used when an external identity loses an allowed group. Revoking every
// server-side row makes the decision visible to all web replicas immediately.
export async function revokeAllUserSessionsForUser(userId: string): Promise<number> {
return withUserRlsContext(userId, () => revokeAllUserSessionsForUserScoped(userId));
}
async function revokeAllUserSessionsForUserScoped(userId: string): Promise<number> {
const sessions = await db.userSession.findMany({
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
select: { tokenHash: true },
});
if (sessions.length === 0) {
return 0;
}
const result = await db.userSession.updateMany({
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
data: { revokedAt: new Date() },
});
for (const session of sessions) {
clearCacheKey(sessionCacheKey(session.tokenHash));
}
return result.count;
}
// Revoke ueber den Cookie-Token (Logout): beendet genau die aktuelle Session.
export async function revokeSessionByToken(rawToken: string | undefined | null): Promise<boolean> {
if (!rawToken) {
return false;
}
const tokenHash = hashSessionToken(rawToken);
const identity = await resolveUserSessionRlsIdentity(tokenHash);
if (!identity) {
return false;
}
return runWithRlsContext({ userId: identity.userId }, () => revokeSessionByTokenScoped(tokenHash, identity.resourceId));
}
async function revokeSessionByTokenScoped(tokenHash: string, expectedSessionId: string): Promise<boolean> {
const session = await db.userSession.findUnique({ where: { tokenHash }, select: { id: true, revokedAt: true } });
if (!session || session.revokedAt !== null) {
if (!session || session.id !== expectedSessionId || session.revokedAt !== null) {
return false;
}
await db.userSession.update({ where: { id: session.id }, data: { revokedAt: new Date() } });
@@ -150,9 +244,18 @@ export async function revokeSessionByToken(rawToken: string | undefined | null):
// Trust-Device (S5/2FA): markiert eine eigene Session als vertrauenswuerdig.
export async function markSessionTrusted({ userId, sessionId }: Identified): Promise<boolean> {
const result = await db.userSession.updateMany({
where: { id: sessionId, userId, revokedAt: null },
data: { trustedAt: new Date() },
return withUserRlsContext(userId, async () => {
const result = await db.userSession.updateMany({
where: { id: sessionId, userId, revokedAt: null },
data: { trustedAt: new Date() },
});
return result.count > 0;
});
return result.count > 0;
}
function withUserRlsContext<T>(userId: string, operation: () => T): T {
if (getRlsExecutionContext()?.userId) {
return operation();
}
return runWithRlsContext({ userId }, operation);
}
@@ -15,6 +15,7 @@ vi.mock("@hivegrid/config", () => ({
vi.mock("~/utils/db/users.db.server", () => ({
activateUserTotpPendingSecret: vi.fn(),
clearUserTotpPendingSecret: vi.fn(),
getUserTotpPendingEnrollment: vi.fn(),
setUserMfaRecoveryCodes: vi.fn(),
setUserTotpPendingSecret: vi.fn(),
@@ -222,6 +223,7 @@ describe("services/auth/totp.server", () => {
const usersDb = await import("~/utils/db/users.db.server");
vi.mocked(usersDb.getUserTotpPendingEnrollment).mockResolvedValueOnce({
totpPendingSecretEncrypted: `encrypted:${vectorSecret}`,
totpPendingCreatedAt: new Date("2026-05-25T09:00:00.000Z"),
} as never);
const { activatePendingTotpForUser } = await import("./totp.server");
@@ -236,6 +238,27 @@ describe("services/auth/totp.server", () => {
expect(usersDb.setUserMfaRecoveryCodes).not.toHaveBeenCalled();
});
test("activatePendingTotpForUser clears and rejects an enrollment older than ten minutes", async () => {
const usersDb = await import("~/utils/db/users.db.server");
const pending = {
totpPendingSecretEncrypted: `encrypted:${vectorSecret}`,
totpPendingCreatedAt: new Date("2026-05-25T09:00:00.000Z"),
};
vi.mocked(usersDb.getUserTotpPendingEnrollment).mockResolvedValueOnce(pending);
const { activatePendingTotpForUser } = await import("./totp.server");
await expect(
activatePendingTotpForUser({
userId: "user_1",
token: generateExpectedCode(vectorSecret, new Date("2026-05-25T09:10:00.001Z").getTime()),
now: new Date("2026-05-25T09:10:00.001Z"),
})
).resolves.toEqual({ activated: false, recoveryCodes: [] });
expect(usersDb.clearUserTotpPendingSecret).toHaveBeenCalledWith("user_1", pending);
expect(usersDb.activateUserTotpPendingSecret).not.toHaveBeenCalled();
expect(usersDb.setUserMfaRecoveryCodes).not.toHaveBeenCalled();
});
test("activatePendingTotpForUser promotes the pending secret and stores recovery codes", async () => {
const usersDb = await import("~/utils/db/users.db.server");
const { generateRecoveryCodes } = await import("~/utils/auth/mfa/recovery-codes.server");
@@ -243,6 +266,7 @@ describe("services/auth/totp.server", () => {
const code = generateExpectedCode(vectorSecret, now.getTime());
vi.mocked(usersDb.getUserTotpPendingEnrollment).mockResolvedValueOnce({
totpPendingSecretEncrypted: `encrypted:${vectorSecret}`,
totpPendingCreatedAt: now,
} as never);
const { activatePendingTotpForUser, TOTP_RECOVERY_CODE_COUNT } = await import("./totp.server");
@@ -3,13 +3,16 @@ import { loadRequiredWebConfig } from "@hivegrid/config";
import CryptoApi from "~/utils/api/.server/CryptoApi";
import {
activateUserTotpPendingSecret,
clearUserTotpPendingSecret,
getUserTotpPendingEnrollment,
setUserMfaRecoveryCodes,
setUserTotpPendingSecret,
type UserTotpPendingEnrollment,
} from "~/utils/db/users.db.server";
import { generateRecoveryCodes } from "~/utils/auth/mfa/recovery-codes.server";
export const TOTP_RECOVERY_CODE_COUNT = 10;
export const TOTP_PENDING_ENROLLMENT_TTL_MS = 10 * 60 * 1000;
const TOTP_DIGITS = 6;
const TOTP_PERIOD_SECONDS = 30;
const DEFAULT_WINDOW = 1;
@@ -36,6 +39,11 @@ export type TotpEnrollmentResult = {
secret: string;
};
export type FreshTotpPendingEnrollment = UserTotpPendingEnrollment & {
totpPendingSecretEncrypted: string;
totpPendingCreatedAt: Date;
};
type OtpauthOptions = {
appName?: string;
issuer?: string;
@@ -148,6 +156,28 @@ export async function createTotpEnrollmentForUser({
};
}
export async function getFreshTotpPendingEnrollmentForUser({
userId,
now = new Date(),
}: {
userId: string;
now?: Date;
}): Promise<FreshTotpPendingEnrollment | null> {
const pending = await getUserTotpPendingEnrollment(userId);
if (!pending) {
return null;
}
const pendingCreatedAtMs = pending.totpPendingCreatedAt?.getTime();
const ageMs = pendingCreatedAtMs === undefined ? Number.NaN : now.getTime() - pendingCreatedAtMs;
if (pending.totpPendingSecretEncrypted && Number.isFinite(ageMs) && ageMs >= 0 && ageMs <= TOTP_PENDING_ENROLLMENT_TTL_MS) {
return pending as FreshTotpPendingEnrollment;
}
if (pending.totpPendingSecretEncrypted || pending.totpPendingCreatedAt) {
await clearUserTotpPendingSecret(userId, pending);
}
return null;
}
export async function activatePendingTotpForUser({
userId,
token,
@@ -157,8 +187,8 @@ export async function activatePendingTotpForUser({
token: string;
now?: Date;
}): Promise<{ activated: boolean; recoveryCodes: string[] }> {
const pending = await getUserTotpPendingEnrollment(userId);
if (!pending?.totpPendingSecretEncrypted) {
const pending = await getFreshTotpPendingEnrollmentForUser({ userId, now });
if (!pending) {
return { activated: false, recoveryCodes: [] };
}
if (!verifyTotpCode(pending.totpPendingSecretEncrypted, token, { timestamp: now.getTime() })) {
@@ -169,4 +199,3 @@ export async function activatePendingTotpForUser({
await setUserMfaRecoveryCodes(userId, recovery.entries, recovery.generatedAt);
return { activated: true, recoveryCodes: recovery.codes };
}