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

@@ -19,7 +19,6 @@ const baseWebConfig: WebConfig = {
novu: {},
mailerSend: {},
ipProviders: {},
portalServer: {},
magicLink: {
enabled: true,
tokenTtlMinutes: 15,
@@ -23,12 +23,10 @@ afterEach(async () => {
const toKey = (userId: string, ip: string) => ({ userId, perIp: `${userId}:${ip}` });
describe("MFA challenge rate limiter", () => {
it("keys attempts by user and a TRUSTED client IP, ignoring spoofable X-Forwarded-For", () => {
it("keys attempts by a Cloudflare client IP only behind a verified Cloudflare peer", () => {
const request = new Request("https://admin.example.test/mfa-challenge", {
headers: {
// Attacker-forged forwarded header must be ignored...
"x-forwarded-for": "1.2.3.4, 10.0.0.1",
// ...in favour of the Cloudflare-set trusted header.
"x-forwarded-for": "1.2.3.4, 173.245.48.10",
"cf-connecting-ip": "203.0.113.5",
},
});
@@ -36,7 +34,7 @@ describe("MFA challenge rate limiter", () => {
expect(mfaChallengeRateLimitKey(request, "user_1")).toEqual({ userId: "user_1", perIp: "user_1:203.0.113.5" });
});
it("falls back to x-real-ip and then unknown, never to x-forwarded-for", () => {
it("falls back to the Traefik-appended XFF or X-Real-IP peer and then unknown", () => {
expect(
mfaChallengeRateLimitKey(
new Request("https://admin.example.test/mfa-challenge", {
@@ -45,13 +43,12 @@ describe("MFA challenge rate limiter", () => {
"user_1",
),
).toEqual({ userId: "user_1", perIp: "user_1:198.51.100.7" });
// Only a spoofable X-Forwarded-For present -> not trusted -> unknown.
expect(
mfaChallengeRateLimitKey(
new Request("https://admin.example.test/mfa-challenge", { headers: { "x-forwarded-for": "203.0.113.9" } }),
"user_1",
),
).toEqual({ userId: "user_1", perIp: "user_1:unknown" });
).toEqual({ userId: "user_1", perIp: "user_1:203.0.113.9" });
expect(mfaChallengeRateLimitKey(new Request("https://admin.example.test/mfa-challenge"), "user_1")).toEqual({
userId: "user_1",
perIp: "user_1:unknown",
@@ -103,7 +100,7 @@ describe("MFA challenge rate limiter", () => {
await expect(checkMfaChallengeRateLimit(key, now)).resolves.toEqual({
allowed: true,
remaining: 5,
remaining: 4,
resetAt: new Date("2026-05-11T12:05:00.000Z"),
});
});
@@ -111,17 +108,37 @@ describe("MFA challenge rate limiter", () => {
it("resetMfaChallengeRateLimiterForTests clears cached fixed-window keys", async () => {
const key = toKey("user_1", "203.0.113.5");
const now = new Date("2026-05-11T12:00:00.000Z");
await recordFailedMfaChallengeAttempt(key, now);
expect((await checkMfaChallengeRateLimit(key, now)).allowed).toBe(true);
await resetMfaChallengeRateLimiterForTests();
const freshStore = createSharedStore({ namespace: "test-mfa-challenge" });
__setMfaChallengeRateLimitStoreForTests(freshStore);
await recordFailedMfaChallengeAttempt(key, now);
expect((await checkMfaChallengeRateLimit(key, now)).allowed).toBe(true);
});
it("atomically caps parallel TOTP verifiers", async () => {
const key = toKey("parallel-user", "198.51.100.88");
const results = await Promise.all(
Array.from({ length: 20 }, () => checkMfaChallengeRateLimit(key)),
);
expect(results.filter((result) => result.allowed)).toHaveLength(5);
expect(results.filter((result) => !result.allowed)).toHaveLength(15);
});
it("does not let a blocked source keep consuming the per-user budget", async () => {
const blockedKey = toKey("victim", "198.51.100.89");
for (let index = 0; index < 5; index += 1) {
expect((await checkMfaChallengeRateLimit(blockedKey)).allowed).toBe(true);
}
for (let index = 0; index < 20; index += 1) {
expect((await checkMfaChallengeRateLimit(blockedKey)).allowed).toBe(false);
}
expect((await checkMfaChallengeRateLimit(toKey("victim", "198.51.100.90"))).allowed).toBe(true);
});
it("swallows scan failures while clearing cached rate-limit keys (best-effort cleanup)", async () => {
const store = createSharedStore({ namespace: "test-mfa-scan-throw" });
// Force the cleanup scan to reject so the best-effort catch path runs.
@@ -66,34 +66,54 @@ export function mfaChallengeRateLimitKey(request: Request, userId: string): MfaC
}
export async function checkMfaChallengeRateLimit(key: MfaChallengeRateLimitKey, now: Date = new Date()): Promise<MfaChallengeRateLimitResult> {
const { store } = getLimiters();
const [perIpCount, perUserCount] = await Promise.all([
peekCount(store, `rl:fixed:mfa-challenge:${key.perIp}`),
peekCount(store, `rl:fixed:mfa-challenge-user:${key.userId}`),
]);
// Block as soon as either bound is reached. The per-user window is longer, so
// report its reset when it is the binding constraint.
if (perUserCount >= MFA_CHALLENGE_USER_LIMIT) {
return { allowed: false, retryAfterSeconds: MFA_CHALLENGE_USER_WINDOW_SECONDS, resetAt: new Date(now.getTime() + MFA_CHALLENGE_USER_WINDOW_SECONDS * 1000) };
}
if (perIpCount >= MFA_CHALLENGE_LIMIT) {
const { perIp, perUser, store } = getLimiters();
// Reserve before TOTP/recovery-code verification. Read-then-consume permits
// every request in a parallel burst to observe the same old count.
const perIpReservation = await reserveWithCorruptionRecovery(
perIp,
store,
key.perIp,
`rl:fixed:mfa-challenge:${key.perIp}`,
);
if (!perIpReservation.allowed) {
return { allowed: false, retryAfterSeconds: MFA_CHALLENGE_WINDOW_SECONDS, resetAt: new Date(now.getTime() + MFA_CHALLENGE_WINDOW_SECONDS * 1000) };
}
const perUserReservation = await reserveWithCorruptionRecovery(
perUser,
store,
key.userId,
`rl:fixed:mfa-challenge-user:${key.userId}`,
);
if (!perUserReservation.allowed) {
return { allowed: false, retryAfterSeconds: MFA_CHALLENGE_USER_WINDOW_SECONDS, resetAt: new Date(now.getTime() + MFA_CHALLENGE_USER_WINDOW_SECONDS * 1000) };
}
return {
allowed: true,
remaining: Math.min(MFA_CHALLENGE_LIMIT - perIpCount, MFA_CHALLENGE_USER_LIMIT - perUserCount),
remaining: Math.min(perIpReservation.remaining, perUserReservation.remaining),
resetAt: new Date(now.getTime() + MFA_CHALLENGE_WINDOW_SECONDS * 1000),
};
}
async function peekCount(store: SharedStore, suffix: string): Promise<number> {
const raw = await store.get(suffix);
return raw === null ? 0 : Number.parseInt(raw, 10) || 0;
export async function recordFailedMfaChallengeAttempt(key: MfaChallengeRateLimitKey, _now: Date = new Date()): Promise<void> {
// checkMfaChallengeRateLimit already reserved this attempt before verification.
void key;
void _now;
}
export async function recordFailedMfaChallengeAttempt(key: MfaChallengeRateLimitKey, _now: Date = new Date()): Promise<void> {
const { perIp, perUser } = getLimiters();
await Promise.all([perIp.consume(key.perIp), perUser.consume(key.userId)]);
async function reserveWithCorruptionRecovery(
limiter: FixedWindowRateLimiter,
store: SharedStore,
key: string,
storageKey: string,
) {
try {
return await limiter.consume(key);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (!/non-numeric|not an integer/i.test(message)) throw error;
await store.del(storageKey);
return limiter.consume(key);
}
}
export async function resetMfaChallengeRateLimit(key: MfaChallengeRateLimitKey): Promise<void> {
@@ -4,6 +4,7 @@ import type { UserTotpStatus } from "~/utils/db/users.db.server";
import type { MfaStepUpCheckResult } from "./step-up.server";
import {
ADMIN_MFA_CHALLENGE_PATH,
ADMIN_MFA_ENROLLMENT_PATH,
enforceAdminMfa,
type AdminMfaEnforcementResult,
} from "./enforcement.server";
@@ -48,21 +49,21 @@ describe("enforceAdminMfa", () => {
});
});
test("allows admins without active TOTP so the profile enrollment path is opt-in and non-blocking", () => {
test("fails closed when TOTP status is unavailable and requires enrollment when disabled", () => {
expect(enforce({ totpStatus: null })).toEqual({
allowed: true,
reason: "allowed",
redirectTo: "/users?tenant=tenant-1#section",
allowed: false,
reason: "missing-totp-status",
redirectTo: "/login",
});
expect(enforce({ totpStatus: { enabled: false, pending: false, enabledAt: null, pendingCreatedAt: null } })).toEqual({
allowed: true,
reason: "allowed",
redirectTo: "/users?tenant=tenant-1#section",
allowed: false,
reason: "totp-not-enabled",
redirectTo: ADMIN_MFA_ENROLLMENT_PATH,
});
expect(enforce({ totpStatus: pendingOnlyTotp })).toEqual({
allowed: true,
reason: "allowed",
redirectTo: "/users?tenant=tenant-1#section",
allowed: false,
reason: "totp-not-enabled",
redirectTo: ADMIN_MFA_ENROLLMENT_PATH,
});
});
@@ -127,9 +128,9 @@ describe("enforceAdminMfa", () => {
});
expect(enforce({ totpStatus: null, redirectMode: "host-aware" })).toEqual({
allowed: true,
reason: "allowed",
redirectTo: "/users?tenant=tenant-1#section",
allowed: false,
reason: "missing-totp-status",
redirectTo: "/login",
});
});
@@ -139,6 +140,11 @@ describe("enforceAdminMfa", () => {
reason: "allowed",
redirectTo: "/settings/profile?mfa=setup",
});
expect(enforce({ requestUrl: "https://admin.example.com/settings/profile/", totpStatus: pendingOnlyTotp, redirectMode: "host-aware" })).toEqual({
allowed: true,
reason: "allowed",
redirectTo: "/settings/profile/",
});
});
test("allows the admin MFA challenge route without existing step-up", () => {
@@ -186,6 +192,34 @@ describe("enforceAdminMfa", () => {
});
});
test("local dev bypass allows admins without TOTP or step-up under the dev:local contract", () => {
const localEnv = { LOCAL_DEV_CREDENTIALS: "1", NODE_ENV: "development" };
expect(enforce({ totpStatus: pendingOnlyTotp, stepUp: { verified: false, reason: "missing" }, env: localEnv })).toEqual({
allowed: true,
reason: "allowed",
redirectTo: "/users?tenant=tenant-1#section",
});
expect(enforce({ totpStatus: null, stepUp: { verified: false, reason: "missing" }, env: localEnv })).toEqual({
allowed: true,
reason: "allowed",
redirectTo: "/users?tenant=tenant-1#section",
});
});
test("local dev bypass never activates outside the dev:local contract and never bypasses auth itself", () => {
const localEnv = { LOCAL_DEV_CREDENTIALS: "1", NODE_ENV: "development" };
const denied = { allowed: false, reason: "totp-not-enabled", redirectTo: ADMIN_MFA_ENROLLMENT_PATH };
expect(enforce({ totpStatus: pendingOnlyTotp, env: {} })).toEqual(denied);
expect(enforce({ totpStatus: pendingOnlyTotp, env: { ...localEnv, NODE_ENV: "production" } })).toEqual(denied);
expect(enforce({ totpStatus: pendingOnlyTotp, env: { ...localEnv, LOCAL_DEV_CREDENTIALS: "" } })).toEqual(denied);
expect(enforce({ totpStatus: pendingOnlyTotp, env: { ...localEnv, CI: "true" } })).toEqual(denied);
expect(enforce({ totpStatus: pendingOnlyTotp, env: { ...localEnv, SENTRY_ENVIRONMENT: "staging" } })).toEqual(denied);
expect(enforce({ totpStatus: pendingOnlyTotp, env: { ...localEnv, RLS_RUNTIME_MODE: "required" } })).toEqual(denied);
expect(enforce({ userId: null, env: localEnv })).toEqual({ allowed: false, reason: "missing-user", redirectTo: "/login" });
expect(enforce({ isAdmin: false, env: localEnv })).toEqual({ allowed: false, reason: "missing-admin", redirectTo: "/" });
});
test("result payloads contain no TOTP secrets, recovery codes, hashes, cookies, tokens, or passwords", () => {
const result = enforce({
requestUrl: "https://admin.example.com/dashboard?tab=secrets",
@@ -1,7 +1,7 @@
import type { UserTotpStatus } from "~/utils/db/users.db.server";
import type { MfaStepUpCheckReason, MfaStepUpCheckResult } from "./step-up.server";
export { ADMIN_MFA_CHALLENGE_PATH, ADMIN_MFA_DEFAULT_REDIRECT_PATH, ADMIN_MFA_ENROLLMENT_PATH } from "./paths";
import { ADMIN_MFA_CHALLENGE_PATH, ADMIN_MFA_DEFAULT_REDIRECT_PATH } from "./paths";
import { ADMIN_MFA_CHALLENGE_PATH, ADMIN_MFA_DEFAULT_REDIRECT_PATH, ADMIN_MFA_ENROLLMENT_PATH } from "./paths";
export type AdminMfaEnforcementFailureReason =
| "missing-user"
@@ -27,12 +27,39 @@ export type AdminMfaEnforcementInput = {
stepUp: MfaStepUpCheckResult;
redirectMode?: "host-aware";
appFallbackPath?: string;
env?: AdminMfaLocalBypassEnvironment;
};
function isAdminMfaChallengePath(requestUrl: string | URL): boolean {
export type AdminMfaLocalBypassEnvironment = {
LOCAL_DEV_CREDENTIALS?: string;
NODE_ENV?: string;
CI?: string;
SENTRY_ENVIRONMENT?: string;
RLS_RUNTIME_MODE?: string;
};
/**
* The canonical local launcher (pnpm dev:local) disables admin TOTP enrollment
* and step-up challenges entirely. Gated on the same environment contract as
* the local credential normalization so it can never activate on CI, staging,
* or production (which additionally never set LOCAL_DEV_CREDENTIALS).
*/
export function isLocalAdminMfaBypassActive(env: AdminMfaLocalBypassEnvironment = process.env): boolean {
return (
env.LOCAL_DEV_CREDENTIALS === "1" &&
env.NODE_ENV === "development" &&
!env.CI?.trim() &&
!env.SENTRY_ENVIRONMENT?.trim() &&
env.RLS_RUNTIME_MODE?.trim().toLowerCase() !== "required"
);
}
function isAdminMfaPath(requestUrl: string | URL, expectedPath: string): boolean {
try {
const url = requestUrl instanceof URL ? requestUrl : new URL(requestUrl);
return url.pathname === ADMIN_MFA_CHALLENGE_PATH;
const pathname = url.pathname.replace(/\/+$/, "") || "/";
const normalizedExpectedPath = expectedPath.replace(/\/+$/, "") || "/";
return pathname === normalizedExpectedPath;
} catch {
return false;
}
@@ -75,11 +102,22 @@ export function enforceAdminMfa(input: AdminMfaEnforcementInput): AdminMfaEnforc
return { allowed: false, reason: "missing-admin", redirectTo: input.appFallbackPath ?? "/" };
}
if (!input.totpStatus || !input.totpStatus.enabled) {
if (isLocalAdminMfaBypassActive(input.env)) {
return { allowed: true, reason: "allowed", redirectTo: safePathFromRequestUrl(input.requestUrl) };
}
if (!input.stepUp.verified && !isAdminMfaChallengePath(input.requestUrl)) {
if (!input.totpStatus) {
return { allowed: false, reason: "missing-totp-status", redirectTo: "/login" };
}
if (!input.totpStatus.enabled) {
if (isAdminMfaPath(input.requestUrl, ADMIN_MFA_ENROLLMENT_PATH)) {
return { allowed: true, reason: "allowed", redirectTo: safePathFromRequestUrl(input.requestUrl) };
}
return { allowed: false, reason: "totp-not-enabled", redirectTo: ADMIN_MFA_ENROLLMENT_PATH };
}
if (!input.stepUp.verified && !isAdminMfaPath(input.requestUrl, ADMIN_MFA_CHALLENGE_PATH)) {
return { allowed: false, reason: stepUpReason(input.stepUp.reason), redirectTo: challengeRedirectTo(input.requestUrl) };
}
@@ -4,11 +4,26 @@
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const { testWebConfig } = vi.hoisted(() => ({
testWebConfig: {
nodeEnv: "test" as string,
sessionSecret: "test-session-secret-please-change",
routing: {
appBaseDomain: "example.test",
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
apiHost: "api.example.test",
protocol: "https" as "http" | "https",
},
},
}));
const resolveTrustedDeviceRlsIdentityMock = vi.hoisted(() => vi.fn());
vi.mock("@hivegrid/config", async () => {
const actual = await vi.importActual<typeof import("@hivegrid/config")>("@hivegrid/config");
return {
...actual,
loadRequiredWebConfig: () => ({ nodeEnv: "test", sessionSecret: "test-session-secret-please-change" }),
loadRequiredWebConfig: () => testWebConfig,
};
});
vi.mock("~/utils/db.server", () => ({
@@ -25,6 +40,9 @@ vi.mock("~/utils/db.server", () => ({
vi.mock("~/services/auth/sessionLifecycle.server", () => ({
buildSessionDeviceContext: vi.fn().mockResolvedValue({ ipHash: null, userAgent: "UA", approxLocation: "DE" }),
}));
vi.mock("@hivegrid/db/rls-resolvers.server", () => ({
resolveTrustedDeviceRlsIdentity: resolveTrustedDeviceRlsIdentityMock,
}));
import { db } from "~/utils/db.server";
import {
@@ -36,6 +54,7 @@ import {
rememberDeviceForUser,
revokeAllTrustedDevices,
revokeTrustedDevice,
LOCAL_TRUSTED_DEVICE_COOKIE_NAME,
TRUSTED_DEVICE_COOKIE_NAME,
} from "./trusted-device.server";
@@ -69,6 +88,10 @@ async function rememberAndGetRequest(userId = "user-1") {
beforeEach(() => {
vi.clearAllMocks();
resolveTrustedDeviceRlsIdentityMock.mockResolvedValue({ resourceId: "td-1", userId: "user-1" });
testWebConfig.nodeEnv = "test";
testWebConfig.routing.protocol = "https";
testWebConfig.routing.appBaseDomain = "example.test";
__resetTrustedDeviceCookieForTests();
});
afterEach(() => __resetTrustedDeviceCookieForTests());
@@ -79,6 +102,9 @@ describe("trusted-device (DB-backed)", () => {
const setCookie = await rememberDeviceForUser({ request: new Request("https://app.example.com/login-mfa"), userId: "user-1" });
expect(create).toHaveBeenCalledTimes(1);
expect(setCookie).toContain(TRUSTED_DEVICE_COOKIE_NAME);
expect(setCookie).toContain("Secure");
expect(setCookie).toContain("Path=/");
expect(setCookie).not.toContain("Domain=");
// Nur der Hash, nie der rohe Token, wird persistiert.
const data = (create.mock.calls[0][0] as { data: { tokenHash: string } }).data;
expect(data.tokenHash).toMatch(/^[0-9a-f]{64}$/);
@@ -129,6 +155,43 @@ describe("trusted-device (DB-backed)", () => {
expect(findUnique).not.toHaveBeenCalled();
});
it("ignores a legacy parent-domain cookie even when its signed value is otherwise valid", async () => {
const validRequest = await rememberAndGetRequest("user-1");
const cookie = validRequest.headers.get("Cookie") ?? "";
const legacyCookie = cookie.replace(TRUSTED_DEVICE_COOKIE_NAME, LOCAL_TRUSTED_DEVICE_COOKIE_NAME);
const request = new Request("https://app.example.test/login", { headers: { Cookie: legacyCookie } });
await expect(isTrustedDevice(request, "user-1")).resolves.toBe(false);
expect(findUnique).not.toHaveBeenCalled();
});
it("does not let a legacy cookie shadow the host-prefixed marker", async () => {
const validRequest = await rememberAndGetRequest("user-1");
const secureCookie = validRequest.headers.get("Cookie") ?? "";
const request = new Request("https://app.example.test/login", {
headers: { Cookie: `${LOCAL_TRUSTED_DEVICE_COOKIE_NAME}=attacker; ${secureCookie}` },
});
findUnique.mockResolvedValue(activeRow() as never);
await expect(isTrustedDevice(request, "user-1")).resolves.toBe(true);
expect(findUnique).toHaveBeenCalledTimes(1);
});
it("uses a distinct non-Secure fallback name on local HTTP", async () => {
testWebConfig.nodeEnv = "development";
testWebConfig.routing.protocol = "http";
testWebConfig.routing.appBaseDomain = "localhost:3000";
__resetTrustedDeviceCookieForTests();
create.mockResolvedValue(activeRow() as never);
const setCookie = await rememberDeviceForUser({ request: new Request("http://localhost:3000/login-mfa"), userId: "user-1" });
expect(setCookie).toContain(`${LOCAL_TRUSTED_DEVICE_COOKIE_NAME}=`);
expect(setCookie).not.toContain(TRUSTED_DEVICE_COOKIE_NAME);
expect(setCookie).not.toContain("Secure");
expect(setCookie).not.toContain("Domain=");
});
it("lists active trusted devices scoped to the owner, newest-used first", async () => {
const rows = [activeRow({ id: "td-1" }), activeRow({ id: "td-2" })];
vi.mocked(db.trustedDevice.findMany).mockResolvedValue(rows as never);
@@ -138,7 +201,7 @@ describe("trusted-device (DB-backed)", () => {
expect.objectContaining({
where: expect.objectContaining({ userId: "user-1", revokedAt: null }),
orderBy: { lastUsedAt: "desc" },
}),
})
);
});
@@ -1,14 +1,17 @@
import { createHash, randomBytes } from "node:crypto";
import { createCookie } from "react-router";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { loadRequiredWebConfig, resolveHostOnlyCookiePolicy } from "@hivegrid/config";
import { db } from "~/utils/db.server";
import { buildSessionDeviceContext } from "~/services/auth/sessionLifecycle.server";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { resolveTrustedDeviceRlsIdentity } from "@hivegrid/db/rls-resolvers.server";
// The trust-device marker survives logout, stays revocable via TrustedDevice,
// and stores only the SHA-256 hash of the opaque cookie token in the database.
export const TRUSTED_DEVICE_COOKIE_NAME = "hivegrid_trusted_device";
export const TRUSTED_DEVICE_MAX_AGE_SECONDS = 60 * 60 * 24 * 30; // 30 Tage
export const TRUSTED_DEVICE_COOKIE_NAME = "__Host-hivegrid_trusted_device";
export const LOCAL_TRUSTED_DEVICE_COOKIE_NAME = "hivegrid_trusted_device";
export const TRUSTED_DEVICE_MAX_AGE_SECONDS = 60 * 60 * 24 * 30; // 30 days
const TRUSTED_DEVICE_TOKEN_BYTES = 32;
const TOUCH_THROTTLE_MS = 5 * 60 * 1000; // throttle lastUsedAt updates to every 5 minutes
@@ -21,12 +24,19 @@ function getTrustedDeviceCookie() {
return cachedCookie;
}
const webConfig = loadRequiredWebConfig();
cachedCookie = createCookie(TRUSTED_DEVICE_COOKIE_NAME, {
httpOnly: true,
sameSite: "lax",
path: "/",
secure: webConfig.nodeEnv === "production",
const policy = resolveHostOnlyCookiePolicy({
nodeEnv: webConfig.nodeEnv,
routing: webConfig.routing,
secureName: TRUSTED_DEVICE_COOKIE_NAME,
localName: LOCAL_TRUSTED_DEVICE_COOKIE_NAME,
maxAge: TRUSTED_DEVICE_MAX_AGE_SECONDS,
});
cachedCookie = createCookie(policy.name, {
httpOnly: policy.httpOnly,
sameSite: policy.sameSite,
path: policy.path,
secure: policy.secure,
maxAge: policy.maxAge,
secrets: webConfig.sessionSecret ? [webConfig.sessionSecret] : [],
});
return cachedCookie;
@@ -54,10 +64,14 @@ async function readRawTokenFromCookie(request: Request): Promise<string | null>
}
/**
* Markiert das aktuelle Geraet fuer `userId` als vertrauenswuerdig: legt die Tabellen-Zeile mit
* (pseudonymisiertem) Geraete-Kontext an und gibt den Set-Cookie-String mit dem rohen Token zurueck.
* Marks the current device as trusted for `userId`, persists only the
* pseudonymized device context, and returns the raw token in a Set-Cookie value.
*/
export async function rememberDeviceForUser({ request, userId, now = new Date() }: { request: Request; userId: string; now?: Date }): Promise<string> {
return withUserRlsContext(userId, () => rememberDeviceForUserScoped({ request, userId, now }));
}
async function rememberDeviceForUserScoped({ request, userId, now }: { request: Request; userId: string; now: Date }): Promise<string> {
const rawToken = generateTrustedDeviceToken();
const context = await buildSessionDeviceContext(request);
await db.trustedDevice.create({
@@ -74,11 +88,14 @@ export async function rememberDeviceForUser({ request, userId, now = new Date()
}
/**
* Prueft, ob der Request ein vertrauenswuerdiges Geraet fuer `userId` traegt: Cookie-Token -> Hash ->
* aktive Tabellen-Zeile mit passender userId. Best-effort: jeder Fehler gilt als "nicht vertraut".
* Schreibt lastUsedAt gedrosselt fort.
* Resolves the cookie token to an active row owned by `userId`. This is
* best-effort and fail-closed; `lastUsedAt` writes are throttled.
*/
export async function isTrustedDevice(request: Request, userId: string, now: Date = new Date()): Promise<boolean> {
return withUserRlsContext(userId, () => isTrustedDeviceScoped(request, userId, now));
}
async function isTrustedDeviceScoped(request: Request, userId: string, now: Date): Promise<boolean> {
try {
const rawToken = await readRawTokenFromCookie(request);
if (!rawToken) {
@@ -97,50 +114,69 @@ export async function isTrustedDevice(request: Request, userId: string, now: Dat
}
}
/** Aktive vertrauenswuerdige Geraete eines Nutzers (Geraete-Liste in Settings > Sicherheit). */
/** Lists active trusted devices for the security settings screen. */
export async function listTrustedDevices(userId: string): Promise<TrustedDeviceRow[]> {
return db.trustedDevice.findMany({
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
orderBy: { lastUsedAt: "desc" },
});
return withUserRlsContext(userId, () =>
db.trustedDevice.findMany({
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
orderBy: { lastUsedAt: "desc" },
}),
);
}
/** Widerruft genau ein eigenes vertrauenswuerdiges Geraet (Eigentuemerschaft ueber userId gesichert). */
/** Revokes one trusted device after enforcing user ownership in the query. */
export async function revokeTrustedDevice({ userId, deviceId }: { userId: string; deviceId: string }): Promise<boolean> {
const result = await db.trustedDevice.updateMany({
where: { id: deviceId, userId, revokedAt: null },
data: { revokedAt: new Date() },
return withUserRlsContext(userId, async () => {
const result = await db.trustedDevice.updateMany({
where: { id: deviceId, userId, revokedAt: null },
data: { revokedAt: new Date() },
});
return result.count > 0;
});
return result.count > 0;
}
/** "Alle Geraete vergessen": widerruft alle aktiven Trust-Marker des Nutzers. */
/** Revokes every active trusted-device marker owned by the user. */
export async function revokeAllTrustedDevices(userId: string): Promise<number> {
const result = await db.trustedDevice.updateMany({
where: { userId, revokedAt: null },
data: { revokedAt: new Date() },
return withUserRlsContext(userId, async () => {
const result = await db.trustedDevice.updateMany({
where: { userId, revokedAt: null },
data: { revokedAt: new Date() },
});
return result.count;
});
return result.count;
}
/**
* Vergisst das aktuelle Geraet: widerruft die zum Cookie gehoerende Zeile (falls vorhanden) und gibt
* den Set-Cookie-String zurueck, der den Trust-Marker im Browser loescht.
*/
/** Revokes the current marker, if present, and clears its browser cookie. */
export async function forgetCurrentTrustedDevice(request: Request): Promise<string> {
const rawToken = await readRawTokenFromCookie(request);
if (rawToken) {
await db.trustedDevice.updateMany({ where: { tokenHash: hashTrustedDeviceToken(rawToken), revokedAt: null }, data: { revokedAt: new Date() } }).catch(() => undefined);
const tokenHash = hashTrustedDeviceToken(rawToken);
const identity = await resolveTrustedDeviceRlsIdentity(tokenHash).catch(() => null);
if (identity) {
await runWithRlsContext({ userId: identity.userId }, () =>
db.trustedDevice.updateMany({
where: { id: identity.resourceId, tokenHash, userId: identity.userId, revokedAt: null },
data: { revokedAt: new Date() },
}),
).catch(() => undefined);
}
}
return clearTrustedDeviceCookie();
}
/** Set-Cookie-String, der den Trust-Marker im Browser loescht (ohne DB-Zugriff). */
/** Returns a Set-Cookie value that clears the marker without a database read. */
export async function clearTrustedDeviceCookie(): Promise<string> {
return getTrustedDeviceCookie().serialize("", { maxAge: 0, expires: new Date(0) });
}
/** Test-Naht: erzwingt eine Neuauflage des Cookies (z.B. nach geaenderter Config im Test). */
/** Test seam for rebuilding the cookie after configuration changes. */
export function __resetTrustedDeviceCookieForTests() {
cachedCookie = null;
}
function withUserRlsContext<T>(userId: string, operation: () => T): T {
if (getRlsExecutionContext()?.userId) {
return operation();
}
return runWithRlsContext({ userId }, operation);
}
@@ -46,6 +46,14 @@ describe("passwordHasher.server", () => {
expect(result.rehashedHash).toBeUndefined();
});
test("verifyPassword rejects bcrypt credentials that would be silently truncated after 72 bytes", async () => {
const exactPrefix = "x".repeat(72);
const legacyHash = await bcryptjs.hash(exactPrefix, 4);
await expect(verifyPassword(exactPrefix, legacyHash)).resolves.toMatchObject({ valid: true });
await expect(verifyPassword(`${exactPrefix}attacker-controlled-suffix`, legacyHash)).resolves.toEqual({ valid: false });
});
test("verifyPassword rejects unknown / empty hashes without throwing", async () => {
await expect(verifyPassword(PLAINTEXT, "")).resolves.toEqual({ valid: false });
await expect(verifyPassword(PLAINTEXT, "garbage")).resolves.toEqual({ valid: false });
@@ -6,6 +6,9 @@
import argon2 from "argon2";
import bcryptjs from "bcryptjs";
import { createScopedLogger } from "~/utils/logger.server";
const passwordHasherLogger = createScopedLogger("auth.password-hasher");
// OWASP 2024 recommendation for argon2id at modest server cost.
// memoryCost is in KiB (19456 = 19 MiB).
@@ -18,6 +21,7 @@ const ARGON2_OPTIONS = {
const ARGON2_PREFIX_RE = /^\$argon2(?:i|d|id)\$/;
const BCRYPT_PREFIX_RE = /^\$2[abxy]\$/;
const BCRYPT_MAX_PASSWORD_BYTES = 72;
export type VerifyPasswordResult = {
valid: boolean;
@@ -56,15 +60,28 @@ export async function verifyPassword(plain: string, hash: string | null | undefi
try {
const valid = await argon2.verify(hash, plain);
return { valid };
} catch {
} catch (error: unknown) {
passwordHasherLogger.warn(
{ op: "verify.argon2.failed", error: toSafeVerificationError(error) },
"Argon2 password verification raised; treating the credential as invalid."
);
return { valid: false };
}
}
if (BCRYPT_PREFIX_RE.test(hash)) {
// bcrypt silently truncates after 72 bytes. Reject an overlong legacy
// credential so a different suffix cannot authenticate as the same key.
if (Buffer.byteLength(plain, "utf8") > BCRYPT_MAX_PASSWORD_BYTES) {
return { valid: false };
}
let valid = false;
try {
valid = await bcryptjs.compare(plain, hash);
} catch {
} catch (error: unknown) {
passwordHasherLogger.warn(
{ op: "verify.bcrypt.failed", error: toSafeVerificationError(error) },
"Bcrypt password verification raised; treating the credential as invalid."
);
return { valid: false };
}
if (!valid) {
@@ -85,3 +102,11 @@ export function isKnownHashFormat(hash: string): "argon2" | "bcrypt" | "unknown"
if (BCRYPT_PREFIX_RE.test(hash)) return "bcrypt";
return "unknown";
}
function toSafeVerificationError(error: unknown): { name: string; code?: string } {
const candidate = error as { name?: unknown; code?: unknown } | null;
return {
name: typeof candidate?.name === "string" ? candidate.name : "Error",
...(typeof candidate?.code === "string" ? { code: candidate.code } : {}),
};
}