Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,88 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
AdminFallbackLoginRejected,
|
||||
assertAdminFallbackLoginAllowed,
|
||||
evaluateAdminFallbackLogin,
|
||||
isAdminFallbackUiVisible,
|
||||
readAdminFallbackPolicy,
|
||||
} from "./admin-fallback.server";
|
||||
|
||||
describe("readAdminFallbackPolicy", () => {
|
||||
it("returns disabled+empty by default", () => {
|
||||
expect(readAdminFallbackPolicy({})).toEqual({ enabled: false, allowlist: [] });
|
||||
});
|
||||
|
||||
it("parses ADMIN_FALLBACK_LOGIN_EMAILS comma-separated, lowercased", () => {
|
||||
expect(
|
||||
readAdminFallbackPolicy({
|
||||
ADMIN_FALLBACK_LOGIN_ENABLED: "true",
|
||||
ADMIN_FALLBACK_LOGIN_EMAILS: " Bootstrap@example.test , ops@example.test , ",
|
||||
})
|
||||
).toEqual({
|
||||
enabled: true,
|
||||
allowlist: ["bootstrap@example.test", "ops@example.test"],
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts common truthy values", () => {
|
||||
for (const value of ["1", "true", "yes", "on", "TRUE"]) {
|
||||
expect(readAdminFallbackPolicy({ ADMIN_FALLBACK_LOGIN_ENABLED: value }).enabled).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects non-truthy values", () => {
|
||||
for (const value of ["0", "false", "no", "", "off", "maybe"]) {
|
||||
expect(readAdminFallbackPolicy({ ADMIN_FALLBACK_LOGIN_ENABLED: value }).enabled).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("evaluateAdminFallbackLogin", () => {
|
||||
it("rejects when disabled even if allowlist matches", () => {
|
||||
const result = evaluateAdminFallbackLogin("bootstrap@example.test", {
|
||||
enabled: false,
|
||||
allowlist: ["bootstrap@example.test"],
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.reason).toBe("disabled");
|
||||
});
|
||||
|
||||
it("rejects when email not in allowlist", () => {
|
||||
const result = evaluateAdminFallbackLogin("intruder@example.test", {
|
||||
enabled: true,
|
||||
allowlist: ["bootstrap@example.test"],
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.reason).toBe("email-not-allowlisted");
|
||||
});
|
||||
|
||||
it("accepts when enabled AND email in allowlist (case-insensitive)", () => {
|
||||
const result = evaluateAdminFallbackLogin("Bootstrap@Example.test", {
|
||||
enabled: true,
|
||||
allowlist: ["bootstrap@example.test"],
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("assertAdminFallbackLoginAllowed", () => {
|
||||
it("throws AdminFallbackLoginRejected when disabled", () => {
|
||||
expect(() => assertAdminFallbackLoginAllowed("anyone@example.test", { enabled: false, allowlist: [] })).toThrowError(AdminFallbackLoginRejected);
|
||||
});
|
||||
|
||||
it("throws AdminFallbackLoginRejected when not in allowlist", () => {
|
||||
expect(() => assertAdminFallbackLoginAllowed("nobody@example.test", { enabled: true, allowlist: ["other@example.test"] })).toThrowError(AdminFallbackLoginRejected);
|
||||
});
|
||||
|
||||
it("passes silently when both conditions are met", () => {
|
||||
expect(() => assertAdminFallbackLoginAllowed("ok@example.test", { enabled: true, allowlist: ["ok@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({})).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* Phase 09 Task #82 — Email/password fallback-login policy for the admin
|
||||
* panel.
|
||||
*
|
||||
* The fallback path stays in the code so operators can recover when
|
||||
* Authentik is unreachable. It is gated by:
|
||||
* - `ADMIN_FALLBACK_LOGIN_ENABLED` env (boolean, default false)
|
||||
* - `ADMIN_FALLBACK_LOGIN_EMAILS` env (comma-separated allowlist)
|
||||
*
|
||||
* Both gates must pass before a non-SSO login succeeds. Callers should
|
||||
* invoke `assertAdminFallbackLoginAllowed` before validating credentials
|
||||
* and audit-log every fallback attempt via the admin-sso audit helper.
|
||||
*/
|
||||
|
||||
const TRUE_VALUES = new Set(["1", "true", "yes", "on"]);
|
||||
|
||||
export type AdminFallbackPolicy = {
|
||||
readonly enabled: boolean;
|
||||
readonly allowlist: readonly string[];
|
||||
};
|
||||
|
||||
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);
|
||||
const rawList = env.ADMIN_FALLBACK_LOGIN_EMAILS ?? "";
|
||||
const allowlist = rawList
|
||||
.split(",")
|
||||
.map((entry) => entry.trim().toLowerCase())
|
||||
.filter((entry) => entry.length > 0);
|
||||
return { enabled, allowlist };
|
||||
}
|
||||
|
||||
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 {
|
||||
if (!policy.enabled) {
|
||||
return { ok: false, reason: "disabled" };
|
||||
}
|
||||
const normalized = email.trim().toLowerCase();
|
||||
if (!policy.allowlist.includes(normalized)) {
|
||||
return { ok: false, reason: "email-not-allowlisted" };
|
||||
}
|
||||
return { ok: true, policy };
|
||||
}
|
||||
|
||||
export class AdminFallbackLoginRejected extends Error {
|
||||
readonly reason: "disabled" | "email-not-allowlisted";
|
||||
constructor(reason: "disabled" | "email-not-allowlisted") {
|
||||
super(`Admin fallback login rejected: ${reason}`);
|
||||
this.name = "AdminFallbackLoginRejected";
|
||||
this.reason = reason;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Guard intended for the email/password login handler. Throws (not
|
||||
* returns) so callers get the same shape as `verifyUserHasPermission`.
|
||||
*/
|
||||
export function assertAdminFallbackLoginAllowed(email: string, policy?: AdminFallbackPolicy): void {
|
||||
const result = evaluateAdminFallbackLogin(email, policy);
|
||||
if (!result.ok) {
|
||||
throw new AdminFallbackLoginRejected(result.reason);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* UI-side helper: true iff the admin login page should reveal the
|
||||
* fallback toggle at all. The actual email-allowlist check happens
|
||||
* server-side on submit.
|
||||
*/
|
||||
export function isAdminFallbackUiVisible(env: Record<string, string | undefined> = process.env): boolean {
|
||||
return readAdminFallbackPolicy(env).enabled;
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
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("@toolctrl/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" },
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* 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 "@toolctrl/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,54 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { cache } from "~/utils/cache.server";
|
||||
import { checkAuthRateLimit, getAuthRateLimitKey } from "./auth-rate-limit.server";
|
||||
|
||||
describe("auth rate limiting", () => {
|
||||
beforeEach(() => {
|
||||
cache.clear();
|
||||
vi.spyOn(Date, "now").mockReturnValue(new Date("2026-05-25T12:00:00.000Z").getTime());
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
cache.clear();
|
||||
});
|
||||
|
||||
it("builds stable keys from action, client ip, and normalized identifier", () => {
|
||||
const request = new Request("https://example.test/login", {
|
||||
headers: { "x-forwarded-for": "203.0.113.10, 198.51.100.5" },
|
||||
});
|
||||
|
||||
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" })
|
||||
);
|
||||
});
|
||||
|
||||
it("allows requests up to the limit and returns retry timing after the limit", () => {
|
||||
const request = new Request("https://example.test/login", {
|
||||
headers: { "x-client-ip": "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 });
|
||||
});
|
||||
|
||||
it("starts a new window after the cached counter expires", () => {
|
||||
const request = new Request("https://example.test/mfa", {
|
||||
headers: { "x-client-ip": "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 });
|
||||
|
||||
vi.mocked(Date.now).mockReturnValue(new Date("2026-05-25T12:00:11.000Z").getTime());
|
||||
|
||||
expect(checkAuthRateLimit(options)).toEqual({ allowed: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { cache } from "~/utils/cache.server";
|
||||
import { getClientIPAddress } from "~/utils/server/IpUtils";
|
||||
|
||||
type AuthRateLimitOptions = {
|
||||
request: Request;
|
||||
action: "login" | "forgot-password" | "reset-password" | "mfa";
|
||||
identifier?: string | null;
|
||||
limit: number;
|
||||
windowMs: number;
|
||||
};
|
||||
|
||||
type AuthRateLimitResult =
|
||||
| { allowed: true }
|
||||
| { allowed: false; retryAfterSeconds: number };
|
||||
|
||||
export function getAuthRateLimitKey({ request, action, identifier }: Omit<AuthRateLimitOptions, "limit" | "windowMs">) {
|
||||
const ipAddress = getClientIPAddress(request.headers)?.toString() ?? "unknown";
|
||||
const normalizedIdentifier = identifier?.trim().toLowerCase() ?? "";
|
||||
const digest = createHash("sha256").update(`${action}:${ipAddress}:${normalizedIdentifier}`).digest("hex");
|
||||
return `auth-rate-limit:${action}:${digest}`;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
cache.set(key, { value: { count, resetAt: current.resetAt }, metadata: { createdTime: now } }, { ttl: Math.max(1, current.resetAt - now) });
|
||||
|
||||
if (count > options.limit) {
|
||||
return { allowed: false, retryAfterSeconds: Math.max(1, Math.ceil((current.resetAt - now) / 1000)) };
|
||||
}
|
||||
|
||||
return { allowed: true };
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createInvitationMagicLinkPassword } from "./invitation-password.server";
|
||||
|
||||
describe("createInvitationMagicLinkPassword", () => {
|
||||
it("creates URL-safe high-entropy one-time passwords", () => {
|
||||
const first = createInvitationMagicLinkPassword();
|
||||
const second = createInvitationMagicLinkPassword();
|
||||
|
||||
expect(first).toMatch(/^[A-Za-z0-9_-]+$/u);
|
||||
expect(first).toHaveLength(43);
|
||||
expect(second).toMatch(/^[A-Za-z0-9_-]+$/u);
|
||||
expect(second).toHaveLength(43);
|
||||
expect(second).not.toBe(first);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
|
||||
export function createInvitationMagicLinkPassword() {
|
||||
return randomBytes(32).toString("base64url");
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { cache } from "~/utils/cache.server";
|
||||
import {
|
||||
clearFailedLogins,
|
||||
getFailedLoginCount,
|
||||
LOGIN_CAPTCHA_AFTER_FAILURES,
|
||||
loginRequiresCaptcha,
|
||||
recordFailedLogin,
|
||||
} from "./login-captcha-gate.server";
|
||||
|
||||
function req() {
|
||||
return new Request("https://example.test/login");
|
||||
}
|
||||
|
||||
describe("login-captcha-gate", () => {
|
||||
beforeEach(() => {
|
||||
cache.clear();
|
||||
});
|
||||
|
||||
it("starts at zero and increments per recorded failure", () => {
|
||||
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);
|
||||
});
|
||||
|
||||
it("requires a captcha only from the configured failure threshold", () => {
|
||||
expect(loginRequiresCaptcha(0)).toBe(false);
|
||||
expect(loginRequiresCaptcha(LOGIN_CAPTCHA_AFTER_FAILURES - 1)).toBe(false);
|
||||
expect(loginRequiresCaptcha(LOGIN_CAPTCHA_AFTER_FAILURES)).toBe(true);
|
||||
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("keys per identifier so a different email does not inherit the captcha gate", () => {
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
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.
|
||||
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;
|
||||
|
||||
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}`;
|
||||
}
|
||||
|
||||
export function getFailedLoginCount(args: Identified): number {
|
||||
const entry = cache.get(failedLoginKey(args))?.value as FailedLoginEntry | undefined;
|
||||
if (!entry || entry.resetAt <= Date.now()) {
|
||||
return 0;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
export function clearFailedLogins(args: Identified): void {
|
||||
cache.delete(failedLoginKey(args));
|
||||
}
|
||||
|
||||
export function loginRequiresCaptcha(failedCount: number): boolean {
|
||||
return failedCount >= LOGIN_CAPTCHA_AFTER_FAILURES;
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { consumeMagicLinkToken, createSignedMagicLinkToken, issueMagicLink, verifySignedMagicLinkToken } from "./magic-link.server";
|
||||
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";
|
||||
|
||||
vi.mock("@toolctrl/config", () => ({
|
||||
loadRequiredWebConfig: vi.fn(() => ({ cryptoSecret: "test-secret", sessionSecret: "session-secret" })),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: {
|
||||
magicLinkToken: {
|
||||
create: vi.fn(),
|
||||
findUnique: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
user: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/url.server", () => ({
|
||||
getAbsoluteUrl: vi.fn((_request: Request, path: string) => `https://example.com${path}`),
|
||||
}));
|
||||
|
||||
vi.mock("~/modules/emails/services/TransactionalEmailQueue.server", () => ({
|
||||
queueTransactionalEmail: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/appConfiguration.db.server", () => ({
|
||||
getAppConfiguration: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/mail-translator.server", () => ({
|
||||
getMailTranslator: vi.fn(),
|
||||
getMailTranslatorFromRequest: vi.fn(),
|
||||
}));
|
||||
|
||||
const getAppConfigurationMock = vi.mocked(getAppConfiguration);
|
||||
const getMailTranslatorMock = vi.mocked(getMailTranslator);
|
||||
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 userFindUniqueMock = vi.mocked(db.user.findUnique);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
getAppConfigurationMock.mockResolvedValue({
|
||||
app: { name: "Acme Portal" },
|
||||
email: { fromName: "Acme Support", supportEmail: "support@acme.test" },
|
||||
branding: { logo: "https://assets.example.com/logo.png", favicon: null },
|
||||
} as Awaited<ReturnType<typeof getAppConfiguration>>);
|
||||
getMailTranslatorMock.mockResolvedValue({
|
||||
locale: "de",
|
||||
t: (key, vars) => (key === "magicLink.subject" ? `Dein Anmeldelink für ${vars?.productName}` : key),
|
||||
});
|
||||
getMailTranslatorFromRequestMock.mockResolvedValue({
|
||||
locale: "en",
|
||||
t: (key) => key,
|
||||
});
|
||||
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>>);
|
||||
userFindUniqueMock.mockResolvedValue({ locale: "de" } as Awaited<ReturnType<typeof db.user.findUnique>>);
|
||||
});
|
||||
|
||||
describe("issueMagicLink", () => {
|
||||
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"),
|
||||
userId: "user_1",
|
||||
email: "ada@example.com",
|
||||
name: "Ada",
|
||||
now: new Date("2026-05-19T12:00:00.000Z"),
|
||||
});
|
||||
|
||||
expect(result.token).toMatch(/\./);
|
||||
// Translator is resolved against the user's locale for the subject.
|
||||
expect(getMailTranslatorMock).toHaveBeenCalledWith("de");
|
||||
expect(getMailTranslatorFromRequestMock).not.toHaveBeenCalled();
|
||||
expect(queueTransactionalEmailMock).toHaveBeenCalledOnce();
|
||||
expect(queueTransactionalEmailMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
to: "ada@example.com",
|
||||
alias: "magic-link",
|
||||
subject: "Dein Anmeldelink für Acme Portal",
|
||||
userId: "user_1",
|
||||
data: expect.objectContaining({
|
||||
action_url: expect.stringContaining("https://example.com/auth/magic-link?token="),
|
||||
name: "Ada",
|
||||
expires_in_minutes: "15",
|
||||
}),
|
||||
priorityOverride: "critical",
|
||||
})
|
||||
);
|
||||
|
||||
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).not.toContain("{i18nT(");
|
||||
});
|
||||
});
|
||||
|
||||
describe("signed magic-link tokens", () => {
|
||||
it("verifies a signed token payload and rejects malformed or tampered tokens", () => {
|
||||
const issued = createSignedMagicLinkToken({
|
||||
userId: "user_1",
|
||||
tokenId: "token_1",
|
||||
now: new Date("2026-05-19T12:00:00.000Z"),
|
||||
purpose: "reset",
|
||||
});
|
||||
|
||||
expect(verifySignedMagicLinkToken(issued.token)).toMatchObject({
|
||||
sub: "user_1",
|
||||
jti: "token_1",
|
||||
p: "reset",
|
||||
v: "v1",
|
||||
});
|
||||
expect(verifySignedMagicLinkToken("not-a-token")).toBeNull();
|
||||
expect(verifySignedMagicLinkToken(`${issued.token}.extra`)).toBeNull();
|
||||
expect(verifySignedMagicLinkToken(`${issued.token.slice(0, -1)}x`)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("consumeMagicLinkToken", () => {
|
||||
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" });
|
||||
magicLinkTokenFindUniqueMock.mockResolvedValue({
|
||||
id: "token_1",
|
||||
userId: "user_1",
|
||||
tokenHash: issued.tokenHash,
|
||||
expiresAt: issued.expiresAt,
|
||||
consumedAt: null,
|
||||
} as Awaited<ReturnType<typeof db.magicLinkToken.findUnique>>);
|
||||
|
||||
await expect(consumeMagicLinkToken(issued.token, { now, expectedPurpose: "login" })).resolves.toEqual({
|
||||
ok: true,
|
||||
userId: "user_1",
|
||||
tokenId: "token_1",
|
||||
purpose: "login",
|
||||
});
|
||||
expect(magicLinkTokenUpdateMock).toHaveBeenCalledWith({
|
||||
where: { id: "token_1" },
|
||||
data: { consumedAt: now },
|
||||
});
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
it("rejects expired signed payloads before reading the database", async () => {
|
||||
const issuedAt = new Date("2026-05-19T12:00:00.000Z");
|
||||
const now = new Date("2026-05-19T12:16:00.000Z");
|
||||
const issued = createSignedMagicLinkToken({ userId: "user_1", tokenId: "token_1", now: issuedAt });
|
||||
|
||||
await expect(consumeMagicLinkToken(issued.token, { now })).resolves.toEqual({ ok: false, reason: "expired" });
|
||||
expect(magicLinkTokenFindUniqueMock).not.toHaveBeenCalled();
|
||||
expect(magicLinkTokenUpdateMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects stored tokens that expired after a valid signed payload was issued", async () => {
|
||||
const now = new Date("2026-05-19T12:00:00.000Z");
|
||||
const issued = createSignedMagicLinkToken({
|
||||
userId: "user_1",
|
||||
tokenId: "token_1",
|
||||
now,
|
||||
ttlMinutes: 60,
|
||||
});
|
||||
magicLinkTokenFindUniqueMock.mockResolvedValue({
|
||||
id: "token_1",
|
||||
userId: "user_1",
|
||||
tokenHash: issued.tokenHash,
|
||||
expiresAt: new Date("2026-05-19T11:59:59.999Z"),
|
||||
consumedAt: null,
|
||||
} as Awaited<ReturnType<typeof db.magicLinkToken.findUnique>>);
|
||||
|
||||
await expect(consumeMagicLinkToken(issued.token, { now })).resolves.toEqual({ ok: false, reason: "expired" });
|
||||
expect(magicLinkTokenUpdateMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects replayed tokens before writing a new consumedAt", 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: new Date("2026-05-19T12:01:00.000Z"),
|
||||
} as Awaited<ReturnType<typeof db.magicLinkToken.findUnique>>);
|
||||
|
||||
await expect(consumeMagicLinkToken(issued.token, { now })).resolves.toEqual({ ok: false, reason: "replayed" });
|
||||
expect(magicLinkTokenUpdateMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects purpose mismatches without consuming the token", async () => {
|
||||
const now = new Date("2026-05-19T12:00:00.000Z");
|
||||
const issued = createSignedMagicLinkToken({ userId: "user_1", tokenId: "token_1", now, purpose: "reset" });
|
||||
magicLinkTokenFindUniqueMock.mockResolvedValue({
|
||||
id: "token_1",
|
||||
userId: "user_1",
|
||||
tokenHash: issued.tokenHash,
|
||||
expiresAt: issued.expiresAt,
|
||||
consumedAt: null,
|
||||
} 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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,236 @@
|
||||
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { resolveTransactionalBrandTokens } from "@toolctrl/brand";
|
||||
import { loadRequiredWebConfig } from "@toolctrl/config";
|
||||
import { buildBrand, renderTransactionalEmail } from "@toolctrl/mail";
|
||||
import { db } from "~/utils/db.server";
|
||||
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";
|
||||
|
||||
export const MAGIC_LINK_TOKEN_TTL_MINUTES = 15;
|
||||
const MAGIC_LINK_TOKEN_VERSION = "v1";
|
||||
|
||||
export type MagicLinkPurpose = "login" | "invitation" | "reset";
|
||||
|
||||
type MagicLinkPayload = {
|
||||
exp: string;
|
||||
iat: string;
|
||||
jti: string;
|
||||
sub: string;
|
||||
/**
|
||||
* Discriminator for what the token is allowed to do. Verifiers pass an
|
||||
* expected value to consumeMagicLinkToken so a "login" token can't be
|
||||
* replayed against an "invitation" endpoint. Older tokens that predate
|
||||
* this field (pre-v2 payloads) are treated as "login".
|
||||
*/
|
||||
p?: MagicLinkPurpose;
|
||||
v: typeof MAGIC_LINK_TOKEN_VERSION;
|
||||
};
|
||||
|
||||
type MagicLinkConsumeResult =
|
||||
| { ok: true; userId: string; tokenId: string; purpose: MagicLinkPurpose }
|
||||
| { ok: false; reason: "expired" | "invalid" | "not-found" | "replayed" | "purpose-mismatch" };
|
||||
|
||||
function getSigningSecret() {
|
||||
const { cryptoSecret, sessionSecret } = loadRequiredWebConfig();
|
||||
const secret = cryptoSecret || sessionSecret;
|
||||
if (!secret) {
|
||||
throw new Error("CRYPTO_SECRET or SESSION_SECRET is required for magic-link auth.");
|
||||
}
|
||||
return secret;
|
||||
}
|
||||
|
||||
function base64UrlEncode(value: string) {
|
||||
return Buffer.from(value).toString("base64url");
|
||||
}
|
||||
|
||||
function base64UrlDecode(value: string) {
|
||||
return Buffer.from(value, "base64url").toString("utf8");
|
||||
}
|
||||
|
||||
function signPayload(encodedPayload: string, secret = getSigningSecret()) {
|
||||
return createHmac("sha256", secret).update(encodedPayload).digest("base64url");
|
||||
}
|
||||
|
||||
function hashToken(token: string) {
|
||||
return createHash("sha256").update(token).digest("hex");
|
||||
}
|
||||
|
||||
function signaturesMatch(actual: string, expected: string) {
|
||||
const actualBuffer = Buffer.from(actual);
|
||||
const expectedBuffer = Buffer.from(expected);
|
||||
return actualBuffer.length === expectedBuffer.length && timingSafeEqual(actualBuffer, expectedBuffer);
|
||||
}
|
||||
|
||||
async function getMagicLinkMailTranslator(request: Request, userId: string) {
|
||||
const userDelegate = (db as { user?: { findUnique: typeof db.user.findUnique } }).user;
|
||||
if (!userDelegate) {
|
||||
return getMailTranslatorFromRequest(request);
|
||||
}
|
||||
|
||||
const user = await userDelegate.findUnique({
|
||||
where: { id: userId },
|
||||
select: { locale: true },
|
||||
});
|
||||
return user?.locale ? getMailTranslator(user.locale) : getMailTranslatorFromRequest(request);
|
||||
}
|
||||
|
||||
function toBrandConfiguration(appConfiguration: Awaited<ReturnType<typeof getAppConfiguration>>) {
|
||||
return {
|
||||
productName: appConfiguration.app?.name,
|
||||
supportEmail: appConfiguration.email?.supportEmail,
|
||||
supportFromName: appConfiguration.email?.fromName,
|
||||
emailFromName: appConfiguration.email?.fromName,
|
||||
logoUrl: appConfiguration.branding?.logo,
|
||||
faviconUrl: appConfiguration.branding?.favicon,
|
||||
};
|
||||
}
|
||||
|
||||
export function createSignedMagicLinkToken({
|
||||
userId,
|
||||
tokenId = randomBytes(16).toString("hex"),
|
||||
now = new Date(),
|
||||
ttlMinutes = MAGIC_LINK_TOKEN_TTL_MINUTES,
|
||||
purpose = "login",
|
||||
}: {
|
||||
userId: string;
|
||||
tokenId?: string;
|
||||
now?: Date;
|
||||
ttlMinutes?: number;
|
||||
purpose?: MagicLinkPurpose;
|
||||
}) {
|
||||
const expiresAt = new Date(now.getTime() + ttlMinutes * 60 * 1000);
|
||||
const payload: MagicLinkPayload = {
|
||||
exp: expiresAt.toISOString(),
|
||||
iat: now.toISOString(),
|
||||
jti: tokenId,
|
||||
sub: userId,
|
||||
p: purpose,
|
||||
v: MAGIC_LINK_TOKEN_VERSION,
|
||||
};
|
||||
const encodedPayload = base64UrlEncode(JSON.stringify(payload));
|
||||
const signature = signPayload(encodedPayload);
|
||||
const token = `${encodedPayload}.${signature}`;
|
||||
|
||||
return {
|
||||
expiresAt,
|
||||
token,
|
||||
tokenHash: hashToken(token),
|
||||
tokenId,
|
||||
};
|
||||
}
|
||||
|
||||
export function verifySignedMagicLinkToken(token: string): MagicLinkPayload | null {
|
||||
const [encodedPayload, signature, extra] = token.split(".");
|
||||
if (!encodedPayload || !signature || extra !== undefined) {
|
||||
return null;
|
||||
}
|
||||
const expectedSignature = signPayload(encodedPayload);
|
||||
if (!signaturesMatch(signature, expectedSignature)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = JSON.parse(base64UrlDecode(encodedPayload)) as Partial<MagicLinkPayload>;
|
||||
if (payload.v !== MAGIC_LINK_TOKEN_VERSION || !payload.jti || !payload.sub || !payload.exp || !payload.iat) {
|
||||
return null;
|
||||
}
|
||||
return payload as MagicLinkPayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function issueMagicLink({
|
||||
request,
|
||||
userId,
|
||||
email,
|
||||
name,
|
||||
redirectPath = "/auth/magic-link",
|
||||
now = new Date(),
|
||||
purpose = "login",
|
||||
}: {
|
||||
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({
|
||||
data: {
|
||||
id: token.tokenId,
|
||||
userId,
|
||||
tokenHash: token.tokenHash,
|
||||
expiresAt: token.expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
const actionUrl = getAbsoluteUrl(request, `${redirectPath}?token=${encodeURIComponent(token.token)}`);
|
||||
const emailData = { action_url: actionUrl, name, expires_in_minutes: String(MAGIC_LINK_TOKEN_TTL_MINUTES) };
|
||||
const mailTranslator = await getMagicLinkMailTranslator(request, userId);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const brand = buildBrand(resolveTransactionalBrandTokens(toBrandConfiguration(appConfiguration)));
|
||||
const { html } = renderTransactionalEmail("magic-link", {
|
||||
brand,
|
||||
recipientName: name ?? undefined,
|
||||
actionUrl,
|
||||
expiresInMinutes: MAGIC_LINK_TOKEN_TTL_MINUTES,
|
||||
});
|
||||
const subject = mailTranslator.t("magicLink.subject", { productName: brand.productName });
|
||||
|
||||
await queueTransactionalEmail({
|
||||
to: email,
|
||||
alias: "magic-link",
|
||||
subject,
|
||||
body: html,
|
||||
userId,
|
||||
data: emailData,
|
||||
priorityOverride: "critical",
|
||||
});
|
||||
|
||||
return {
|
||||
expiresAt: token.expiresAt,
|
||||
token: token.token,
|
||||
};
|
||||
}
|
||||
|
||||
export async function consumeMagicLinkToken(token: string, options: { now?: Date; expectedPurpose?: MagicLinkPurpose } = {}): Promise<MagicLinkConsumeResult> {
|
||||
const now = options.now ?? new Date();
|
||||
const payload = verifySignedMagicLinkToken(token);
|
||||
if (!payload) {
|
||||
return { ok: false, reason: "invalid" };
|
||||
}
|
||||
if (new Date(payload.exp).getTime() <= now.getTime()) {
|
||||
return { ok: false, reason: "expired" };
|
||||
}
|
||||
|
||||
const tokenHash = hashToken(token);
|
||||
const storedToken = await db.magicLinkToken.findUnique({ where: { id: payload.jti } });
|
||||
if (!storedToken || storedToken.userId !== payload.sub || storedToken.tokenHash !== tokenHash) {
|
||||
return { ok: false, reason: "not-found" };
|
||||
}
|
||||
if (storedToken.consumedAt) {
|
||||
return { ok: false, reason: "replayed" };
|
||||
}
|
||||
if (storedToken.expiresAt.getTime() <= now.getTime()) {
|
||||
return { ok: false, reason: "expired" };
|
||||
}
|
||||
|
||||
// Pre-v2 tokens lack p; treat them as "login" so legacy outstanding tokens
|
||||
// still work during the rollout. New tokens always have an explicit p.
|
||||
const actualPurpose: MagicLinkPurpose = (payload.p as MagicLinkPurpose | undefined) ?? "login";
|
||||
if (options.expectedPurpose && options.expectedPurpose !== actualPurpose) {
|
||||
return { ok: false, reason: "purpose-mismatch" };
|
||||
}
|
||||
|
||||
await db.magicLinkToken.update({
|
||||
where: { id: payload.jti },
|
||||
data: { consumedAt: now },
|
||||
});
|
||||
|
||||
return { ok: true, userId: payload.sub, tokenId: payload.jti, purpose: actualPurpose };
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildRemindCookie,
|
||||
evaluatePasswordPolicyBanner,
|
||||
PASSWORD_POLICY_REMIND_COOKIE,
|
||||
PASSWORD_POLICY_REMIND_DURATION_MS,
|
||||
readRemindAfterCookie,
|
||||
} from "./password-policy-banner.server.js";
|
||||
|
||||
describe("evaluatePasswordPolicyBanner", () => {
|
||||
it("hides the banner when the session flag is not set", () => {
|
||||
expect(evaluatePasswordPolicyBanner({ policyOutdated: false })).toEqual({ show: false, reason: "not_outdated" });
|
||||
});
|
||||
|
||||
it("shows the banner when the flag is set and no snooze cookie is present", () => {
|
||||
const result = evaluatePasswordPolicyBanner({ policyOutdated: true, cookieHeader: null });
|
||||
expect(result.show).toBe(true);
|
||||
expect(result.reason).toBe("show");
|
||||
});
|
||||
|
||||
it("hides the banner when the snooze cookie is still in the future", () => {
|
||||
const now = 1_700_000_000_000;
|
||||
const future = now + 60_000;
|
||||
const result = evaluatePasswordPolicyBanner({
|
||||
policyOutdated: true,
|
||||
cookieHeader: `${PASSWORD_POLICY_REMIND_COOKIE}=${future}`,
|
||||
now,
|
||||
});
|
||||
expect(result.show).toBe(false);
|
||||
expect(result.reason).toBe("remind_active");
|
||||
});
|
||||
|
||||
it("shows the banner once the snooze cookie has expired", () => {
|
||||
const now = 1_700_000_000_000;
|
||||
const past = now - 1;
|
||||
const result = evaluatePasswordPolicyBanner({
|
||||
policyOutdated: true,
|
||||
cookieHeader: `${PASSWORD_POLICY_REMIND_COOKIE}=${past}`,
|
||||
now,
|
||||
});
|
||||
expect(result.show).toBe(true);
|
||||
});
|
||||
|
||||
it("ignores unrelated cookies", () => {
|
||||
const result = evaluatePasswordPolicyBanner({
|
||||
policyOutdated: true,
|
||||
cookieHeader: "session=abc; theme=dark",
|
||||
});
|
||||
expect(result.show).toBe(true);
|
||||
});
|
||||
|
||||
it("treats a malformed cookie value as 'no snooze'", () => {
|
||||
const result = evaluatePasswordPolicyBanner({
|
||||
policyOutdated: true,
|
||||
cookieHeader: `${PASSWORD_POLICY_REMIND_COOKIE}=not-a-number`,
|
||||
});
|
||||
expect(result.show).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("readRemindAfterCookie", () => {
|
||||
it("returns undefined when the header is missing", () => {
|
||||
expect(readRemindAfterCookie(undefined)).toBeUndefined();
|
||||
expect(readRemindAfterCookie("")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("parses an unsigned integer", () => {
|
||||
expect(readRemindAfterCookie(`${PASSWORD_POLICY_REMIND_COOKIE}=12345`)).toBe(12345);
|
||||
});
|
||||
|
||||
it("returns undefined for a negative or zero value", () => {
|
||||
expect(readRemindAfterCookie(`${PASSWORD_POLICY_REMIND_COOKIE}=-1`)).toBeUndefined();
|
||||
expect(readRemindAfterCookie(`${PASSWORD_POLICY_REMIND_COOKIE}=0`)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("decodes URL-encoded values", () => {
|
||||
expect(readRemindAfterCookie(`${PASSWORD_POLICY_REMIND_COOKIE}=${encodeURIComponent("123")}`)).toBe(123);
|
||||
});
|
||||
|
||||
it("treats malformed percent-encoding as a malformed snooze value", () => {
|
||||
expect(readRemindAfterCookie(`${PASSWORD_POLICY_REMIND_COOKIE}=%E0%A4%A`)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("ignores other cookies on the line", () => {
|
||||
expect(readRemindAfterCookie(`a=1; ${PASSWORD_POLICY_REMIND_COOKIE}=42; b=2`)).toBe(42);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildRemindCookie", () => {
|
||||
it("emits the expected Set-Cookie shape", () => {
|
||||
const now = 1_700_000_000_000;
|
||||
const cookie = buildRemindCookie(now);
|
||||
const expectedExpiry = now + PASSWORD_POLICY_REMIND_DURATION_MS;
|
||||
expect(cookie).toContain(`${PASSWORD_POLICY_REMIND_COOKIE}=${expectedExpiry}`);
|
||||
expect(cookie).toContain("Path=/");
|
||||
expect(cookie).toContain(`Max-Age=${Math.floor(PASSWORD_POLICY_REMIND_DURATION_MS / 1000)}`);
|
||||
expect(cookie).toContain("SameSite=Lax");
|
||||
});
|
||||
|
||||
it("produces a value the parser can read back", () => {
|
||||
const now = 1_700_000_000_000;
|
||||
const cookie = buildRemindCookie(now);
|
||||
// Strip attributes; the parser only cares about the name=value segment.
|
||||
const firstSegment = cookie.split(";")[0];
|
||||
expect(readRemindAfterCookie(firstSegment)).toBe(now + PASSWORD_POLICY_REMIND_DURATION_MS);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
// Password-policy soft-banner helpers (Phase 01 / #27).
|
||||
//
|
||||
// validatePassword-based hard-enforcement is already shipped across the
|
||||
// registration / reset / profile / admin-reset / invitation write paths.
|
||||
// What lives here is the *soft* path: once a user has already authenticated
|
||||
// with a password that does not satisfy the current policy, we surface a
|
||||
// dismissible banner pointing them at the change-password page.
|
||||
//
|
||||
// Two inputs decide whether the banner renders:
|
||||
//
|
||||
// 1. A session flag `passwordPolicyOutdated`. Set at login time by
|
||||
// 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
|
||||
// route. While the timestamp is still in the future the banner stays
|
||||
// hidden even when the session flag is on.
|
||||
//
|
||||
// Everything here is server-only and dependency-free so it can be unit
|
||||
// tested without spinning up a React Router request.
|
||||
|
||||
export const PASSWORD_POLICY_REMIND_COOKIE = "pwPolicyRemindAfter";
|
||||
export const PASSWORD_POLICY_REMIND_DURATION_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export type PasswordPolicyBannerInput = {
|
||||
/** Session flag captured at login time. */
|
||||
policyOutdated: boolean;
|
||||
/** Raw `Cookie` header value, may be null/undefined. */
|
||||
cookieHeader?: string | null;
|
||||
/** Override `Date.now()` for deterministic tests. */
|
||||
now?: number;
|
||||
};
|
||||
|
||||
export type PasswordPolicyBannerState = {
|
||||
show: boolean;
|
||||
reason?: "not_outdated" | "remind_active" | "show";
|
||||
};
|
||||
|
||||
/**
|
||||
* Pure decision function. The route loader passes the session flag plus the
|
||||
* raw Cookie header and gets back a `{ show }` it can return to the
|
||||
* component without any further work.
|
||||
*/
|
||||
export function evaluatePasswordPolicyBanner(input: PasswordPolicyBannerInput): PasswordPolicyBannerState {
|
||||
if (!input.policyOutdated) {
|
||||
return { show: false, reason: "not_outdated" };
|
||||
}
|
||||
const remindAfter = readRemindAfterCookie(input.cookieHeader ?? undefined);
|
||||
const now = input.now ?? Date.now();
|
||||
if (remindAfter !== undefined && remindAfter > now) {
|
||||
return { show: false, reason: "remind_active" };
|
||||
}
|
||||
return { show: true, reason: "show" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the snooze cookie. Returns undefined when the cookie is missing or
|
||||
* malformed — the caller treats that the same as "no snooze active".
|
||||
*/
|
||||
export function readRemindAfterCookie(cookieHeader: string | undefined): number | undefined {
|
||||
if (!cookieHeader) return undefined;
|
||||
for (const segment of cookieHeader.split(";")) {
|
||||
const trimmed = segment.trim();
|
||||
if (!trimmed.startsWith(`${PASSWORD_POLICY_REMIND_COOKIE}=`)) continue;
|
||||
const raw = trimmed.slice(PASSWORD_POLICY_REMIND_COOKIE.length + 1);
|
||||
if (!raw) return undefined;
|
||||
const decoded = (() => {
|
||||
try {
|
||||
return decodeURIComponent(raw);
|
||||
} catch {
|
||||
return raw;
|
||||
}
|
||||
})();
|
||||
const parsed = Number.parseInt(decoded, 10);
|
||||
if (Number.isFinite(parsed) && parsed > 0) return parsed;
|
||||
return undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the `Set-Cookie` header value for the "Remind me in 7 days" action.
|
||||
* Kept here so tests cover the exact serialization shape.
|
||||
*/
|
||||
export function buildRemindCookie(now: number = Date.now()): string {
|
||||
const expires = now + PASSWORD_POLICY_REMIND_DURATION_MS;
|
||||
const maxAgeSeconds = Math.floor(PASSWORD_POLICY_REMIND_DURATION_MS / 1000);
|
||||
return `${PASSWORD_POLICY_REMIND_COOKIE}=${expires}; Path=/; Max-Age=${maxAgeSeconds}; SameSite=Lax`;
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
// @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";
|
||||
|
||||
function sha1Upper(value: string): string {
|
||||
return createHash("sha1").update(value).digest("hex").toUpperCase();
|
||||
}
|
||||
|
||||
function hibpFetcherFor(pwnedPasswords: Map<string, number>): typeof fetch {
|
||||
return (async (input: RequestInfo | URL) => {
|
||||
const url = typeof input === "string" ? input : (input as URL).toString();
|
||||
const prefix = url.slice(url.lastIndexOf("/") + 1).toUpperCase();
|
||||
const matches: string[] = [];
|
||||
for (const [password, count] of pwnedPasswords) {
|
||||
const hash = sha1Upper(password);
|
||||
if (hash.startsWith(prefix)) {
|
||||
matches.push(`${hash.slice(5)}:${count}`);
|
||||
}
|
||||
}
|
||||
matches.push("0".repeat(35) + ":0"); // padding row
|
||||
return new Response(matches.join("\n"), { status: 200 });
|
||||
}) as unknown as typeof fetch;
|
||||
}
|
||||
|
||||
const ALL_FLAGS_OFF = {
|
||||
minLength: 1,
|
||||
requireUpper: false,
|
||||
requireLower: false,
|
||||
requireDigit: false,
|
||||
requireSpecial: false,
|
||||
hibpCheck: false,
|
||||
hibpMaxOccurrences: 0,
|
||||
};
|
||||
|
||||
describe("validatePassword", () => {
|
||||
test("rejects empty input with code 'empty'", async () => {
|
||||
const result = await validatePassword("", {}, { policy: ALL_FLAGS_OFF });
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toEqual([{ code: "auth.password.errors.empty" }]);
|
||||
});
|
||||
|
||||
test("enforces minLength at the boundary", async () => {
|
||||
const policy = { ...ALL_FLAGS_OFF, minLength: 12 };
|
||||
expect((await validatePassword("12345678901", {}, { policy })).valid).toBe(false);
|
||||
expect((await validatePassword("123456789012", {}, { policy })).valid).toBe(true);
|
||||
});
|
||||
|
||||
test("flags missingUpper / missingLower / missingDigit / missingSpecial independently", async () => {
|
||||
const policy = { ...ALL_FLAGS_OFF, requireUpper: true, requireLower: true, requireDigit: true, requireSpecial: true };
|
||||
const result = await validatePassword("abcdef", {}, { policy });
|
||||
const codes = result.errors.map((e) => e.code);
|
||||
expect(codes).toContain("auth.password.errors.missingUpper");
|
||||
expect(codes).toContain("auth.password.errors.missingDigit");
|
||||
expect(codes).toContain("auth.password.errors.missingSpecial");
|
||||
expect(codes).not.toContain("auth.password.errors.missingLower");
|
||||
});
|
||||
|
||||
test("accepts a password that meets every active rule", async () => {
|
||||
const policy = { ...ALL_FLAGS_OFF, minLength: 12, requireUpper: true, requireLower: true, requireDigit: true, requireSpecial: true };
|
||||
const result = await validatePassword("Strong-Pass1word!", {}, { policy });
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.errors).toEqual([]);
|
||||
});
|
||||
|
||||
test("rejects passwords that contain the email local-part", async () => {
|
||||
const policy = { ...ALL_FLAGS_OFF, minLength: 1 };
|
||||
const result = await validatePassword("grace1234567890", { email: "grace@example.com" }, { policy });
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors.map((e) => e.code)).toContain("auth.password.errors.containsEmail");
|
||||
});
|
||||
|
||||
test("ignores email local-parts shorter than 3 chars to avoid false positives", async () => {
|
||||
const policy = { ...ALL_FLAGS_OFF, minLength: 1 };
|
||||
const result = await validatePassword("any-password-here", { email: "x@example.com" }, { policy });
|
||||
expect(result.errors.map((e) => e.code)).not.toContain("auth.password.errors.containsEmail");
|
||||
});
|
||||
|
||||
test("HIBP-pwned password is rejected", async () => {
|
||||
const pwnedPasswords = new Map<string, number>([["Password123!", 12345]]);
|
||||
const policy = { ...ALL_FLAGS_OFF, hibpCheck: true };
|
||||
const result = await validatePassword("Password123!", {}, { policy, fetcher: hibpFetcherFor(pwnedPasswords) });
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors.map((e) => e.code)).toContain("auth.password.errors.pwned");
|
||||
});
|
||||
|
||||
test("HIBP-clean password passes", async () => {
|
||||
const pwnedPasswords = new Map<string, number>();
|
||||
const policy = { ...ALL_FLAGS_OFF, hibpCheck: true };
|
||||
const result = await validatePassword("Never-Pwned-XyZ-12345", {}, { policy, fetcher: hibpFetcherFor(pwnedPasswords) });
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.hibpBypassed).toBeUndefined();
|
||||
});
|
||||
|
||||
test("HIBP-pwned but under hibpMaxOccurrences is accepted", async () => {
|
||||
const pwnedPasswords = new Map<string, number>([["RarelyLeaked-XyZ", 1]]);
|
||||
const policy = { ...ALL_FLAGS_OFF, hibpCheck: true, hibpMaxOccurrences: 5 };
|
||||
const result = await validatePassword("RarelyLeaked-XyZ", {}, { policy, fetcher: hibpFetcherFor(pwnedPasswords) });
|
||||
expect(result.valid).toBe(true);
|
||||
});
|
||||
|
||||
test("HIBP-5xx fails open with hibpBypassed=true", async () => {
|
||||
const fetcher = (async () => new Response("", { status: 503 })) as unknown as typeof fetch;
|
||||
const policy = { ...ALL_FLAGS_OFF, hibpCheck: true };
|
||||
const result = await validatePassword("Long-Enough-Password", {}, { policy, fetcher });
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.hibpBypassed).toBe(true);
|
||||
});
|
||||
|
||||
test("HIBP-network-error fails open with hibpBypassed=true", async () => {
|
||||
const fetcher = vi.fn(async () => {
|
||||
throw new Error("ENOTFOUND api.pwnedpasswords.com");
|
||||
}) as unknown as typeof fetch;
|
||||
const policy = { ...ALL_FLAGS_OFF, hibpCheck: true };
|
||||
const result = await validatePassword("Long-Enough-Password", {}, { policy, fetcher });
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.hibpBypassed).toBe(true);
|
||||
});
|
||||
|
||||
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 });
|
||||
expect(result.valid).toBe(true);
|
||||
});
|
||||
|
||||
test("absurdly long passwords are rejected by the ABSOLUTE_MAX_LENGTH guard", async () => {
|
||||
const policy = { ...ALL_FLAGS_OFF, minLength: 1 };
|
||||
const result = await validatePassword("a".repeat(2048), {}, { policy });
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors.map((e) => e.code)).toContain("auth.password.errors.tooLong");
|
||||
});
|
||||
});
|
||||
|
||||
describe("loadPasswordPolicy", () => {
|
||||
test("uses OWASP-aligned defaults when env is empty", () => {
|
||||
const policy = loadPasswordPolicy({});
|
||||
expect(policy.minLength).toBe(12);
|
||||
expect(policy.requireUpper).toBe(true);
|
||||
expect(policy.requireLower).toBe(true);
|
||||
expect(policy.requireDigit).toBe(true);
|
||||
expect(policy.requireSpecial).toBe(false);
|
||||
expect(policy.hibpCheck).toBe(true);
|
||||
expect(policy.hibpMaxOccurrences).toBe(0);
|
||||
});
|
||||
|
||||
test("reads overrides from env vars", () => {
|
||||
const policy = loadPasswordPolicy({
|
||||
AUTH_PASSWORD_MIN_LENGTH: "16",
|
||||
AUTH_PASSWORD_REQUIRE_UPPER: "false",
|
||||
AUTH_PASSWORD_REQUIRE_DIGIT: "no",
|
||||
AUTH_PASSWORD_REQUIRE_SPECIAL: "true",
|
||||
AUTH_PASSWORD_HIBP_CHECK: "0",
|
||||
AUTH_PASSWORD_HIBP_MAX_OCCURRENCES: "10",
|
||||
});
|
||||
expect(policy.minLength).toBe(16);
|
||||
expect(policy.requireUpper).toBe(false);
|
||||
expect(policy.requireLower).toBe(true);
|
||||
expect(policy.requireDigit).toBe(false);
|
||||
expect(policy.requireSpecial).toBe(true);
|
||||
expect(policy.hibpCheck).toBe(false);
|
||||
expect(policy.hibpMaxOccurrences).toBe(10);
|
||||
});
|
||||
|
||||
test("invalid env values fall back to defaults", () => {
|
||||
const policy = loadPasswordPolicy({
|
||||
AUTH_PASSWORD_MIN_LENGTH: "garbage",
|
||||
AUTH_PASSWORD_REQUIRE_UPPER: "maybe",
|
||||
});
|
||||
expect(policy.minLength).toBe(12);
|
||||
expect(policy.requireUpper).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("prototype compatibility shims", () => {
|
||||
test("isPasswordPwned returns true only when HIBP reports the password above the threshold", async () => {
|
||||
const fetcher = hibpFetcherFor(new Map<string, number>([["Password123!", 12345]]));
|
||||
await expect(isPasswordPwned("Password123!", fetcher)).resolves.toBe(true);
|
||||
await expect(isPasswordPwned("Never-Pwned-XyZ-12345", fetcher)).resolves.toBe(false);
|
||||
});
|
||||
|
||||
test("validatePasswordPolicy maps canonical errors to legacy issue names", async () => {
|
||||
const fetcher = hibpFetcherFor(new Map<string, number>([["short", 99]]));
|
||||
await expect(validatePasswordPolicy("short", { fetchImpl: fetcher })).resolves.toEqual({
|
||||
ok: false,
|
||||
issues: ["too-short", "pwned"],
|
||||
});
|
||||
});
|
||||
|
||||
test("validatePasswordPolicy reports unavailable HIBP checks as a legacy issue", async () => {
|
||||
const fetcher = vi.fn(async () => {
|
||||
throw new Error("network down");
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
await expect(validatePasswordPolicy("Long-Enough-Password", { fetchImpl: fetcher })).resolves.toEqual({
|
||||
ok: false,
|
||||
issues: ["pwned-check-unavailable"],
|
||||
});
|
||||
});
|
||||
|
||||
test("assertPasswordPolicy resolves successful checks and throws with legacy issues on failure", async () => {
|
||||
const cleanFetcher = hibpFetcherFor(new Map());
|
||||
await expect(assertPasswordPolicy("Strong-Enough-Password1", { fetchImpl: cleanFetcher })).resolves.toEqual({
|
||||
ok: true,
|
||||
issues: [],
|
||||
});
|
||||
await expect(assertPasswordPolicy("short", { fetchImpl: cleanFetcher })).rejects.toThrow(/too-short/u);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,224 @@
|
||||
// Central password validation. Every password-write endpoint MUST go through
|
||||
// validatePassword(); inline length / character-class checks are forbidden.
|
||||
// Configuration is env-driven so operators can tighten the policy without a
|
||||
// code deploy.
|
||||
//
|
||||
// Supersedes the earlier prototype (validatePasswordPolicy / isPasswordPwned).
|
||||
// Those were never wired up to any caller; the new API is the canonical one.
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
const HIBP_API_BASE = "https://api.pwnedpasswords.com/range/";
|
||||
const HIBP_TIMEOUT_MS = 3000;
|
||||
const ABSOLUTE_MAX_LENGTH = 1024;
|
||||
|
||||
export type PasswordPolicyConfig = {
|
||||
minLength: number;
|
||||
requireUpper: boolean;
|
||||
requireLower: boolean;
|
||||
requireDigit: boolean;
|
||||
requireSpecial: boolean;
|
||||
hibpCheck: boolean;
|
||||
hibpMaxOccurrences: number;
|
||||
};
|
||||
|
||||
export type PasswordPolicyContext = {
|
||||
email?: string;
|
||||
};
|
||||
|
||||
/** Bounded i18n keys for each failure mode. */
|
||||
export type PasswordPolicyErrorCode =
|
||||
| "auth.password.errors.tooShort"
|
||||
| "auth.password.errors.tooLong"
|
||||
| "auth.password.errors.missingUpper"
|
||||
| "auth.password.errors.missingLower"
|
||||
| "auth.password.errors.missingDigit"
|
||||
| "auth.password.errors.missingSpecial"
|
||||
| "auth.password.errors.containsEmail"
|
||||
| "auth.password.errors.pwned"
|
||||
| "auth.password.errors.empty";
|
||||
|
||||
export type PasswordPolicyError = {
|
||||
code: PasswordPolicyErrorCode;
|
||||
/** Non-secret args for the i18n template (e.g. minLength). */
|
||||
args?: Record<string, string | number>;
|
||||
};
|
||||
|
||||
export type PasswordPolicyValidation = {
|
||||
valid: boolean;
|
||||
errors: PasswordPolicyError[];
|
||||
/**
|
||||
* True when the HIBP check was skipped because the API call failed. Route
|
||||
* code may want to log this so operators can monitor the bypass rate.
|
||||
*/
|
||||
hibpBypassed?: boolean;
|
||||
};
|
||||
|
||||
const SPECIAL_CHAR_RE = /[^A-Za-z0-9]/;
|
||||
|
||||
export function loadPasswordPolicy(env: Record<string, string | undefined> = process.env): PasswordPolicyConfig {
|
||||
return {
|
||||
minLength: parseIntWithDefault(env.AUTH_PASSWORD_MIN_LENGTH, 12),
|
||||
requireUpper: parseBool(env.AUTH_PASSWORD_REQUIRE_UPPER, true),
|
||||
requireLower: parseBool(env.AUTH_PASSWORD_REQUIRE_LOWER, true),
|
||||
requireDigit: parseBool(env.AUTH_PASSWORD_REQUIRE_DIGIT, true),
|
||||
requireSpecial: parseBool(env.AUTH_PASSWORD_REQUIRE_SPECIAL, false),
|
||||
hibpCheck: parseBool(env.AUTH_PASSWORD_HIBP_CHECK, true),
|
||||
hibpMaxOccurrences: parseIntWithDefault(env.AUTH_PASSWORD_HIBP_MAX_OCCURRENCES, 0),
|
||||
};
|
||||
}
|
||||
|
||||
export type ValidatePasswordOptions = {
|
||||
policy?: PasswordPolicyConfig;
|
||||
/** Test seam. Defaults to globalThis.fetch. */
|
||||
fetcher?: typeof fetch;
|
||||
};
|
||||
|
||||
export async function validatePassword(
|
||||
plain: string,
|
||||
ctx: PasswordPolicyContext = {},
|
||||
options: ValidatePasswordOptions = {}
|
||||
): Promise<PasswordPolicyValidation> {
|
||||
const policy = options.policy ?? loadPasswordPolicy();
|
||||
const errors: PasswordPolicyError[] = [];
|
||||
|
||||
if (typeof plain !== "string" || plain.length === 0) {
|
||||
return { valid: false, errors: [{ code: "auth.password.errors.empty" }] };
|
||||
}
|
||||
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 (policy.requireUpper && !/[A-Z]/.test(plain)) {
|
||||
errors.push({ code: "auth.password.errors.missingUpper" });
|
||||
}
|
||||
if (policy.requireLower && !/[a-z]/.test(plain)) {
|
||||
errors.push({ code: "auth.password.errors.missingLower" });
|
||||
}
|
||||
if (policy.requireDigit && !/\d/.test(plain)) {
|
||||
errors.push({ code: "auth.password.errors.missingDigit" });
|
||||
}
|
||||
if (policy.requireSpecial && !SPECIAL_CHAR_RE.test(plain)) {
|
||||
errors.push({ code: "auth.password.errors.missingSpecial" });
|
||||
}
|
||||
if (ctx.email && containsEmailLocalPart(plain, ctx.email)) {
|
||||
errors.push({ code: "auth.password.errors.containsEmail" });
|
||||
}
|
||||
|
||||
let hibpBypassed = false;
|
||||
if (policy.hibpCheck) {
|
||||
const result = await checkHibp(plain, policy.hibpMaxOccurrences, options.fetcher);
|
||||
if (result === "pwned") {
|
||||
errors.push({ code: "auth.password.errors.pwned" });
|
||||
} else if (result === "bypassed") {
|
||||
hibpBypassed = true;
|
||||
}
|
||||
}
|
||||
|
||||
return { valid: errors.length === 0, errors, ...(hibpBypassed ? { hibpBypassed } : {}) };
|
||||
}
|
||||
|
||||
function containsEmailLocalPart(plain: string, email: string): boolean {
|
||||
const local = email.split("@")[0]?.toLowerCase();
|
||||
if (!local || local.length < 3) return false;
|
||||
return plain.toLowerCase().includes(local);
|
||||
}
|
||||
|
||||
async function checkHibp(plain: string, maxOccurrences: number, fetcher?: typeof fetch): Promise<"clean" | "pwned" | "bypassed"> {
|
||||
const sha1 = createHash("sha1").update(plain).digest("hex").toUpperCase();
|
||||
const prefix = sha1.slice(0, 5);
|
||||
const suffix = sha1.slice(5);
|
||||
const url = `${HIBP_API_BASE}${prefix}`;
|
||||
const usedFetcher = fetcher ?? globalThis.fetch;
|
||||
if (typeof usedFetcher !== "function") return "bypassed";
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await withTimeout(usedFetcher(url, { headers: { "Add-Padding": "true" } }), HIBP_TIMEOUT_MS);
|
||||
} catch {
|
||||
return "bypassed";
|
||||
}
|
||||
if (!response.ok) return "bypassed";
|
||||
|
||||
let body: string;
|
||||
try {
|
||||
body = await response.text();
|
||||
} catch {
|
||||
return "bypassed";
|
||||
}
|
||||
for (const line of body.split(/\r?\n/)) {
|
||||
const [candidateSuffix, countStr] = line.trim().split(":");
|
||||
if (candidateSuffix?.toUpperCase() !== suffix) continue;
|
||||
const count = Number(countStr);
|
||||
if (!Number.isFinite(count)) continue;
|
||||
if (count > maxOccurrences) return "pwned";
|
||||
return "clean";
|
||||
}
|
||||
return "clean";
|
||||
}
|
||||
|
||||
async function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const timeout = new Promise<T>((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error("hibp_timeout")), ms);
|
||||
});
|
||||
try {
|
||||
return await Promise.race([promise, timeout]);
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
function parseIntWithDefault(raw: string | undefined, fallback: number): number {
|
||||
if (!raw) return fallback;
|
||||
const n = Number.parseInt(raw, 10);
|
||||
return Number.isFinite(n) && n > 0 ? n : fallback;
|
||||
}
|
||||
|
||||
function parseBool(raw: string | undefined, fallback: boolean): boolean {
|
||||
if (raw === undefined) return fallback;
|
||||
const lower = raw.trim().toLowerCase();
|
||||
if (["true", "1", "yes", "on"].includes(lower)) return true;
|
||||
if (["false", "0", "no", "off"].includes(lower)) return false;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Backwards-compatibility shims for the prototype API. Nothing in-tree calls
|
||||
// these (rg -n "validatePasswordPolicy|assertPasswordPolicy|isPasswordPwned|
|
||||
// MIN_PASSWORD_LENGTH" returns zero matches at the time of this rewrite), but
|
||||
// they stay exported as one-liners around validatePassword so out-of-tree
|
||||
// scripts that imported them don't break.
|
||||
|
||||
export const MIN_PASSWORD_LENGTH = 12;
|
||||
|
||||
export async function isPasswordPwned(password: string, fetchImpl: typeof fetch = fetch): Promise<boolean> {
|
||||
const result = await checkHibp(password, 0, fetchImpl);
|
||||
return result === "pwned";
|
||||
}
|
||||
|
||||
export type PasswordPolicyIssue = "too-short" | "pwned" | "pwned-check-unavailable";
|
||||
|
||||
export type PasswordPolicyResult = {
|
||||
ok: boolean;
|
||||
issues: PasswordPolicyIssue[];
|
||||
};
|
||||
|
||||
export async function validatePasswordPolicy(password: string, options: { fetchImpl?: typeof fetch } = {}): Promise<PasswordPolicyResult> {
|
||||
const result = await validatePassword(password, {}, { fetcher: options.fetchImpl });
|
||||
const issues: PasswordPolicyIssue[] = [];
|
||||
if (result.errors.some((e) => e.code === "auth.password.errors.tooShort")) issues.push("too-short");
|
||||
if (result.errors.some((e) => e.code === "auth.password.errors.pwned")) issues.push("pwned");
|
||||
if (result.hibpBypassed) issues.push("pwned-check-unavailable");
|
||||
return { ok: result.valid && !result.hibpBypassed, issues };
|
||||
}
|
||||
|
||||
export async function assertPasswordPolicy(password: string, options: { fetchImpl?: typeof fetch } = {}) {
|
||||
const result = await validatePasswordPolicy(password, options);
|
||||
if (!result.ok) {
|
||||
throw new Error(`Password policy failed: ${result.issues.join(", ")}`);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
createPasswordResetTokenUpdate,
|
||||
createPasswordResetVerifyToken,
|
||||
hashPasswordResetToken,
|
||||
isPasswordResetTokenValid,
|
||||
PASSWORD_RESET_TOKEN_TTL_MS,
|
||||
} from "./password-reset-token.server";
|
||||
|
||||
describe("password reset token helpers", () => {
|
||||
it("creates token update data with an issue timestamp", () => {
|
||||
const issuedAt = new Date("2026-05-11T12:00:00.000Z");
|
||||
|
||||
expect(createPasswordResetTokenUpdate("token_1", issuedAt)).toEqual({
|
||||
verifyToken: hashPasswordResetToken("token_1"),
|
||||
verifyTokenCreatedAt: issuedAt,
|
||||
});
|
||||
});
|
||||
|
||||
it("creates high-entropy reset tokens as hex strings", () => {
|
||||
const token = createPasswordResetVerifyToken();
|
||||
|
||||
expect(token).toMatch(/^[a-f0-9]{40}$/);
|
||||
});
|
||||
|
||||
it("accepts matching tokens within the reset TTL", () => {
|
||||
const issuedAt = new Date("2026-05-11T12:00:00.000Z");
|
||||
const now = new Date(issuedAt.getTime() + PASSWORD_RESET_TOKEN_TTL_MS - 1);
|
||||
|
||||
expect(isPasswordResetTokenValid({ verifyToken: hashPasswordResetToken("token_1"), verifyTokenCreatedAt: issuedAt }, "token_1", now)).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts legacy plaintext tokens during migration", () => {
|
||||
const issuedAt = new Date("2026-05-11T12:00:00.000Z");
|
||||
|
||||
expect(isPasswordResetTokenValid({ verifyToken: "token_1", verifyTokenCreatedAt: issuedAt }, "token_1", issuedAt)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects missing, mismatched, or expired tokens", () => {
|
||||
const issuedAt = new Date("2026-05-11T12:00:00.000Z");
|
||||
const expiredNow = new Date(issuedAt.getTime() + PASSWORD_RESET_TOKEN_TTL_MS + 1);
|
||||
|
||||
expect(isPasswordResetTokenValid({ verifyToken: "token_1", verifyTokenCreatedAt: null }, "token_1", issuedAt)).toBe(false);
|
||||
expect(isPasswordResetTokenValid({ verifyToken: hashPasswordResetToken("token_1"), verifyTokenCreatedAt: issuedAt }, "", issuedAt)).toBe(false);
|
||||
expect(isPasswordResetTokenValid({ verifyToken: hashPasswordResetToken("token_1"), verifyTokenCreatedAt: issuedAt }, "wrong", issuedAt)).toBe(false);
|
||||
expect(isPasswordResetTokenValid({ verifyToken: hashPasswordResetToken("token_1"), verifyTokenCreatedAt: issuedAt }, "token_1", expiredNow)).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects malformed token issue timestamps", () => {
|
||||
expect(isPasswordResetTokenValid({ verifyToken: hashPasswordResetToken("token_1"), verifyTokenCreatedAt: "not-a-date" }, "token_1")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
|
||||
export const PASSWORD_RESET_TOKEN_TTL_MS = 1000 * 60 * 60;
|
||||
const PASSWORD_RESET_TOKEN_HASH_PREFIX = "sha256:";
|
||||
|
||||
export function hashPasswordResetToken(verifyToken: string) {
|
||||
return `${PASSWORD_RESET_TOKEN_HASH_PREFIX}${createHash("sha256").update(verifyToken).digest("hex")}`;
|
||||
}
|
||||
|
||||
export function createPasswordResetTokenUpdate(verifyToken: string, now = new Date()) {
|
||||
return {
|
||||
verifyToken: hashPasswordResetToken(verifyToken),
|
||||
verifyTokenCreatedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
export function createPasswordResetVerifyToken() {
|
||||
return randomBytes(20).toString("hex");
|
||||
}
|
||||
|
||||
export function isPasswordResetTokenValid(
|
||||
user: { verifyToken?: string | null; verifyTokenCreatedAt?: Date | string | null },
|
||||
verifyToken: string,
|
||||
now = new Date(),
|
||||
) {
|
||||
if (!user.verifyToken || !verifyToken || !user.verifyTokenCreatedAt) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const createdAt = new Date(user.verifyTokenCreatedAt).getTime();
|
||||
if (!Number.isFinite(createdAt) || now.getTime() - createdAt > PASSWORD_RESET_TOKEN_TTL_MS) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const storedToken = user.verifyToken.startsWith(PASSWORD_RESET_TOKEN_HASH_PREFIX)
|
||||
? user.verifyToken
|
||||
: user.verifyToken;
|
||||
const candidate = user.verifyToken.startsWith(PASSWORD_RESET_TOKEN_HASH_PREFIX)
|
||||
? hashPasswordResetToken(verifyToken)
|
||||
: verifyToken;
|
||||
|
||||
return timingSafeStringEqual(storedToken, candidate);
|
||||
}
|
||||
|
||||
function timingSafeStringEqual(a: string, b: string) {
|
||||
const aBuffer = Buffer.from(a);
|
||||
const bBuffer = Buffer.from(b);
|
||||
|
||||
if (aBuffer.byteLength !== bBuffer.byteLength) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return timingSafeEqual(aBuffer, bBuffer);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const storeMock = vi.hoisted(() => ({
|
||||
createUserSession: vi.fn(),
|
||||
revokeSessionByToken: vi.fn(),
|
||||
}));
|
||||
vi.mock("./sessionStore.server", () => ({
|
||||
createUserSession: (...args: unknown[]) => storeMock.createUserSession(...args),
|
||||
revokeSessionByToken: (...args: unknown[]) => storeMock.revokeSessionByToken(...args),
|
||||
}));
|
||||
|
||||
const geoMock = vi.hoisted(() => ({ lookupCountry: vi.fn() }));
|
||||
vi.mock("~/modules/ipAddress/services/geoip.server", () => ({
|
||||
// Realistischer Mock: der Hash enthaelt die Roh-IP NICHT (wie der echte hashIp).
|
||||
hashIp: () => "HASHED",
|
||||
lookupCountry: (...args: unknown[]) => geoMock.lookupCountry(...args),
|
||||
}));
|
||||
|
||||
import { buildSessionDeviceContext, endServerSession, startServerSession } from "./sessionLifecycle.server";
|
||||
|
||||
function requestWith(headers: Record<string, string>) {
|
||||
return new Request("https://example.test/login", { headers });
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
geoMock.lookupCountry.mockResolvedValue({ countryCode: "DE", countryName: "Germany" });
|
||||
});
|
||||
|
||||
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" }));
|
||||
expect(ctx.ipHash).toBe("HASHED");
|
||||
expect(ctx.userAgent).toBe("Safari");
|
||||
expect(ctx.approxLocation).toBe("Germany");
|
||||
expect(JSON.stringify(ctx)).not.toContain("9.9.9.9");
|
||||
});
|
||||
|
||||
it("yields nulls and skips the geo lookup when no IP is present", async () => {
|
||||
const ctx = await buildSessionDeviceContext(requestWith({}));
|
||||
expect(ctx.ipHash).toBeNull();
|
||||
expect(ctx.userAgent).toBeNull();
|
||||
expect(ctx.approxLocation).toBeNull();
|
||||
expect(geoMock.lookupCountry).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
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" });
|
||||
expect(token).toBe("tok-123");
|
||||
expect(storeMock.createUserSession).toHaveBeenCalledWith({ userId: "u1", ipHash: "HASHED", userAgent: "Safari", approxLocation: "Germany" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("endServerSession", () => {
|
||||
it("delegates revocation to the store", async () => {
|
||||
storeMock.revokeSessionByToken.mockResolvedValue(true);
|
||||
await endServerSession("tok-123");
|
||||
expect(storeMock.revokeSessionByToken).toHaveBeenCalledWith("tok-123");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { hashIp, lookupCountry } from "~/modules/ipAddress/services/geoip.server";
|
||||
import { getClientIPAddress } from "~/utils/server/IpUtils";
|
||||
|
||||
import { createUserSession as createServerSessionRow, revokeSessionByToken } from "./sessionStore.server";
|
||||
|
||||
// R-P2a S4b — Bruecke zwischen Cookie-Login und dem serverseitigen Session-Store. Additiv:
|
||||
// das Login-Cookie bleibt der primaere Auth-Mechanismus, parallel wird eine UserSession-Zeile
|
||||
// gefuehrt, damit Geraeteliste, Revoke und "ueberall abmelden" greifen.
|
||||
|
||||
export function extractRawClientIp(request: Request): string | null {
|
||||
return getClientIPAddress(request.headers)?.toString() ?? null;
|
||||
}
|
||||
|
||||
// AD-22: persistiert KEINE Klartext-IP. Die IP wird gehasht (hashIp, Wiedererkennung "gleiches
|
||||
// Geraet") und das Land lokal aufgeloest (lookupCountry; die IP verlaesst die Infra nicht).
|
||||
export async function buildSessionDeviceContext(request: Request): Promise<{ ipHash: string | null; userAgent: string | null; approxLocation: string | null }> {
|
||||
const rawIp = extractRawClientIp(request);
|
||||
const country = rawIp ? await lookupCountry(rawIp) : null;
|
||||
return {
|
||||
ipHash: rawIp ? hashIp(rawIp) : null,
|
||||
userAgent: request.headers.get("user-agent"),
|
||||
approxLocation: country?.countryName ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
// 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> {
|
||||
const context = await buildSessionDeviceContext(request);
|
||||
const { rawToken } = await createServerSessionRow({ userId, ...context });
|
||||
return rawToken;
|
||||
}
|
||||
|
||||
export async function endServerSession(rawToken: string | undefined | null): Promise<void> {
|
||||
await revokeSessionByToken(rawToken);
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const dbMock = vi.hoisted(() => ({
|
||||
userSession: {
|
||||
create: vi.fn(),
|
||||
findUnique: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
update: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({ db: dbMock, dbRead: dbMock }));
|
||||
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(),
|
||||
}));
|
||||
|
||||
import { clearCacheKey } from "~/utils/cache.server";
|
||||
import {
|
||||
createUserSession,
|
||||
generateSessionToken,
|
||||
getActiveSessionByToken,
|
||||
hashSessionToken,
|
||||
listActiveUserSessions,
|
||||
markSessionTrusted,
|
||||
revokeAllUserSessionsExcept,
|
||||
revokeSessionByToken,
|
||||
revokeUserSession,
|
||||
} from "./sessionStore.server";
|
||||
|
||||
const clearCacheKeyMock = vi.mocked(clearCacheKey);
|
||||
|
||||
function futureDate(msFromNow = 60_000) {
|
||||
return new Date(Date.now() + msFromNow);
|
||||
}
|
||||
function pastDate(msAgo = 60_000) {
|
||||
return new Date(Date.now() - msAgo);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("session token hashing", () => {
|
||||
it("hashes deterministically and never stores the raw token", () => {
|
||||
expect(hashSessionToken("abc")).toBe(hashSessionToken("abc"));
|
||||
expect(hashSessionToken("abc")).not.toBe("abc");
|
||||
expect(hashSessionToken("abc")).toMatch(/^[0-9a-f]{64}$/);
|
||||
});
|
||||
|
||||
it("generates unique opaque tokens", () => {
|
||||
expect(generateSessionToken()).not.toBe(generateSessionToken());
|
||||
});
|
||||
});
|
||||
|
||||
describe("createUserSession", () => {
|
||||
it("persists only the token hash and returns the raw token for the cookie", async () => {
|
||||
dbMock.userSession.create.mockResolvedValue({ id: "s1", userId: "u1" });
|
||||
const { session, rawToken } = await createUserSession({ userId: "u1", ipHash: "deadbeef", userAgent: "UA" });
|
||||
|
||||
expect(session).toEqual({ id: "s1", userId: "u1" });
|
||||
expect(rawToken).toEqual(expect.any(String));
|
||||
const data = dbMock.userSession.create.mock.calls[0][0].data;
|
||||
expect(data.tokenHash).toBe(hashSessionToken(rawToken));
|
||||
expect(data).not.toHaveProperty("token");
|
||||
// AD-22: kein Klartext-IP-Feld; nur der Hash.
|
||||
expect(data).not.toHaveProperty("ipAddress");
|
||||
expect(data.ipHash).toBe("deadbeef");
|
||||
expect(data.trustedAt).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getActiveSessionByToken", () => {
|
||||
it("returns null for a missing token without hitting the DB", async () => {
|
||||
expect(await getActiveSessionByToken(undefined)).toBeNull();
|
||||
expect(dbMock.userSession.findUnique).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns the session when active", async () => {
|
||||
dbMock.userSession.findUnique.mockResolvedValue({ id: "s1", revokedAt: null, expiresAt: futureDate() });
|
||||
expect(await getActiveSessionByToken("raw")).toMatchObject({ id: "s1" });
|
||||
});
|
||||
|
||||
it("returns null for a revoked session", async () => {
|
||||
dbMock.userSession.findUnique.mockResolvedValue({ id: "s1", revokedAt: pastDate(), expiresAt: futureDate() });
|
||||
expect(await getActiveSessionByToken("raw")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for an expired session", async () => {
|
||||
dbMock.userSession.findUnique.mockResolvedValue({ id: "s1", revokedAt: null, expiresAt: pastDate() });
|
||||
expect(await getActiveSessionByToken("raw")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("listActiveUserSessions", () => {
|
||||
it("filters to non-revoked, non-expired sessions for the device list", async () => {
|
||||
dbMock.userSession.findMany.mockResolvedValue([{ id: "s1" }]);
|
||||
await listActiveUserSessions("u1");
|
||||
const where = dbMock.userSession.findMany.mock.calls[0][0].where;
|
||||
expect(where.userId).toBe("u1");
|
||||
expect(where.revokedAt).toBeNull();
|
||||
expect(where.expiresAt).toHaveProperty("gt");
|
||||
});
|
||||
});
|
||||
|
||||
describe("revokeUserSession", () => {
|
||||
it("rejects revoking a session that is not owned by the user", async () => {
|
||||
dbMock.userSession.findFirst.mockResolvedValue(null);
|
||||
expect(await revokeUserSession({ userId: "u1", sessionId: "s1" })).toBe(false);
|
||||
expect(dbMock.userSession.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("is a no-op for an already revoked session", async () => {
|
||||
dbMock.userSession.findFirst.mockResolvedValue({ id: "s1", tokenHash: "h", revokedAt: pastDate() });
|
||||
expect(await revokeUserSession({ userId: "u1", sessionId: "s1" })).toBe(false);
|
||||
expect(dbMock.userSession.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("revokes an active owned session and clears its cache key", async () => {
|
||||
dbMock.userSession.findFirst.mockResolvedValue({ id: "s1", tokenHash: "hash1", revokedAt: null });
|
||||
dbMock.userSession.update.mockResolvedValue({});
|
||||
expect(await revokeUserSession({ userId: "u1", sessionId: "s1" })).toBe(true);
|
||||
expect(dbMock.userSession.update).toHaveBeenCalledWith({ where: { id: "s1" }, data: { revokedAt: expect.any(Date) } });
|
||||
expect(clearCacheKeyMock).toHaveBeenCalledWith("user-session:hash1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("revokeAllUserSessionsExcept", () => {
|
||||
it("revokes every other active session and clears each cache key", async () => {
|
||||
dbMock.userSession.findMany.mockResolvedValue([
|
||||
{ id: "s2", tokenHash: "h2" },
|
||||
{ id: "s3", tokenHash: "h3" },
|
||||
]);
|
||||
dbMock.userSession.updateMany.mockResolvedValue({ count: 2 });
|
||||
const revoked = await revokeAllUserSessionsExcept({ userId: "u1", sessionId: "s1" });
|
||||
expect(revoked).toBe(2);
|
||||
expect(dbMock.userSession.updateMany.mock.calls[0][0].where.id).toEqual({ not: "s1" });
|
||||
expect(clearCacheKeyMock).toHaveBeenCalledWith("user-session:h2");
|
||||
expect(clearCacheKeyMock).toHaveBeenCalledWith("user-session:h3");
|
||||
});
|
||||
|
||||
it("returns zero and does not write when there is nothing else to revoke", async () => {
|
||||
dbMock.userSession.findMany.mockResolvedValue([]);
|
||||
expect(await revokeAllUserSessionsExcept({ userId: "u1", sessionId: "s1" })).toBe(0);
|
||||
expect(dbMock.userSession.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("revokeSessionByToken", () => {
|
||||
it("returns false for a missing token without touching the DB", async () => {
|
||||
expect(await revokeSessionByToken(undefined)).toBe(false);
|
||||
expect(dbMock.userSession.findUnique).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("revokes the active session for a token and clears its cache key", async () => {
|
||||
dbMock.userSession.findUnique.mockResolvedValue({ id: "s1", revokedAt: null });
|
||||
dbMock.userSession.update.mockResolvedValue({});
|
||||
expect(await revokeSessionByToken("raw")).toBe(true);
|
||||
expect(dbMock.userSession.update).toHaveBeenCalledWith({ where: { id: "s1" }, data: { revokedAt: expect.any(Date) } });
|
||||
expect(clearCacheKeyMock).toHaveBeenCalledWith(`user-session:${hashSessionToken("raw")}`);
|
||||
});
|
||||
|
||||
it("is a no-op for an already revoked or unknown token", async () => {
|
||||
dbMock.userSession.findUnique.mockResolvedValueOnce({ id: "s1", revokedAt: pastDate() });
|
||||
expect(await revokeSessionByToken("raw")).toBe(false);
|
||||
dbMock.userSession.findUnique.mockResolvedValueOnce(null);
|
||||
expect(await revokeSessionByToken("raw")).toBe(false);
|
||||
expect(dbMock.userSession.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("markSessionTrusted", () => {
|
||||
it("marks an owned active session trusted", async () => {
|
||||
dbMock.userSession.updateMany.mockResolvedValue({ count: 1 });
|
||||
expect(await markSessionTrusted({ userId: "u1", sessionId: "s1" })).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when no owned active session matched", async () => {
|
||||
dbMock.userSession.updateMany.mockResolvedValue({ count: 0 });
|
||||
expect(await markSessionTrusted({ userId: "u1", sessionId: "s1" })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
|
||||
import { cachified, clearCacheKey } from "~/utils/cache.server";
|
||||
import { db } from "~/utils/db.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
|
||||
// Login-Cookie traegt einen opaken Zufalls-Token; persistiert wird nur dessen SHA-256-Hash.
|
||||
|
||||
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>>;
|
||||
|
||||
type Identified = { userId: string; sessionId: string };
|
||||
|
||||
export function generateSessionToken(): string {
|
||||
return randomBytes(SESSION_TOKEN_BYTES).toString("base64url");
|
||||
}
|
||||
|
||||
export function hashSessionToken(rawToken: string): string {
|
||||
return createHash("sha256").update(rawToken).digest("hex");
|
||||
}
|
||||
|
||||
function sessionCacheKey(tokenHash: string): string {
|
||||
return `user-session:${tokenHash}`;
|
||||
}
|
||||
|
||||
function isActive(session: Pick<UserSessionRow, "revokedAt" | "expiresAt"> | null, now = Date.now()): boolean {
|
||||
return Boolean(session && session.revokedAt === null && session.expiresAt.getTime() > now);
|
||||
}
|
||||
|
||||
export type CreateSessionInput = {
|
||||
userId: string;
|
||||
// Wenn nicht gesetzt, wird ein Token generiert. Der rohe Token gehoert ins Cookie.
|
||||
rawToken?: string;
|
||||
expiresAt?: Date;
|
||||
// AD-22: gehashte IP (hashIp), NICHT Klartext.
|
||||
ipHash?: string | null;
|
||||
userAgent?: string | null;
|
||||
deviceLabel?: string | null;
|
||||
approxLocation?: string | null;
|
||||
browserFingerprint?: string | null;
|
||||
trusted?: boolean;
|
||||
};
|
||||
|
||||
export async function createUserSession(input: CreateSessionInput): Promise<{ session: UserSessionRow; rawToken: string }> {
|
||||
const rawToken = input.rawToken ?? generateSessionToken();
|
||||
const now = Date.now();
|
||||
const session = await db.userSession.create({
|
||||
data: {
|
||||
userId: input.userId,
|
||||
tokenHash: hashSessionToken(rawToken),
|
||||
expiresAt: input.expiresAt ?? new Date(now + DEFAULT_SESSION_TTL_MS),
|
||||
ipHash: input.ipHash ?? null,
|
||||
userAgent: input.userAgent ?? null,
|
||||
deviceLabel: input.deviceLabel ?? null,
|
||||
approxLocation: input.approxLocation ?? null,
|
||||
browserFingerprint: input.browserFingerprint ?? null,
|
||||
trustedAt: input.trusted ? new Date(now) : null,
|
||||
},
|
||||
});
|
||||
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> {
|
||||
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)) {
|
||||
return null;
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
// Schreibt lastSeenAt fort, aber gedrosselt (hoechstens alle TOUCH_THROTTLE_MS), um den
|
||||
// Hot-Path nicht mit Writes zu belasten.
|
||||
export async function touchSession(session: Pick<UserSessionRow, "id" | "lastSeenAt" | "tokenHash">): Promise<void> {
|
||||
const now = Date.now();
|
||||
if (now - session.lastSeenAt.getTime() < TOUCH_THROTTLE_MS) {
|
||||
return;
|
||||
}
|
||||
await db.userSession.update({ where: { id: session.id }, data: { lastSeenAt: new Date(now) } });
|
||||
clearCacheKey(sessionCacheKey(session.tokenHash));
|
||||
}
|
||||
|
||||
export async function listActiveUserSessions(userId: string): Promise<UserSessionRow[]> {
|
||||
return 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> {
|
||||
const session = await db.userSession.findFirst({ where: { id: sessionId, userId }, select: { id: true, tokenHash: true, revokedAt: true } });
|
||||
if (!session || session.revokedAt !== null) {
|
||||
return false;
|
||||
}
|
||||
await db.userSession.update({ where: { id: session.id }, data: { revokedAt: new Date() } });
|
||||
clearCacheKey(sessionCacheKey(session.tokenHash));
|
||||
return true;
|
||||
}
|
||||
|
||||
// "Ueberall abmelden": alle aktiven Sessions des Nutzers ausser der aktuellen beenden.
|
||||
export async function revokeAllUserSessionsExcept({ userId, sessionId }: Identified): Promise<number> {
|
||||
const sessions = await db.userSession.findMany({
|
||||
where: { userId, revokedAt: null, id: { not: sessionId } },
|
||||
select: { id: true, tokenHash: true },
|
||||
});
|
||||
if (sessions.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
const now = new Date();
|
||||
await db.userSession.updateMany({
|
||||
where: { userId, revokedAt: null, id: { not: sessionId } },
|
||||
data: { revokedAt: now },
|
||||
});
|
||||
for (const session of sessions) {
|
||||
clearCacheKey(sessionCacheKey(session.tokenHash));
|
||||
}
|
||||
return sessions.length;
|
||||
}
|
||||
|
||||
// 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 session = await db.userSession.findUnique({ where: { tokenHash }, select: { id: true, revokedAt: true } });
|
||||
if (!session || session.revokedAt !== null) {
|
||||
return false;
|
||||
}
|
||||
await db.userSession.update({ where: { id: session.id }, data: { revokedAt: new Date() } });
|
||||
clearCacheKey(sessionCacheKey(tokenHash));
|
||||
return true;
|
||||
}
|
||||
|
||||
// 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 result.count > 0;
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import * as OTPAuth from "otpauth";
|
||||
|
||||
vi.mock("~/utils/api/.server/CryptoApi", () => ({
|
||||
default: {
|
||||
encrypt: vi.fn((value: string) => `encrypted:${value}`),
|
||||
decrypt: vi.fn((value: string) => value.replace(/^encrypted:/, "")),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@toolctrl/config", () => ({
|
||||
loadRequiredWebConfig: vi.fn(() => ({ appName: "ToolCTRL" })),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/users.db.server", () => ({
|
||||
activateUserTotpPendingSecret: vi.fn(),
|
||||
getUserTotpPendingEnrollment: vi.fn(),
|
||||
setUserMfaRecoveryCodes: vi.fn(),
|
||||
setUserTotpPendingSecret: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/auth/mfa/recovery-codes.server", () => ({
|
||||
generateRecoveryCodes: vi.fn(() => ({
|
||||
codes: ["recovery-1", "recovery-2"],
|
||||
entries: [
|
||||
{ codeHash: "hash-1", createdAt: new Date("2026-05-25T10:00:00.000Z") },
|
||||
{ codeHash: "hash-2", createdAt: new Date("2026-05-25T10:00:00.000Z") },
|
||||
],
|
||||
generatedAt: new Date("2026-05-25T10:00:00.000Z"),
|
||||
})),
|
||||
}));
|
||||
|
||||
const vectorSecret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
|
||||
|
||||
function generateExpectedCode(secret: string, timestamp: number): string {
|
||||
const totp = new OTPAuth.TOTP({
|
||||
issuer: "ToolCTRL",
|
||||
label: "test",
|
||||
algorithm: "SHA1",
|
||||
digits: 6,
|
||||
period: 30,
|
||||
secret: OTPAuth.Secret.fromBase32(secret),
|
||||
});
|
||||
return totp.generate({ timestamp });
|
||||
}
|
||||
|
||||
describe("services/auth/totp.server", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
test("generateTotpSecret returns a 32-char base32 string", async () => {
|
||||
const { generateTotpSecret } = await import("./totp.server");
|
||||
const secret = generateTotpSecret();
|
||||
expect(secret).toMatch(/^[A-Z2-7]{32}$/);
|
||||
});
|
||||
|
||||
test("encryptTotpSecret / decryptTotpSecret round-trip via CryptoApi", async () => {
|
||||
const { encryptTotpSecret, decryptTotpSecret } = await import("./totp.server");
|
||||
const encrypted = encryptTotpSecret(vectorSecret);
|
||||
expect(encrypted).toBe(`encrypted:${vectorSecret}`);
|
||||
expect(decryptTotpSecret(encrypted)).toBe(vectorSecret);
|
||||
});
|
||||
|
||||
test("verifyTotpCode accepts the current code with default window", async () => {
|
||||
const { encryptTotpSecret, verifyTotpCode } = await import("./totp.server");
|
||||
const encryptedSecret = encryptTotpSecret(vectorSecret);
|
||||
const now = 1_234_567_890_000;
|
||||
const code = generateExpectedCode(vectorSecret, now);
|
||||
expect(verifyTotpCode(encryptedSecret, code, { timestamp: now })).toBe(true);
|
||||
});
|
||||
|
||||
test("verifyTotpCode with window=1 accepts ±30s clock drift", async () => {
|
||||
const { encryptTotpSecret, verifyTotpCode } = await import("./totp.server");
|
||||
const encryptedSecret = encryptTotpSecret(vectorSecret);
|
||||
const now = 1_234_567_890_000;
|
||||
|
||||
const pastCode = generateExpectedCode(vectorSecret, now - 30_000);
|
||||
const futureCode = generateExpectedCode(vectorSecret, now + 30_000);
|
||||
|
||||
expect(verifyTotpCode(encryptedSecret, pastCode, { timestamp: now })).toBe(true);
|
||||
expect(verifyTotpCode(encryptedSecret, futureCode, { timestamp: now })).toBe(true);
|
||||
});
|
||||
|
||||
test("verifyTotpCode rejects ±60s clock drift outside the window", async () => {
|
||||
const { encryptTotpSecret, verifyTotpCode } = await import("./totp.server");
|
||||
const encryptedSecret = encryptTotpSecret(vectorSecret);
|
||||
const now = 1_234_567_890_000;
|
||||
|
||||
const tooOld = generateExpectedCode(vectorSecret, now - 60_000);
|
||||
const tooNew = generateExpectedCode(vectorSecret, now + 60_000);
|
||||
|
||||
expect(verifyTotpCode(encryptedSecret, tooOld, { timestamp: now })).toBe(false);
|
||||
expect(verifyTotpCode(encryptedSecret, tooNew, { timestamp: now })).toBe(false);
|
||||
});
|
||||
|
||||
test("verifyTotpCode rejects malformed codes without consulting otpauth", async () => {
|
||||
const { encryptTotpSecret, verifyTotpCode } = await import("./totp.server");
|
||||
const encryptedSecret = encryptTotpSecret(vectorSecret);
|
||||
const now = 1_234_567_890_000;
|
||||
|
||||
expect(verifyTotpCode(encryptedSecret, "12345", { timestamp: now })).toBe(false);
|
||||
expect(verifyTotpCode(encryptedSecret, "1234567", { timestamp: now })).toBe(false);
|
||||
expect(verifyTotpCode(encryptedSecret, "12345a", { timestamp: now })).toBe(false);
|
||||
expect(verifyTotpCode(encryptedSecret, "", { timestamp: now })).toBe(false);
|
||||
});
|
||||
|
||||
test("verifyTotpCode returns false when decryption throws", async () => {
|
||||
const cryptoApi = (await import("~/utils/api/.server/CryptoApi")).default;
|
||||
vi.mocked(cryptoApi.decrypt).mockImplementationOnce(() => {
|
||||
throw new Error("Invalid encrypted payload");
|
||||
});
|
||||
const { verifyTotpCode } = await import("./totp.server");
|
||||
const now = 1_234_567_890_000;
|
||||
const code = generateExpectedCode(vectorSecret, now);
|
||||
expect(verifyTotpCode("corrupt-encrypted-secret", code, { timestamp: now })).toBe(false);
|
||||
});
|
||||
|
||||
test("verifyTotpCode rejects a non-integer or negative window", async () => {
|
||||
const { encryptTotpSecret, verifyTotpCode } = await import("./totp.server");
|
||||
const encryptedSecret = encryptTotpSecret(vectorSecret);
|
||||
const now = 1_234_567_890_000;
|
||||
const code = generateExpectedCode(vectorSecret, now);
|
||||
expect(() => verifyTotpCode(encryptedSecret, code, { timestamp: now, window: -1 })).toThrow();
|
||||
expect(() => verifyTotpCode(encryptedSecret, code, { timestamp: now, window: 1.5 })).toThrow();
|
||||
});
|
||||
|
||||
test("buildTotpOtpauthUri produces a parsable otpauth:// URI with issuer and label", async () => {
|
||||
const { buildTotpOtpauthUri } = await import("./totp.server");
|
||||
const uri = buildTotpOtpauthUri(vectorSecret, "user+security@example.com", { issuer: "Tool Ctrl Admin" });
|
||||
|
||||
expect(uri.startsWith("otpauth://totp/")).toBe(true);
|
||||
expect(uri).toContain(`secret=${vectorSecret}`);
|
||||
expect(uri).toContain("algorithm=SHA1");
|
||||
expect(uri).toContain("digits=6");
|
||||
expect(uri).toContain("period=30");
|
||||
// Issuer + email appear URL-encoded, not as raw plaintext
|
||||
expect(uri).not.toContain("Tool Ctrl Admin:user+security@example.com");
|
||||
|
||||
const parsed = OTPAuth.URI.parse(uri);
|
||||
expect(parsed).toBeInstanceOf(OTPAuth.TOTP);
|
||||
expect(parsed.issuer).toBe("Tool Ctrl Admin");
|
||||
expect(parsed.label).toBe("user+security@example.com");
|
||||
});
|
||||
|
||||
test("startTotpEnrollment yields encrypted secret + parsable otpauth URI", async () => {
|
||||
const { startTotpEnrollment } = await import("./totp.server");
|
||||
const enrollment = startTotpEnrollment("person@example.com", { issuer: "ToolCTRL" });
|
||||
|
||||
expect(enrollment.secret).toMatch(/^[A-Z2-7]{32}$/);
|
||||
expect(enrollment.encryptedSecret).toBe(`encrypted:${enrollment.secret}`);
|
||||
expect(enrollment.otpauthUri).toBe(enrollment.qrValue);
|
||||
expect(enrollment.otpauthUri).toContain(`secret=${enrollment.secret}`);
|
||||
});
|
||||
|
||||
test("getTotpSafeStatus exposes only booleans and timestamps", async () => {
|
||||
const { getTotpSafeStatus } = await import("./totp.server");
|
||||
const enabledAt = new Date("2026-05-08T13:10:00.000Z");
|
||||
const pendingCreatedAt = new Date("2026-05-08T13:00:00.000Z");
|
||||
|
||||
const status = getTotpSafeStatus({
|
||||
hasEncryptedSecret: true,
|
||||
hasEncryptedPendingSecret: true,
|
||||
totpEnabledAt: enabledAt,
|
||||
totpPendingCreatedAt: pendingCreatedAt,
|
||||
});
|
||||
|
||||
expect(status).toEqual({ enabled: true, pending: true, enabledAt, pendingCreatedAt });
|
||||
expect(JSON.stringify(status)).not.toMatch(/secret|otpauth|encrypted/i);
|
||||
});
|
||||
|
||||
test("getTotpSafeStatus returns disabled when prerequisites are missing", async () => {
|
||||
const { getTotpSafeStatus } = await import("./totp.server");
|
||||
expect(
|
||||
getTotpSafeStatus({
|
||||
hasEncryptedSecret: false,
|
||||
hasEncryptedPendingSecret: false,
|
||||
totpEnabledAt: null,
|
||||
totpPendingCreatedAt: null,
|
||||
})
|
||||
).toEqual({ enabled: false, pending: false, enabledAt: null, pendingCreatedAt: null });
|
||||
});
|
||||
|
||||
test("createTotpEnrollmentForUser stores a pending encrypted secret", async () => {
|
||||
const { setUserTotpPendingSecret } = await import("~/utils/db/users.db.server");
|
||||
const { createTotpEnrollmentForUser } = await import("./totp.server");
|
||||
const now = new Date("2026-05-25T09:00:00.000Z");
|
||||
|
||||
const result = await createTotpEnrollmentForUser({
|
||||
userId: "user_1",
|
||||
userEmail: "security@example.com",
|
||||
issuer: "ToolCTRL Admin",
|
||||
now,
|
||||
});
|
||||
|
||||
expect(result.secret).toMatch(/^[A-Z2-7]{32}$/);
|
||||
expect(result.encryptedSecret).toBe(`encrypted:${result.secret}`);
|
||||
expect(result.recoveryCodesPending).toBe(true);
|
||||
expect(result.otpauthUri).toContain(`secret=${result.secret}`);
|
||||
expect(setUserTotpPendingSecret).toHaveBeenCalledWith("user_1", result.encryptedSecret, now);
|
||||
});
|
||||
|
||||
test("activatePendingTotpForUser returns false when no pending secret exists", async () => {
|
||||
const usersDb = await import("~/utils/db/users.db.server");
|
||||
vi.mocked(usersDb.getUserTotpPendingEnrollment).mockResolvedValueOnce(null);
|
||||
const { activatePendingTotpForUser } = await import("./totp.server");
|
||||
|
||||
await expect(
|
||||
activatePendingTotpForUser({
|
||||
userId: "user_1",
|
||||
token: "123456",
|
||||
now: new Date("2026-05-25T09:00:00.000Z"),
|
||||
})
|
||||
).resolves.toEqual({ activated: false, recoveryCodes: [] });
|
||||
expect(usersDb.activateUserTotpPendingSecret).not.toHaveBeenCalled();
|
||||
expect(usersDb.setUserMfaRecoveryCodes).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("activatePendingTotpForUser returns false when the token is invalid", async () => {
|
||||
const usersDb = await import("~/utils/db/users.db.server");
|
||||
vi.mocked(usersDb.getUserTotpPendingEnrollment).mockResolvedValueOnce({
|
||||
totpPendingSecretEncrypted: `encrypted:${vectorSecret}`,
|
||||
} as never);
|
||||
const { activatePendingTotpForUser } = await import("./totp.server");
|
||||
|
||||
await expect(
|
||||
activatePendingTotpForUser({
|
||||
userId: "user_1",
|
||||
token: "not-a-code",
|
||||
now: new Date("2026-05-25T09:00:00.000Z"),
|
||||
})
|
||||
).resolves.toEqual({ activated: false, recoveryCodes: [] });
|
||||
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");
|
||||
const now = new Date("2026-05-25T09:00:00.000Z");
|
||||
const code = generateExpectedCode(vectorSecret, now.getTime());
|
||||
vi.mocked(usersDb.getUserTotpPendingEnrollment).mockResolvedValueOnce({
|
||||
totpPendingSecretEncrypted: `encrypted:${vectorSecret}`,
|
||||
} as never);
|
||||
const { activatePendingTotpForUser, TOTP_RECOVERY_CODE_COUNT } = await import("./totp.server");
|
||||
|
||||
await expect(
|
||||
activatePendingTotpForUser({
|
||||
userId: "user_1",
|
||||
token: code,
|
||||
now,
|
||||
})
|
||||
).resolves.toEqual({ activated: true, recoveryCodes: ["recovery-1", "recovery-2"] });
|
||||
expect(generateRecoveryCodes).toHaveBeenCalledWith({ count: TOTP_RECOVERY_CODE_COUNT, now });
|
||||
expect(usersDb.activateUserTotpPendingSecret).toHaveBeenCalledWith("user_1", `encrypted:${vectorSecret}`, now);
|
||||
expect(usersDb.setUserMfaRecoveryCodes).toHaveBeenCalledWith(
|
||||
"user_1",
|
||||
[
|
||||
{ codeHash: "hash-1", createdAt: new Date("2026-05-25T10:00:00.000Z") },
|
||||
{ codeHash: "hash-2", createdAt: new Date("2026-05-25T10:00:00.000Z") },
|
||||
],
|
||||
new Date("2026-05-25T10:00:00.000Z")
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
import * as OTPAuth from "otpauth";
|
||||
import { loadRequiredWebConfig } from "@toolctrl/config";
|
||||
import CryptoApi from "~/utils/api/.server/CryptoApi";
|
||||
import {
|
||||
activateUserTotpPendingSecret,
|
||||
getUserTotpPendingEnrollment,
|
||||
setUserMfaRecoveryCodes,
|
||||
setUserTotpPendingSecret,
|
||||
} from "~/utils/db/users.db.server";
|
||||
import { generateRecoveryCodes } from "~/utils/auth/mfa/recovery-codes.server";
|
||||
|
||||
export const TOTP_RECOVERY_CODE_COUNT = 10;
|
||||
const TOTP_DIGITS = 6;
|
||||
const TOTP_PERIOD_SECONDS = 30;
|
||||
const DEFAULT_WINDOW = 1;
|
||||
const DEFAULT_SECRET_SIZE = 20;
|
||||
|
||||
export type TotpEnrollment = {
|
||||
secret: string;
|
||||
encryptedSecret: string;
|
||||
otpauthUri: string;
|
||||
qrValue: string;
|
||||
};
|
||||
|
||||
export type TotpSafeStatus = {
|
||||
enabled: boolean;
|
||||
pending: boolean;
|
||||
enabledAt: Date | null;
|
||||
pendingCreatedAt: Date | null;
|
||||
};
|
||||
|
||||
export type TotpEnrollmentResult = {
|
||||
encryptedSecret: string;
|
||||
otpauthUri: string;
|
||||
recoveryCodesPending: boolean;
|
||||
secret: string;
|
||||
};
|
||||
|
||||
type OtpauthOptions = {
|
||||
appName?: string;
|
||||
issuer?: string;
|
||||
};
|
||||
|
||||
type VerifyOptions = {
|
||||
window?: number;
|
||||
timestamp?: number;
|
||||
};
|
||||
|
||||
function getDefaultTotpIssuer() {
|
||||
return loadRequiredWebConfig().appName;
|
||||
}
|
||||
|
||||
function buildTotp(secret: string, label: string, issuer = getDefaultTotpIssuer()) {
|
||||
return new OTPAuth.TOTP({
|
||||
issuer,
|
||||
label,
|
||||
algorithm: "SHA1",
|
||||
digits: TOTP_DIGITS,
|
||||
period: TOTP_PERIOD_SECONDS,
|
||||
secret: OTPAuth.Secret.fromBase32(secret),
|
||||
});
|
||||
}
|
||||
|
||||
export function generateTotpSecret() {
|
||||
return new OTPAuth.Secret({ size: DEFAULT_SECRET_SIZE }).base32;
|
||||
}
|
||||
|
||||
export function encryptTotpSecret(secret: string) {
|
||||
return CryptoApi.encrypt(secret);
|
||||
}
|
||||
|
||||
export function decryptTotpSecret(encryptedSecret: string) {
|
||||
return CryptoApi.decrypt(encryptedSecret);
|
||||
}
|
||||
|
||||
export function buildTotpOtpauthUri(secret: string, userEmail: string, options: OtpauthOptions = {}) {
|
||||
const issuer = options.issuer ?? options.appName ?? getDefaultTotpIssuer();
|
||||
return buildTotp(secret, userEmail, issuer).toString();
|
||||
}
|
||||
|
||||
export function startTotpEnrollment(userEmail: string, options: OtpauthOptions = {}): TotpEnrollment {
|
||||
const secret = generateTotpSecret();
|
||||
const otpauthUri = buildTotpOtpauthUri(secret, userEmail, options);
|
||||
return {
|
||||
secret,
|
||||
encryptedSecret: encryptTotpSecret(secret),
|
||||
otpauthUri,
|
||||
qrValue: otpauthUri,
|
||||
};
|
||||
}
|
||||
|
||||
export function verifyTotpCode(encryptedSecret: string, code: string, options: VerifyOptions = {}) {
|
||||
if (!new RegExp(`^\\d{${TOTP_DIGITS}}$`).test(code)) {
|
||||
return false;
|
||||
}
|
||||
const window = options.window ?? DEFAULT_WINDOW;
|
||||
if (!Number.isInteger(window) || window < 0) {
|
||||
throw new Error("window must be a non-negative integer");
|
||||
}
|
||||
let secret: string;
|
||||
try {
|
||||
secret = decryptTotpSecret(encryptedSecret);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
const timestamp = options.timestamp ?? Date.now();
|
||||
const delta = buildTotp(secret, "verify").validate({ token: code, window, timestamp });
|
||||
return delta !== null;
|
||||
}
|
||||
|
||||
export function getTotpSafeStatus({
|
||||
totpEnabledAt,
|
||||
totpPendingCreatedAt,
|
||||
hasEncryptedSecret,
|
||||
hasEncryptedPendingSecret,
|
||||
}: {
|
||||
totpEnabledAt: Date | null | undefined;
|
||||
totpPendingCreatedAt: Date | null | undefined;
|
||||
hasEncryptedSecret: boolean;
|
||||
hasEncryptedPendingSecret: boolean;
|
||||
}): TotpSafeStatus {
|
||||
return {
|
||||
enabled: Boolean(hasEncryptedSecret && totpEnabledAt),
|
||||
pending: Boolean(hasEncryptedPendingSecret && totpPendingCreatedAt),
|
||||
enabledAt: totpEnabledAt ?? null,
|
||||
pendingCreatedAt: totpPendingCreatedAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function createTotpEnrollmentForUser({
|
||||
userId,
|
||||
userEmail,
|
||||
issuer,
|
||||
now = new Date(),
|
||||
}: {
|
||||
userId: string;
|
||||
userEmail: string;
|
||||
issuer?: string;
|
||||
now?: Date;
|
||||
}): Promise<TotpEnrollmentResult> {
|
||||
const enrollment = startTotpEnrollment(userEmail, { issuer });
|
||||
await setUserTotpPendingSecret(userId, enrollment.encryptedSecret, now);
|
||||
return {
|
||||
secret: enrollment.secret,
|
||||
encryptedSecret: enrollment.encryptedSecret,
|
||||
otpauthUri: enrollment.otpauthUri,
|
||||
recoveryCodesPending: true,
|
||||
};
|
||||
}
|
||||
|
||||
export async function activatePendingTotpForUser({
|
||||
userId,
|
||||
token,
|
||||
now = new Date(),
|
||||
}: {
|
||||
userId: string;
|
||||
token: string;
|
||||
now?: Date;
|
||||
}): Promise<{ activated: boolean; recoveryCodes: string[] }> {
|
||||
const pending = await getUserTotpPendingEnrollment(userId);
|
||||
if (!pending?.totpPendingSecretEncrypted) {
|
||||
return { activated: false, recoveryCodes: [] };
|
||||
}
|
||||
if (!verifyTotpCode(pending.totpPendingSecretEncrypted, token, { timestamp: now.getTime() })) {
|
||||
return { activated: false, recoveryCodes: [] };
|
||||
}
|
||||
const recovery = generateRecoveryCodes({ count: TOTP_RECOVERY_CODE_COUNT, now });
|
||||
await activateUserTotpPendingSecret(userId, pending.totpPendingSecretEncrypted, now);
|
||||
await setUserMfaRecoveryCodes(userId, recovery.entries, recovery.generatedAt);
|
||||
return { activated: true, recoveryCodes: recovery.codes };
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user