Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+67
-14
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { createSharedStore } from "@toolctrl/shared-store";
|
||||
import { createSharedStore } from "@hivegrid/shared-store";
|
||||
|
||||
import {
|
||||
checkMfaChallengeRateLimit,
|
||||
@@ -20,31 +20,46 @@ afterEach(async () => {
|
||||
__resetMfaChallengeRateLimitStoreForTests();
|
||||
});
|
||||
|
||||
const toKey = (userId: string, ip: string) => ({ userId, perIp: `${userId}:${ip}` });
|
||||
|
||||
describe("MFA challenge rate limiter", () => {
|
||||
it("keys attempts by user and client IP", () => {
|
||||
it("keys attempts by user and a TRUSTED client IP, ignoring spoofable X-Forwarded-For", () => {
|
||||
const request = new Request("https://admin.example.test/mfa-challenge", {
|
||||
headers: { "x-forwarded-for": "203.0.113.5, 10.0.0.1" },
|
||||
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.
|
||||
"cf-connecting-ip": "203.0.113.5",
|
||||
},
|
||||
});
|
||||
|
||||
expect(mfaChallengeRateLimitKey(request, "user_1")).toBe("user_1:203.0.113.5");
|
||||
expect(mfaChallengeRateLimitKey(request, "user_1")).toEqual({ userId: "user_1", perIp: "user_1:203.0.113.5" });
|
||||
});
|
||||
|
||||
it("falls back from blank forwarded headers to real-ip and then unknown", () => {
|
||||
it("falls back to x-real-ip and then unknown, never to x-forwarded-for", () => {
|
||||
expect(
|
||||
mfaChallengeRateLimitKey(
|
||||
new Request("https://admin.example.test/mfa-challenge", {
|
||||
headers: { "x-forwarded-for": " ", "x-real-ip": "198.51.100.7" },
|
||||
headers: { "x-real-ip": "198.51.100.7" },
|
||||
}),
|
||||
"user_1",
|
||||
),
|
||||
).toBe("user_1:198.51.100.7");
|
||||
expect(mfaChallengeRateLimitKey(new Request("https://admin.example.test/mfa-challenge"), "user_1")).toBe(
|
||||
"user_1:unknown",
|
||||
);
|
||||
).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" });
|
||||
expect(mfaChallengeRateLimitKey(new Request("https://admin.example.test/mfa-challenge"), "user_1")).toEqual({
|
||||
userId: "user_1",
|
||||
perIp: "user_1:unknown",
|
||||
});
|
||||
});
|
||||
|
||||
it("blocks after repeated failed attempts and can be reset", async () => {
|
||||
const key = "user_1:203.0.113.5";
|
||||
const key = toKey("user_1", "203.0.113.5");
|
||||
const now = new Date("2026-05-11T12:00:00.000Z");
|
||||
|
||||
for (let index = 0; index < 5; index += 1) {
|
||||
@@ -62,12 +77,29 @@ describe("MFA challenge rate limiter", () => {
|
||||
expect((await checkMfaChallengeRateLimit(key, now)).allowed).toBe(true);
|
||||
});
|
||||
|
||||
it("enforces the per-user cap even when the attacker rotates the client IP", async () => {
|
||||
const now = new Date("2026-05-11T12:00:00.000Z");
|
||||
// Attacker changes the trusted IP every attempt, so no per-IP bucket ever
|
||||
// fills — but the per-user bucket (keyed on userId alone) still bounds them.
|
||||
for (let index = 0; index < 15; index += 1) {
|
||||
const key = toKey("victim", `203.0.113.${index}`);
|
||||
expect((await checkMfaChallengeRateLimit(key, now)).allowed).toBe(true);
|
||||
await recordFailedMfaChallengeAttempt(key, now);
|
||||
}
|
||||
|
||||
const blocked = await checkMfaChallengeRateLimit(toKey("victim", "203.0.113.99"), now);
|
||||
expect(blocked.allowed).toBe(false);
|
||||
if (!blocked.allowed) {
|
||||
expect(blocked.retryAfterSeconds).toBe(900);
|
||||
}
|
||||
});
|
||||
|
||||
it("treats non-numeric stored counters as zero remaining attempts", async () => {
|
||||
const store = createSharedStore({ namespace: "test-mfa-challenge-nan" });
|
||||
__setMfaChallengeRateLimitStoreForTests(store);
|
||||
const key = "user_1:203.0.113.5";
|
||||
const key = toKey("user_1", "203.0.113.5");
|
||||
const now = new Date("2026-05-11T12:00:00.000Z");
|
||||
await store.set(`rl:fixed:mfa-challenge:${key}`, "NaN", { ttlSeconds: 300 });
|
||||
await store.set(`rl:fixed:mfa-challenge:${key.perIp}`, "NaN", { ttlSeconds: 300 });
|
||||
|
||||
await expect(checkMfaChallengeRateLimit(key, now)).resolves.toEqual({
|
||||
allowed: true,
|
||||
@@ -77,7 +109,7 @@ describe("MFA challenge rate limiter", () => {
|
||||
});
|
||||
|
||||
it("resetMfaChallengeRateLimiterForTests clears cached fixed-window keys", async () => {
|
||||
const key = "user_1:203.0.113.5";
|
||||
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);
|
||||
@@ -90,6 +122,27 @@ describe("MFA challenge rate limiter", () => {
|
||||
expect((await checkMfaChallengeRateLimit(key, now)).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.
|
||||
(store.adapter as unknown as { scan: () => AsyncIterable<string> }).scan = async function* () {
|
||||
throw new Error("scan boom");
|
||||
};
|
||||
__setMfaChallengeRateLimitStoreForTests(store);
|
||||
// Populate the cached limiter so the reset has a previous store to scan.
|
||||
await checkMfaChallengeRateLimit(toKey("user_scan", "203.0.113.9"));
|
||||
|
||||
await expect(resetMfaChallengeRateLimiterForTests()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("falls back to the process shared store after the test override is reset", async () => {
|
||||
// Drops the injected store and reverts storeFactory to the default web store.
|
||||
__resetMfaChallengeRateLimitStoreForTests();
|
||||
|
||||
const result = await checkMfaChallengeRateLimit(toKey("default-factory-user", "9.9.9.9"));
|
||||
expect(result.allowed).toBe(true);
|
||||
});
|
||||
|
||||
it("uses the redis adapter when REDIS_URL is set", () => {
|
||||
const originalRedisUrl = process.env.REDIS_URL;
|
||||
try {
|
||||
|
||||
+62
-29
@@ -2,72 +2,103 @@ import {
|
||||
createFixedWindowRateLimiter,
|
||||
type FixedWindowRateLimiter,
|
||||
type SharedStore,
|
||||
} from "@toolctrl/shared-store";
|
||||
} from "@hivegrid/shared-store";
|
||||
import { getSharedStore } from "~/shared-store.server";
|
||||
import { getTrustedClientIp } from "~/utils/server/IpUtils";
|
||||
|
||||
// Per (user, IP) throttle. The IP is derived from a trusted, proxy-set header
|
||||
// so it cannot be rotated by forging X-Forwarded-For.
|
||||
const MFA_CHALLENGE_LIMIT = 5;
|
||||
const MFA_CHALLENGE_WINDOW_SECONDS = 5 * 60;
|
||||
|
||||
// Authoritative per-user throttle, independent of IP. This is what actually
|
||||
// bounds a brute-force attack: the victim's userId is fixed, so an attacker
|
||||
// cannot escape it by changing IPs. Generous enough that a real user retrying
|
||||
// their TOTP a few times never hits it, tight enough that guessing a 6-digit
|
||||
// code stays astronomically unlikely.
|
||||
const MFA_CHALLENGE_USER_LIMIT = 15;
|
||||
const MFA_CHALLENGE_USER_WINDOW_SECONDS = 15 * 60;
|
||||
|
||||
export type MfaChallengeRateLimitKey = {
|
||||
/** Per-user key, independent of IP — the authoritative brute-force bound. */
|
||||
userId: string;
|
||||
/** Per (user, trusted-IP) key for finer-grained throttling. */
|
||||
perIp: string;
|
||||
};
|
||||
|
||||
export type MfaChallengeRateLimitResult =
|
||||
| { allowed: true; remaining: number; resetAt: Date }
|
||||
| { allowed: false; retryAfterSeconds: number; resetAt: Date };
|
||||
|
||||
type Limiter = {
|
||||
limiter: FixedWindowRateLimiter;
|
||||
type Limiters = {
|
||||
perIp: FixedWindowRateLimiter;
|
||||
perUser: FixedWindowRateLimiter;
|
||||
store: SharedStore;
|
||||
};
|
||||
|
||||
let cached: Limiter | null = null;
|
||||
let cached: Limiters | null = null;
|
||||
let storeFactory: () => SharedStore = () => getSharedStore();
|
||||
|
||||
function getLimiter(): Limiter {
|
||||
function getLimiters(): Limiters {
|
||||
if (cached !== null) return cached;
|
||||
const store = storeFactory();
|
||||
cached = {
|
||||
store,
|
||||
limiter: createFixedWindowRateLimiter({
|
||||
perIp: createFixedWindowRateLimiter({
|
||||
store,
|
||||
prefix: "mfa-challenge",
|
||||
windowSeconds: MFA_CHALLENGE_WINDOW_SECONDS,
|
||||
max: MFA_CHALLENGE_LIMIT,
|
||||
}),
|
||||
perUser: createFixedWindowRateLimiter({
|
||||
store,
|
||||
prefix: "mfa-challenge-user",
|
||||
windowSeconds: MFA_CHALLENGE_USER_WINDOW_SECONDS,
|
||||
max: MFA_CHALLENGE_USER_LIMIT,
|
||||
}),
|
||||
};
|
||||
return cached;
|
||||
}
|
||||
|
||||
export function mfaChallengeRateLimitKey(request: Request, userId: string) {
|
||||
const forwardedFor = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim();
|
||||
const ip = forwardedFor || request.headers.get("x-real-ip")?.trim() || "unknown";
|
||||
return `${userId}:${ip}`;
|
||||
export function mfaChallengeRateLimitKey(request: Request, userId: string): MfaChallengeRateLimitKey {
|
||||
const ip = getTrustedClientIp(request);
|
||||
return { userId, perIp: `${userId}:${ip}` };
|
||||
}
|
||||
|
||||
export async function checkMfaChallengeRateLimit(key: string, now: Date = new Date()): Promise<MfaChallengeRateLimitResult> {
|
||||
const { store } = getLimiter();
|
||||
const suffix = `rl:fixed:mfa-challenge:${key}`;
|
||||
const raw = await store.get(suffix);
|
||||
const count = raw === null ? 0 : Number.parseInt(raw, 10) || 0;
|
||||
if (count >= MFA_CHALLENGE_LIMIT) {
|
||||
return {
|
||||
allowed: false,
|
||||
retryAfterSeconds: MFA_CHALLENGE_WINDOW_SECONDS,
|
||||
resetAt: new Date(now.getTime() + MFA_CHALLENGE_WINDOW_SECONDS * 1000),
|
||||
};
|
||||
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) {
|
||||
return { allowed: false, retryAfterSeconds: MFA_CHALLENGE_WINDOW_SECONDS, resetAt: new Date(now.getTime() + MFA_CHALLENGE_WINDOW_SECONDS * 1000) };
|
||||
}
|
||||
return {
|
||||
allowed: true,
|
||||
remaining: MFA_CHALLENGE_LIMIT - count,
|
||||
remaining: Math.min(MFA_CHALLENGE_LIMIT - perIpCount, MFA_CHALLENGE_USER_LIMIT - perUserCount),
|
||||
resetAt: new Date(now.getTime() + MFA_CHALLENGE_WINDOW_SECONDS * 1000),
|
||||
};
|
||||
}
|
||||
|
||||
export async function recordFailedMfaChallengeAttempt(key: string, _now: Date = new Date()): Promise<void> {
|
||||
const { limiter } = getLimiter();
|
||||
await limiter.consume(key);
|
||||
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 resetMfaChallengeRateLimit(key: string): Promise<void> {
|
||||
const { limiter } = getLimiter();
|
||||
await limiter.reset(key);
|
||||
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)]);
|
||||
}
|
||||
|
||||
export async function resetMfaChallengeRateLimit(key: MfaChallengeRateLimitKey): Promise<void> {
|
||||
const { perIp, perUser } = getLimiters();
|
||||
await Promise.all([perIp.reset(key.perIp), perUser.reset(key.userId)]);
|
||||
}
|
||||
|
||||
export async function resetMfaChallengeRateLimiterForTests(): Promise<void> {
|
||||
@@ -76,7 +107,9 @@ export async function resetMfaChallengeRateLimiterForTests(): Promise<void> {
|
||||
if (previous) {
|
||||
try {
|
||||
for await (const fullKey of previous.store.adapter.scan(
|
||||
`shared-store:${previous.store.namespace}:rl:fixed:mfa-challenge:*`,
|
||||
// Matches both the per-IP (mfa-challenge:*) and per-user
|
||||
// (mfa-challenge-user:*) buckets.
|
||||
`shared-store:${previous.store.namespace}:rl:fixed:mfa-challenge*`,
|
||||
)) {
|
||||
const prefix = `shared-store:${previous.store.namespace}:`;
|
||||
if (fullKey.startsWith(prefix)) {
|
||||
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
// @vitest-environment node
|
||||
//
|
||||
// Fault-injection coverage for the hard-to-reach failure branches in
|
||||
// recovery-codes.server: the HMAC-secret resolution (CRYPTO_SECRET vs the
|
||||
// SESSION_SECRET fallback vs neither) and the "could not generate unique
|
||||
// codes after retry" guard. Both need control over `@hivegrid/config` /
|
||||
// `node:crypto`, so they live in a dedicated file with their own mocks
|
||||
// instead of the env-driven happy-path suite.
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
secret: { cryptoSecret: "fault-crypto-secret", sessionSecret: "" } as { cryptoSecret?: string; sessionSecret?: string },
|
||||
collapseEntropy: false,
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/config", async () => {
|
||||
const actual = await vi.importActual<typeof import("@hivegrid/config")>("@hivegrid/config");
|
||||
return {
|
||||
...actual,
|
||||
loadRequiredWebConfig: () => state.secret,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("node:crypto", async () => {
|
||||
const actual = await vi.importActual<typeof import("node:crypto")>("node:crypto");
|
||||
return {
|
||||
...actual,
|
||||
// When collapsed, every random byte is 0 → every generated character is the
|
||||
// first alphabet entry → all codes are identical → the uniqueness retry
|
||||
// loop is exhausted. Real HMAC/equality stay intact via `actual`.
|
||||
randomBytes: (size: number) =>
|
||||
state.collapseEntropy ? Buffer.alloc(size, 0) : (actual.randomBytes as (n: number) => Buffer)(size),
|
||||
};
|
||||
});
|
||||
|
||||
import { generateRecoveryCodes, hashRecoveryCode } from "./recovery-codes.server";
|
||||
|
||||
describe("recovery-codes.server (fault injection)", () => {
|
||||
test("falls back to SESSION_SECRET when CRYPTO_SECRET is unset", () => {
|
||||
state.secret = { cryptoSecret: "", sessionSecret: "session-fallback-secret" };
|
||||
|
||||
const hash = hashRecoveryCode("2345-6789-ABCD");
|
||||
expect(hash).toMatch(/^[a-f0-9]{64}$/);
|
||||
});
|
||||
|
||||
test("throws a configuration error when neither CRYPTO_SECRET nor SESSION_SECRET is set", () => {
|
||||
state.secret = { cryptoSecret: "", sessionSecret: "" };
|
||||
|
||||
expect(() => hashRecoveryCode("2345-6789-ABCD")).toThrow("CRYPTO_SECRET or SESSION_SECRET env variable not set");
|
||||
});
|
||||
|
||||
test("throws when unique recovery codes cannot be generated after the retry budget is exhausted", () => {
|
||||
state.secret = { cryptoSecret: "fault-crypto-secret", sessionSecret: "" };
|
||||
state.collapseEntropy = true;
|
||||
try {
|
||||
expect(() => generateRecoveryCodes({ count: 2 })).toThrow(
|
||||
"Failed to generate unique recovery codes after retry; suspected entropy source failure.",
|
||||
);
|
||||
} finally {
|
||||
state.collapseEntropy = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
+46
@@ -155,4 +155,50 @@ describe("recovery-codes.server", () => {
|
||||
expect(consumed.usedAt).toBeInstanceOf(Date);
|
||||
expect(consumed.entries[0].usedAt).toBe(consumed.usedAt);
|
||||
});
|
||||
|
||||
test("rejects non-positive and non-integer count, segment, and segment-length parameters", async () => {
|
||||
const { generateRecoveryCode, generateRecoveryCodes, normalizeRecoveryCode } = await import("./recovery-codes.server");
|
||||
|
||||
// Integer-but-non-positive values reach the `value <= 0` guard branch...
|
||||
expect(() => generateRecoveryCode({ segments: 0 })).toThrow("segments must be a positive integer");
|
||||
expect(() => generateRecoveryCode({ segmentLength: -1 })).toThrow("segmentLength must be a positive integer");
|
||||
expect(() => generateRecoveryCodes({ count: 0 })).toThrow("count must be a positive integer");
|
||||
expect(() => normalizeRecoveryCode("2345-6789-ABCD", { segments: 0 })).toThrow("segments must be a positive integer");
|
||||
expect(() => normalizeRecoveryCode("2345-6789-ABCD", { segmentLength: 0 })).toThrow("segmentLength must be a positive integer");
|
||||
// ...while a fractional value trips the `!Number.isInteger(value)` guard first.
|
||||
expect(() => generateRecoveryCode({ segments: 2.5 })).toThrow("segments must be a positive integer");
|
||||
});
|
||||
|
||||
test("generateRecoveryCode honours explicit shapes and falls back to the default segment layout", async () => {
|
||||
const { generateRecoveryCode } = await import("./recovery-codes.server");
|
||||
|
||||
// No options → both `??` defaults are exercised (3 segments × 4 chars).
|
||||
expect(generateRecoveryCode()).toMatch(codePattern);
|
||||
// Explicit options → the provided values win over the defaults.
|
||||
expect(generateRecoveryCode({ segments: 2, segmentLength: 5 })).toMatch(
|
||||
/^[23456789ABCDEFGHJKLMNPQRSTUVWXYZ]{5}-[23456789ABCDEFGHJKLMNPQRSTUVWXYZ]{5}$/,
|
||||
);
|
||||
});
|
||||
|
||||
test("status helper keeps the most recent usage timestamp and stays null-safe when the first entry lacks a creation date", async () => {
|
||||
const { getRecoveryCodeStatus } = await import("./recovery-codes.server");
|
||||
|
||||
// Two used entries with the later one first forces the reduce to keep the
|
||||
// running `latest` (the `entry > latest` comparison resolves to false), and
|
||||
// an undefined `createdAt` on the first entry exercises the `?? null`
|
||||
// fallback for `generatedAt`.
|
||||
const entries = [
|
||||
{ hash: "aa", usedAt: new Date("2026-05-08T10:00:00.000Z"), createdAt: undefined as unknown as Date },
|
||||
{ hash: "bb", usedAt: new Date("2026-05-08T09:00:00.000Z"), createdAt: new Date("2026-05-08T08:00:00.000Z") },
|
||||
];
|
||||
|
||||
expect(getRecoveryCodeStatus(entries)).toEqual({
|
||||
configured: true,
|
||||
totalCount: 2,
|
||||
remainingCount: 0,
|
||||
usedCount: 2,
|
||||
generatedAt: null,
|
||||
lastUsedAt: new Date("2026-05-08T10:00:00.000Z"),
|
||||
});
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { loadRequiredWebConfig } from "@toolctrl/config";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
|
||||
export const DEFAULT_RECOVERY_CODE_COUNT = 10;
|
||||
export const DEFAULT_RECOVERY_CODE_SEGMENTS = 3;
|
||||
|
||||
+17
@@ -122,6 +122,23 @@ describe("step-up.server", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("falls back to the wall clock when no timestamp is supplied for set or check", async () => {
|
||||
const session = await createSession();
|
||||
|
||||
// No `now` → setMfaStepUpState stamps the current time...
|
||||
const state = setMfaStepUpState(session, { userId: "admin-1", method: "totp" });
|
||||
expect(typeof state.verifiedAt).toBe("string");
|
||||
expect(Number.isNaN(Date.parse(state.verifiedAt))).toBe(false);
|
||||
|
||||
// ...and checkMfaStepUpState with no options compares against the current time.
|
||||
const result = checkMfaStepUpState(session, "admin-1");
|
||||
expect(result.verified).toBe(true);
|
||||
if (result.verified) {
|
||||
expect(result.ageMs).toBeGreaterThanOrEqual(0);
|
||||
expect(result.ageMs).toBeLessThan(MFA_STEP_UP_MAX_AGE_MS);
|
||||
}
|
||||
});
|
||||
|
||||
test("clears existing MFA step-up state", async () => {
|
||||
const session = await createSession();
|
||||
setMfaStepUpState(session, { userId: "admin-1", method: "totp", now: new Date("2026-05-08T14:00:00.000Z") });
|
||||
|
||||
+22
-2
@@ -4,8 +4,8 @@
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@toolctrl/config", async () => {
|
||||
const actual = await vi.importActual<typeof import("@toolctrl/config")>("@toolctrl/config");
|
||||
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" }),
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
clearTrustedDeviceCookie,
|
||||
forgetCurrentTrustedDevice,
|
||||
isTrustedDevice,
|
||||
listTrustedDevices,
|
||||
rememberDeviceForUser,
|
||||
revokeAllTrustedDevices,
|
||||
revokeTrustedDevice,
|
||||
@@ -128,6 +129,25 @@ describe("trusted-device (DB-backed)", () => {
|
||||
expect(findUnique).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
await expect(listTrustedDevices("user-1")).resolves.toEqual(rows);
|
||||
expect(db.trustedDevice.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({ userId: "user-1", revokedAt: null }),
|
||||
orderBy: { lastUsedAt: "desc" },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("treats a database failure during the trust lookup as not-trusted", async () => {
|
||||
const request = await rememberAndGetRequest("user-1");
|
||||
findUnique.mockRejectedValue(new Error("db unavailable"));
|
||||
await expect(isTrustedDevice(request, "user-1")).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it("revokes a single device scoped to the owner", async () => {
|
||||
updateMany.mockResolvedValue({ count: 1 } as never);
|
||||
await expect(revokeTrustedDevice({ userId: "user-1", deviceId: "td-1" })).resolves.toBe(true);
|
||||
|
||||
+5
-9
@@ -1,20 +1,16 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { createCookie } from "react-router";
|
||||
import { loadRequiredWebConfig } from "@toolctrl/config";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { buildSessionDeviceContext } from "~/services/auth/sessionLifecycle.server";
|
||||
|
||||
// D1 (Trust-Device) — "diesem Geraet vertrauen" beim 2FA-Login. Der Marker UEBERLEBT den Logout
|
||||
// (deshalb NICHT die per-Session `UserSession.trustedAt`), ist aber WIDERRUFBAR: ein eigenes, langlebiges
|
||||
// Cookie (`RJ_trusted_device`) traegt einen opaken Zufalls-Token, persistiert wird nur dessen SHA-256-Hash
|
||||
// in der Tabelle `TrustedDevice`. Autoritaet ist die Tabelle (Revoke einzeln / "ueberall vergessen" ueber
|
||||
// Settings > Sicherheit) -> erfuellt den DoD-Screen "Trust-Device-Revoke" (R-P2a). Das Cookie ist nur der
|
||||
// Traeger; ohne passende, aktive Zeile gilt das Geraet als NICHT vertrauenswuerdig.
|
||||
// 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 = "RJ_trusted_device";
|
||||
export const TRUSTED_DEVICE_COOKIE_NAME = "hivegrid_trusted_device";
|
||||
export const TRUSTED_DEVICE_MAX_AGE_SECONDS = 60 * 60 * 24 * 30; // 30 Tage
|
||||
const TRUSTED_DEVICE_TOKEN_BYTES = 32;
|
||||
const TOUCH_THROTTLE_MS = 5 * 60 * 1000; // lastUsedAt hoechstens alle 5min fortschreiben
|
||||
const TOUCH_THROTTLE_MS = 5 * 60 * 1000; // throttle lastUsedAt updates to every 5 minutes
|
||||
|
||||
export type TrustedDeviceRow = Awaited<ReturnType<typeof db.trustedDevice.create>>;
|
||||
|
||||
|
||||
Reference in new issue
Block a user