Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
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 };
}
@@ -0,0 +1,312 @@
import { NavigateFunction } from "react-router";
import { describe, expect, it, vi } from "vitest";
import { getCommandRegistryActions, getSidebarCommandActions } from "./commandRegistry";
const t = vi.fn().mockImplementation((value: string) => value) as any;
const routing = {
protocol: "https",
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
apiHost: "api.example.test",
appBaseDomain: "example.test",
};
function rootData(tenantApiKeys = true, admin = false, routingConfig?: typeof routing, crm = false) {
return {
appConfiguration: {
app: { features: { tenantApiKeys, crm } },
portals: { enabled: false, forTenants: false },
},
user: { admin },
routing: routingConfig,
} as any;
}
function appData(options?: { admin?: boolean; permissions?: string[]; tenantApiKeys?: boolean }) {
return {
currentTenant: { id: "tenant_1", slug: "acme" },
entities: [
{ name: "company", titlePlural: "models.company.plural", slug: "companies", showInSidebar: true },
{ name: "contact", titlePlural: "models.contact.plural", slug: "contacts", showInSidebar: true },
{ name: "opportunity", titlePlural: "models.opportunity.plural", slug: "opportunities", showInSidebar: true },
],
myTenants: [{ id: "tenant_2", slug: "other" }],
permissions: options?.permissions ?? [
"app.settings.members.view",
"app.settings.subscription.view",
"app.settings.account.view",
"app.settings.apiKeys.view",
"app.settings.auditTrails.view",
"entity.company.view",
"entity.contact.view",
"entity.opportunity.view",
],
isSuperAdmin: false,
user: { id: "user_1", admin: options?.admin ?? true },
} as any;
}
function navigateMock() {
return vi.fn() as unknown as NavigateFunction & { mock: ReturnType<typeof vi.fn>["mock"] };
}
function perform(action: { perform?: (action: any) => void; id: string }) {
action.perform?.({ id: action.id });
}
function expectNoLegacyPrefixes(targets: string[]) {
targets.forEach((target) => {
expect(target).not.toMatch(/^\/app\//);
expect(target).not.toMatch(/^\/admin(?:\/|$)/);
});
}
describe("command registry", () => {
it("builds app tenant commands with host-aware tenant URLs and scope metadata", () => {
const navigate = navigateMock();
const actions = getCommandRegistryActions({ layout: "app", t, navigate, appData: appData(), rootData: rootData() });
perform(actions.find((action) => action.id === "dashboard")!);
perform(actions.find((action) => action.id === "members")!);
perform(actions.find((action) => action.id === "apiKeys")!);
expect(navigate).toHaveBeenNthCalledWith(1, "/acme/dashboard");
expect(navigate).toHaveBeenNthCalledWith(2, "/acme/settings/members");
expect(navigate).toHaveBeenNthCalledWith(3, "/acme/settings/api");
expect(actions.find((action) => action.id === "members")?.scope).toMatchObject({
layout: "app",
tenantSlug: "acme",
permission: "app.settings.members.view",
});
expect(actions.find((action) => action.id === "apiKeys")?.scope).toMatchObject({ featureFlag: "tenantApiKeys", permission: "app.settings.apiKeys.view" });
expectNoLegacyPrefixes(navigate.mock.calls.map(([target]) => target));
});
it("omits app commands for empty app data", () => {
expect(getCommandRegistryActions({ layout: "app", t, navigate: navigateMock(), rootData: rootData() })).toEqual([]);
});
it("filters tenant settings commands by permissions and feature flags", () => {
const actions = getCommandRegistryActions({
layout: "app",
t,
navigate: navigateMock(),
appData: appData({ permissions: ["app.settings.account.view"] }),
rootData: rootData(false),
});
expect(actions.some((action) => action.id === "account")).toBe(true);
expect(actions.some((action) => action.id === "members")).toBe(false);
expect(actions.some((action) => action.id === "subscription")).toBe(false);
expect(actions.some((action) => action.id === "apiKeys")).toBe(false);
expect(actions.some((action) => action.id === "auditTrails")).toBe(false);
expect(actions.some((action) => action.id === "events")).toBe(false);
});
it("filters tenant entity commands through permission-aware scope metadata", () => {
const actions = getCommandRegistryActions({
layout: "app",
t,
navigate: navigateMock(),
appData: appData({ permissions: ["entity.company.view"] }),
rootData: rootData(),
});
expect(actions.find((action) => action.id === "entity-company")?.scope).toMatchObject({
layout: "app",
tenantSlug: "acme",
permission: "entity.company.view",
});
expect(actions.some((action) => action.id === "entity-contact")).toBe(false);
expect(actions.some((action) => action.id === "entity-opportunity")).toBe(false);
});
it("omits CRM command while the CRM route tree is disabled", () => {
const disabled = getCommandRegistryActions({
layout: "app",
t,
navigate: navigateMock(),
appData: appData(),
rootData: rootData(true, true, routing, false),
});
const enabled = getCommandRegistryActions({
layout: "app",
t,
navigate: navigateMock(),
appData: appData(),
rootData: rootData(true, true, routing, true),
});
expect(disabled.some((action) => action.id === "crm")).toBe(false);
expect(enabled.some((action) => action.id === "crm")).toBe(false);
});
it("keeps platform commands available when scoped tenant commands are denied", () => {
const actions = getCommandRegistryActions({
layout: "app",
t,
navigate: navigateMock(),
appData: appData({ admin: false, permissions: [] }),
rootData: rootData(),
});
expect(actions.some((action) => action.id === "entity-company")).toBe(false);
expect(actions.some((action) => action.id === "create account")).toBe(true);
expect(actions.some((action) => action.id === "logout")).toBe(true);
});
it("omits switch-to-admin for non-admin app users", () => {
const actions = getCommandRegistryActions({ layout: "app", t, navigate: navigateMock(), appData: appData({ admin: false }), rootData: rootData() });
expect(actions.some((action) => action.id === "switch to admin")).toBe(false);
});
it("switches app admins to the admin dashboard instead of the admin host root", () => {
const navigate = navigateMock();
const actions = getCommandRegistryActions({ layout: "app", t, navigate, appData: appData({ admin: true }), rootData: rootData(true, true, routing) });
vi.stubGlobal("window", undefined);
try {
perform(actions.find((action) => action.id === "switch to admin")!);
} finally {
vi.unstubAllGlobals();
}
expect(navigate).toHaveBeenCalledWith("https://admin.example.test/dashboard");
});
it("filters admin sidebar commands for non-superadmin contexts while preserving platform commands", () => {
const actions = getCommandRegistryActions({ layout: "admin", t, navigate: navigateMock(), rootData: rootData() });
expect(actions.some((action) => action.id === "/dashboard")).toBe(false);
expect(actions.some((action) => action.id === "create account")).toBe(true);
expect(actions.some((action) => action.id === "logout")).toBe(true);
});
it("builds admin commands when app data has no current tenant", () => {
const actions = getCommandRegistryActions({
layout: "admin",
t,
navigate: navigateMock(),
appData: { ...appData({ admin: true }), currentTenant: null, isSuperAdmin: true } as any,
rootData: rootData(true, true),
});
expect(actions.some((action) => action.id === "/dashboard")).toBe(true);
expect(actions.every((action) => action.scope.layout === "admin")).toBe(true);
});
it("builds admin commands with host-aware paths and app fallback switch", () => {
const navigate = navigateMock();
const actions = getCommandRegistryActions({ layout: "admin", t, navigate, rootData: rootData(true, true) });
perform(actions.find((action) => action.id === "/dashboard")!);
perform(actions.find((action) => action.id === "/settings/profile")!);
perform(actions.find((action) => action.name === "admin.switchToApp")!);
expect(navigate).toHaveBeenNthCalledWith(1, "/dashboard");
expect(navigate).toHaveBeenNthCalledWith(2, "/settings/profile");
expect(navigate).toHaveBeenNthCalledWith(3, "/");
expect(actions.find((action) => action.id === "/dashboard")?.scope).toMatchObject({ layout: "admin", platform: true, adminOnly: true });
expect(actions.find((action) => action.name === "admin.switchToApp")?.scope).toMatchObject({ layout: "admin", platform: true, adminOnly: true });
expectNoLegacyPrefixes(navigate.mock.calls.map(([target]) => target));
});
it("does not expose expandable admin sidebar parents as command destinations", () => {
const actions = getCommandRegistryActions({
layout: "admin",
t,
navigate: navigateMock(),
appData: {
...appData({
admin: true,
permissions: ["admin.accounts.view", "admin.settings.view"],
}),
currentTenant: null,
isSuperAdmin: true,
} as any,
rootData: rootData(true, true),
});
expect(actions.some((action) => action.id === "/accounts" && action.name === "app.sidebar.accountsAndUsers")).toBe(false);
expect(actions.some((action) => action.id === "/settings" && action.name === "app.sidebar.settings")).toBe(false);
expect(actions.some((action) => action.id === "/accounts" && action.name === "admin.tenants.title")).toBe(true);
expect(actions.some((action) => action.id === "/settings/profile")).toBe(true);
});
it("does not expose disabled sidebar items as command destinations", () => {
const actions = getSidebarCommandActions(
[
{
title: "Settings",
path: "/settings",
items: [
{ title: "Profile", path: "/settings/profile" },
{ title: "Disabled Plugin", path: "/settings/plugin", disabled: true },
],
},
],
"admin"
);
expect(actions.some((action) => action.id === "/settings/profile")).toBe(true);
expect(actions.some((action) => action.id === "/settings/plugin")).toBe(false);
});
it("uses parent sidebar titles as command subtitles", () => {
const actions = getSidebarCommandActions(
[
{
title: "Settings",
path: "/settings",
items: [{ title: "Profile", path: "/settings/profile" }],
},
],
"admin"
);
expect(actions.find((action) => action.id === "/settings/profile")?.subtitle).toBe("Settings");
});
it("builds admin public-app commands with absolute app-host URLs when routing is configured", () => {
const navigate = navigateMock();
const actions = getCommandRegistryActions({ layout: "admin", t, navigate, rootData: rootData(true, true, routing) });
expect(actions.find((action) => action.name === "admin.switchToApp")?.id).toBe("https://app.example.test/");
vi.stubGlobal("window", undefined);
try {
perform(actions.find((action) => action.name === "admin.switchToApp")!);
perform(actions.find((action) => action.id === "create account")!);
} finally {
vi.unstubAllGlobals();
}
expect(navigate).toHaveBeenNthCalledWith(1, "https://app.example.test/");
expect(navigate).toHaveBeenNthCalledWith(2, "https://app.example.test/new-account");
});
it("passes docs commands through with registry scope and navigation", () => {
const navigate = navigateMock();
const actions = getCommandRegistryActions({ layout: "docs", t, navigate });
const firstAction = actions[0];
perform(firstAction);
expect(firstAction.scope).toMatchObject({ layout: "docs", platform: true });
expect(navigate).toHaveBeenCalledWith(firstAction.id);
});
it("exposes app, admin, and docs commands directly through the registry", () => {
expect(getCommandRegistryActions({ layout: "app", t, navigate: navigateMock(), appData: appData(), rootData: rootData() })[0]).toMatchObject({
id: "dashboard",
scope: { layout: "app" },
});
expect(getCommandRegistryActions({ layout: "admin", t, navigate: navigateMock(), rootData: rootData(true, true) })[0]).toMatchObject({
id: "/dashboard",
scope: { layout: "admin" },
});
expect(getCommandRegistryActions({ layout: "docs", t, navigate: navigateMock() })[0]).toMatchObject({ scope: { layout: "docs" } });
});
});
@@ -0,0 +1,304 @@
import type { ReactNode } from "react";
import { TFunction, i18n } from "i18next";
import { NavigateFunction } from "react-router";
import { AdminSidebar } from "~/application/sidebar/AdminSidebar";
import { SideBarItem } from "~/application/sidebar/SidebarItem";
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
import { AppLoaderData } from "~/utils/data/useAppData";
import { AppRootData } from "~/utils/data/useRootData";
import { getDocCommands } from "~/utils/services/docsService";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { absoluteAdminPath, absoluteAppRootPath, isAbsoluteHttpUrl, type PublicDomainRoutingConfig } from "~/utils/app/CrossHostUrls";
import { filterCommandActions } from "~/services/search/commandSearch";
import { translateLabel } from "~/utils/i18n/translateLabel";
// Registry marker: services/command-registry paths are app-relative for package verification.
export type CommandRegistryLayout = "app" | "admin" | "docs";
export type CommandActionScope = {
layout: CommandRegistryLayout;
tenantSlug?: string;
platform?: boolean;
adminOnly?: boolean;
featureFlag?: string;
permission?: string;
};
export type CommandAction = {
id: string;
name: string;
subtitle?: string;
keywords?: string;
shortcut?: string[];
icon?: ReactNode;
perform?: (currentAction: CommandAction) => void;
};
export type ScopedCommandAction = CommandAction & {
scope: CommandActionScope;
};
export type CommandRegistryContext = {
layout: CommandRegistryLayout;
t: TFunction;
i18n?: Pick<i18n, "exists">;
navigate: NavigateFunction;
submitLogout?: () => void;
appData?: AppLoaderData;
rootData?: AppRootData;
};
export function getCommandRegistryActions(context: CommandRegistryContext): ScopedCommandAction[] {
const actions = getUnfilteredCommandRegistryActions(context);
return filterCommandActions({
actions,
query: "",
layout: context.layout,
tenantSlug: context.appData?.currentTenant?.slug,
appData: context.appData,
rootData: context.rootData,
});
}
function getUnfilteredCommandRegistryActions(context: CommandRegistryContext): ScopedCommandAction[] {
if (context.layout === "app") {
return getAppCommandActions(context);
}
if (context.layout === "admin") {
return getAdminCommandActions(context);
}
return getDocsCommandActions(context);
}
function getAppCommandActions({ t, i18n, navigate, submitLogout, appData, rootData }: CommandRegistryContext): ScopedCommandAction[] {
if (!appData || !rootData) {
return [];
}
const tenantSlug = appData.currentTenant.slug;
const tenantPath = (path?: string) => appPath({ tenantSlug, path, mode: "host-aware" });
const tenantScope = (metadata?: Omit<CommandActionScope, "layout" | "tenantSlug">): CommandActionScope => ({ layout: "app", tenantSlug, ...metadata });
const actions: ScopedCommandAction[] = [
{
id: "dashboard",
shortcut: [],
name: t("app.sidebar.dashboard"),
keywords: "",
scope: tenantScope(),
perform: () => navigate(tenantPath("dashboard")),
},
];
appData.entities
.filter((entity) => entity.showInSidebar)
.forEach((entity) => {
const permission = typeof entity.name === "string" && entity.name.trim() ? `entity.${entity.name}.view` : undefined;
actions.push({
id: "entity-" + entity.name,
name: translateLabel(t, i18n, entity.titlePlural),
scope: tenantScope({ permission }),
perform: () => navigate(tenantPath(entity.slug)),
});
});
actions.push({
id: "profile",
shortcut: [],
name: t("app.commands.profile.title"),
subtitle: t("app.sidebar.settings"),
keywords: t("app.commands.profile.description"),
scope: tenantScope(),
perform: () => navigate(tenantPath("settings/profile")),
});
pushPermissionAction(actions, appData, "app.settings.members.view", {
id: "members",
name: t("app.navbar.members"),
shortcut: [],
keywords: "",
subtitle: t("app.sidebar.settings"),
scope: tenantScope({ permission: "app.settings.members.view" }),
perform: () => navigate(tenantPath("settings/members")),
});
pushPermissionAction(actions, appData, "app.settings.subscription.view", {
id: "subscription",
name: t("app.navbar.subscription"),
shortcut: [],
keywords: "",
subtitle: t("app.sidebar.settings"),
scope: tenantScope({ permission: "app.settings.subscription.view" }),
perform: () => navigate(tenantPath("settings/subscription")),
});
pushPermissionAction(actions, appData, "app.settings.account.view", {
id: "account",
name: t("app.navbar.tenant"),
shortcut: [],
keywords: "",
subtitle: t("app.sidebar.settings"),
scope: tenantScope({ permission: "app.settings.account.view" }),
perform: () => navigate(tenantPath("settings/account")),
});
if (rootData.appConfiguration.app.features.tenantApiKeys) {
pushPermissionAction(actions, appData, "app.settings.apiKeys.view", {
id: "apiKeys",
name: t("models.apiKey.plural"),
shortcut: [],
keywords: "",
subtitle: t("app.sidebar.settings"),
scope: tenantScope({ featureFlag: "tenantApiKeys", permission: "app.settings.apiKeys.view" }),
perform: () => navigate(tenantPath("settings/api")),
});
}
if (getUserHasPermission(appData, "app.settings.auditTrails.view")) {
actions.push({
id: "auditTrails",
name: t("models.log.plural"),
shortcut: [],
keywords: "",
subtitle: t("app.sidebar.settings"),
scope: tenantScope({ permission: "app.settings.auditTrails.view" }),
perform: () => navigate(tenantPath("settings/logs")),
});
actions.push({
id: "events",
name: t("models.event.plural"),
shortcut: [],
keywords: "",
subtitle: t("app.sidebar.settings"),
scope: tenantScope({ permission: "app.settings.auditTrails.view" }),
perform: () => navigate(tenantPath("settings/logs/events")),
});
}
if (appData.myTenants.length > 0) {
actions.push({
id: "switch account",
shortcut: [],
name: t("app.commands.tenants.switch"),
keywords: t("app.commands.tenants.description"),
scope: { layout: "app", platform: true },
perform: () => navigateOrAssign(absoluteAppRootPath(rootData.routing), navigate),
});
}
actions.push({
id: "create account",
shortcut: [],
name: t("app.commands.tenants.create"),
keywords: "",
scope: { layout: "app", platform: true },
perform: () => navigateOrAssign(absolutePublicAppPath(rootData.routing, "new-account"), navigate),
});
if (appData.user?.admin) {
actions.push({
id: "switch to admin",
shortcut: [],
name: t("admin.switchToAdmin"),
keywords: "",
scope: { layout: "app", platform: true, adminOnly: true },
perform: () => navigateOrAssign(absoluteAdminPath(rootData.routing, "dashboard"), navigate),
});
}
actions.push({
id: "logout",
shortcut: [],
name: t("app.commands.profile.logout"),
scope: { layout: "app", platform: true },
perform: () => submitLogout?.(),
});
return actions;
}
function pushPermissionAction(actions: ScopedCommandAction[], appData: AppLoaderData, permission: string, action: ScopedCommandAction) {
if (getUserHasPermission(appData, permission as never)) {
actions.push(action);
}
}
function getAdminCommandActions({ t, navigate, submitLogout, rootData }: CommandRegistryContext): ScopedCommandAction[] {
if (!rootData) {
return [];
}
const actions = getSidebarCommandActions(AdminSidebar({ t, appConfiguration: rootData.appConfiguration, routing: rootData.routing }), "admin").map(
(action) => ({
...action,
perform(currentAction: CommandAction) {
navigateOrAssign(currentAction.id, navigate);
},
})
);
actions.push({
id: "create account",
shortcut: [],
name: t("app.commands.tenants.create"),
keywords: "",
scope: { layout: "admin", platform: true },
perform: () => navigateOrAssign(absolutePublicAppPath(rootData.routing, "new-account"), navigate),
});
actions.push({
id: "logout",
shortcut: [],
name: t("app.commands.profile.logout"),
scope: { layout: "admin", platform: true },
perform: () => submitLogout?.(),
});
return actions;
}
function navigateOrAssign(target: string, navigate: NavigateFunction) {
if (isAbsoluteHttpUrl(target) && typeof window !== "undefined") {
window.location.assign(target);
return;
}
navigate(target);
}
function absolutePublicAppPath(routing: PublicDomainRoutingConfig | undefined, path: string) {
const appRoot = absoluteAppRootPath(routing);
const cleanPath = path.replace(/^\/+/, "");
if (isAbsoluteHttpUrl(appRoot)) {
return new URL(cleanPath, appRoot).toString();
}
return `/${cleanPath}`;
}
function getDocsCommandActions({ navigate }: CommandRegistryContext): ScopedCommandAction[] {
return getDocCommands().map((action) => ({
...action,
scope: { layout: "docs", platform: true },
perform(currentAction) {
navigate(currentAction.id);
},
}));
}
export function getSidebarCommandActions(items: SideBarItem[], layout: CommandRegistryLayout): ScopedCommandAction[] {
const commands: ScopedCommandAction[] = [];
items.forEach((item) => commands.push(...getCommandsFromSidebarItem(item, layout, [], [])));
return commands;
}
function getCommandsFromSidebarItem(item: SideBarItem, layout: CommandRegistryLayout, commands: ScopedCommandAction[], parent: string[]) {
if (item.hidden || item.disabled) {
return commands;
}
const isExpandableOnlyParent = item.isCollapsible && item.items && item.items.length > 0;
if (item.path && item.title && !isExpandableOnlyParent) {
let description = item.description ?? "";
const parentTitles = parent.filter((value) => value);
if (parentTitles.length > 0) {
description = parentTitles.join(" / ");
}
commands.push({
id: item.path,
name: item.title,
shortcut: [],
subtitle: description,
scope: { layout, platform: true, adminOnly: layout === "admin", permission: item.permission },
});
}
item.items?.forEach((subItem) => getCommandsFromSidebarItem(subItem, layout, commands, [...parent, item.title]));
return commands;
}
@@ -0,0 +1,207 @@
import { describe, expect, it, vi } from "vitest";
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import {
evaluateDashboardModuleGates,
getDashboardModuleDiagnostics,
getVisibleDashboardModules,
type DashboardModuleGateDiagnostic,
} from "./gating.server";
import { dashboardRegistryEvidence, getDashboardModuleDefinitions, type DashboardModuleDefinition } from "./registry.server";
const request = new Request("https://app.example.com/acme/dashboard?tenantId=tenant_123&token=secret-token");
const params = { tenant: "acme", tenantId: "tenant_123" };
const summaryModule = {
id: "summary-stats",
titleKey: "app.dashboard.modules.summaryStats.title",
descriptionKey: "app.dashboard.modules.summaryStats.description",
} as const satisfies DashboardModuleDefinition;
const featureModule = {
id: "subscription-health",
titleKey: "app.dashboard.modules.subscriptionHealth.title",
descriptionKey: "app.dashboard.modules.subscriptionHealth.description",
featureFlagKey: "tenant.subscription.active",
} as const satisfies DashboardModuleDefinition;
const planModule = {
id: "priority-insights",
titleKey: "app.dashboard.modules.priorityInsights.title",
descriptionKey: "app.dashboard.modules.priorityInsights.description",
planFeatureKey: DefaultFeatures.PrioritySupport,
} as const satisfies DashboardModuleDefinition;
function entitlementService(allowed: boolean) {
return vi.fn(() => ({
allowed,
reason: allowed ? ("included" as const) : ("missing-subscription" as const),
featureKey: DefaultFeatures.PrioritySupport,
}));
}
const sensitiveSamples = [
"tenant_123",
"secret-token",
"user_456",
"subscription_789",
"provider_api_key_live",
"raw-feature-input=tenant.subscription.active",
"DATABASE_URL",
"bearer jwt-token",
] as const;
function expectSafeStaticPayload(payload: unknown) {
const serialized = JSON.stringify(payload);
for (const sample of sensitiveSamples) {
expect(serialized).not.toContain(sample);
}
expect(serialized).not.toMatch(/user[_-]?\d+|subscription[_-]?\d+|provider[_-]?api[_-]?key|bearer\s+jwt|jwt-token|secret-token/i);
}
function expectDiagnosticsRedacted(diagnostics: readonly DashboardModuleGateDiagnostic[]) {
expectSafeStaticPayload(diagnostics);
}
describe("dashboard module registry", () => {
it("defines stable module contracts for summary, plan-gated, and feature-gated modules", () => {
expect(getDashboardModuleDefinitions()).toEqual(
expect.arrayContaining([
expect.objectContaining({ id: "summary-stats" }),
expect.objectContaining({ id: "priority-insights", planFeatureKey: DefaultFeatures.PrioritySupport }),
expect.objectContaining({ id: "subscription-health", featureFlagKey: "tenant.subscription.active" }),
]),
);
});
it("exports source-backed registry evidence with stable IDs and gate coverage", () => {
const definitions = getDashboardModuleDefinitions();
expect(dashboardRegistryEvidence.registryName).toBe("Tenant/Workspace Dashboard");
expect(dashboardRegistryEvidence.registryScope).toBe("tenant-workspace-dashboard-modules");
expect(dashboardRegistryEvidence.expectedModuleIds).toEqual(definitions.map((module) => module.id));
expect(dashboardRegistryEvidence.expectedModuleIds).toEqual(["summary-stats", "priority-insights", "subscription-health"]);
expect(dashboardRegistryEvidence.gatingSourcesRepresented).toEqual(["feature-flag", "plan"]);
expect(definitions.find((module) => module.id === "summary-stats")).toEqual(expect.not.objectContaining({ featureFlagKey: expect.any(String) }));
expect(definitions.find((module) => module.id === "summary-stats")).toEqual(expect.not.objectContaining({ planFeatureKey: expect.any(String) }));
expect(definitions.find((module) => module.id === "priority-insights")).toEqual(
expect.objectContaining({ planFeatureKey: DefaultFeatures.PrioritySupport }),
);
expect(definitions.find((module) => module.id === "subscription-health")).toEqual(
expect.objectContaining({ featureFlagKey: "tenant.subscription.active" }),
);
});
it("keeps registry evidence limited to safe static metadata", () => {
expect(dashboardRegistryEvidence.redactionGuarantee).toContain("static source metadata only");
expect(dashboardRegistryEvidence.redactionGuarantee).toContain("excludes request, tenant, subscription, user, token, environment, and raw feature input values");
expect(dashboardRegistryEvidence.expectedModuleIds.length).toBe(getDashboardModuleDefinitions().length);
expectSafeStaticPayload(dashboardRegistryEvidence);
});
});
describe("evaluateDashboardModuleGates", () => {
it("returns visible modules when all gates allow access", async () => {
const decisions = await evaluateDashboardModuleGates({
request,
params,
definitions: [summaryModule, featureModule, planModule],
services: {
hasFeatureFlag: vi.fn(async () => true),
evaluateSubscriptionEntitlement: entitlementService(true),
},
});
expect(getVisibleDashboardModules(decisions).map((module) => module.id)).toEqual(["summary-stats", "subscription-health", "priority-insights"]);
expect(getDashboardModuleDiagnostics(decisions)).toEqual([]);
});
it("denies only a disabled feature-flagged module", async () => {
const decisions = await evaluateDashboardModuleGates({
request,
params,
definitions: [summaryModule, featureModule, planModule],
services: {
hasFeatureFlag: vi.fn(async () => false),
evaluateSubscriptionEntitlement: entitlementService(true),
},
});
expect(getVisibleDashboardModules(decisions).map((module) => module.id)).toEqual(["summary-stats", "priority-insights"]);
expect(getDashboardModuleDiagnostics(decisions)).toEqual([
{
moduleId: "subscription-health",
source: "feature-flag",
reason: "feature-disabled",
redirectPath: "/feature-disabled",
},
]);
});
it("denies only the gated module when feature flag lookup fails", async () => {
const decisions = await evaluateDashboardModuleGates({
request,
params,
definitions: [summaryModule, featureModule],
services: {
hasFeatureFlag: vi.fn(async () => {
throw new Error("backend unavailable for tenant_123 with token secret-token");
}),
},
});
expect(getVisibleDashboardModules(decisions).map((module) => module.id)).toEqual(["summary-stats"]);
expect(getDashboardModuleDiagnostics(decisions)).toEqual([
{
moduleId: "subscription-health",
source: "feature-flag",
reason: "feature-check-failed",
redirectPath: "/feature-disabled",
},
]);
});
it("denies missing plan entitlement with plan-required diagnostics", async () => {
const decisions = await evaluateDashboardModuleGates({
request,
params,
definitions: [summaryModule, planModule],
subscription: { products: [] },
services: {
evaluateSubscriptionEntitlement: entitlementService(false),
},
});
expect(getVisibleDashboardModules(decisions).map((module) => module.id)).toEqual(["summary-stats"]);
expect(getDashboardModuleDiagnostics(decisions)).toEqual([
{
moduleId: "priority-insights",
source: "plan",
reason: "plan-required",
redirectPath: "plan-required",
},
]);
});
it("keeps denied diagnostics redacted from tenant, subscription, user, and token inputs", async () => {
const decisions = await evaluateDashboardModuleGates({
request,
params,
definitions: [featureModule, planModule],
subscription: { products: [] },
services: {
hasFeatureFlag: vi.fn(async () => false),
evaluateSubscriptionEntitlement: entitlementService(false),
},
redirectPaths: {
"feature-flag": "/feature-disabled",
plan: "plan-required",
},
});
expect(getDashboardModuleDiagnostics(decisions)).toEqual([
expect.objectContaining({ moduleId: "subscription-health", source: "feature-flag", reason: "feature-disabled" }),
expect.objectContaining({ moduleId: "priority-insights", source: "plan", reason: "plan-required" }),
]);
expectDiagnosticsRedacted(getDashboardModuleDiagnostics(decisions));
});
});
@@ -0,0 +1,198 @@
import type { Params } from "react-router";
import type { EntitlementDecision } from "@toolctrl/entitlements";
import type {
SubscriptionEntitlementSubscription,
SubscriptionEntitlementTrialState,
} from "~/utils/entitlements/.server/subscriptionEntitlements.server";
import { evaluateSubscriptionEntitlement as defaultEvaluateSubscriptionEntitlement } from "~/utils/entitlements/.server/subscriptionEntitlements.server";
import { isFeatureFlagEnabled } from "~/utils/services/.server/featureFlagsRequest.server";
import { getDashboardModuleDefinitions, type DashboardModuleDefinition, type DashboardModuleId } from "./registry.server";
export type DashboardModuleGateSource = "feature-flag" | "plan";
export type DashboardModuleGateReason = "feature-disabled" | "feature-check-failed" | "plan-required";
export interface DashboardModuleGateDiagnostic {
readonly moduleId: DashboardModuleId;
readonly source: DashboardModuleGateSource;
readonly reason: DashboardModuleGateReason;
readonly redirectPath?: string;
}
export interface DashboardModuleGateDecision {
readonly module: DashboardModuleDefinition;
readonly allowed: boolean;
readonly diagnostic?: DashboardModuleGateDiagnostic;
}
export interface EvaluateDashboardModuleGatesInput {
readonly request: Request;
readonly params: Params;
readonly subscription?: SubscriptionEntitlementSubscription | null;
readonly trial?: SubscriptionEntitlementTrialState | null;
readonly definitions?: readonly DashboardModuleDefinition[];
readonly redirectPaths?: Partial<Record<DashboardModuleGateSource, string>>;
readonly services?: DashboardModuleGateServices;
readonly serviceLoaders?: DashboardModuleGateServiceLoaders;
}
export interface DashboardModuleGateServices {
/**
* Boolean feature-flag check shimmed against the v2 evaluator
* (`isFeatureFlagEnabled`). Tests inject a stub; production wiring
* resolves the request + tenant context inside the v2 helper.
*/
readonly hasFeatureFlag?: (input: { request: Request; params: Params; flagName: string }) => Promise<boolean>;
readonly evaluateSubscriptionEntitlement?: (input: {
featureKey: string;
subscription?: SubscriptionEntitlementSubscription | null;
trial?: SubscriptionEntitlementTrialState | null;
}) => EntitlementDecision;
}
export interface DashboardModuleGateServiceLoaders {
readonly featureFlags?: () => Promise<Pick<Required<DashboardModuleGateServices>, "hasFeatureFlag">>;
readonly entitlements?: () => Promise<Pick<Required<DashboardModuleGateServices>, "evaluateSubscriptionEntitlement">>;
}
const defaultRedirectPaths = Object.freeze({
"feature-flag": "/feature-disabled",
plan: "plan-required",
} satisfies Record<DashboardModuleGateSource, string>);
function diagnostic(input: {
moduleId: DashboardModuleId;
source: DashboardModuleGateSource;
reason: DashboardModuleGateReason;
redirectPath?: string;
}): DashboardModuleGateDiagnostic {
return {
moduleId: input.moduleId,
source: input.source,
reason: input.reason,
...(input.redirectPath ? { redirectPath: input.redirectPath } : {}),
};
}
async function evaluateDashboardModuleGate({
module,
request,
params,
subscription,
trial,
redirectPaths,
services,
serviceLoaders,
}: Omit<EvaluateDashboardModuleGatesInput, "definitions"> & { module: DashboardModuleDefinition }): Promise<DashboardModuleGateDecision> {
if (module.featureFlagKey) {
try {
if (!services?.hasFeatureFlag) {
const featureFlagService = serviceLoaders?.featureFlags
? await serviceLoaders.featureFlags()
: { hasFeatureFlag: ({ request: req, params: p, flagName }: { request: Request; params: Params; flagName: string }) => isFeatureFlagEnabled(flagName, { request: req, params: p }) };
services = { ...services, hasFeatureFlag: featureFlagService.hasFeatureFlag };
}
const hasFeatureFlag = services.hasFeatureFlag;
if (!hasFeatureFlag) {
throw new Error("Dashboard feature flag service unavailable");
}
const enabled = await hasFeatureFlag({
request,
params,
flagName: module.featureFlagKey,
});
if (!enabled) {
return {
module,
allowed: false,
diagnostic: diagnostic({
moduleId: module.id,
source: "feature-flag",
reason: "feature-disabled",
redirectPath: redirectPaths?.["feature-flag"] ?? defaultRedirectPaths["feature-flag"],
}),
};
}
} catch {
return {
module,
allowed: false,
diagnostic: diagnostic({
moduleId: module.id,
source: "feature-flag",
reason: "feature-check-failed",
redirectPath: redirectPaths?.["feature-flag"] ?? defaultRedirectPaths["feature-flag"],
}),
};
}
}
if (module.planFeatureKey) {
if (!services?.evaluateSubscriptionEntitlement) {
const entitlementService = serviceLoaders?.entitlements
? await serviceLoaders.entitlements()
: { evaluateSubscriptionEntitlement: defaultEvaluateSubscriptionEntitlement };
services = { ...services, evaluateSubscriptionEntitlement: entitlementService.evaluateSubscriptionEntitlement };
}
const evaluateSubscriptionEntitlement = services.evaluateSubscriptionEntitlement;
if (!evaluateSubscriptionEntitlement) {
throw new Error("Dashboard entitlement service unavailable");
}
const entitlement = evaluateSubscriptionEntitlement({
featureKey: module.planFeatureKey,
subscription,
trial,
});
if (!entitlement.allowed) {
return {
module,
allowed: false,
diagnostic: diagnostic({
moduleId: module.id,
source: "plan",
reason: "plan-required",
redirectPath: redirectPaths?.plan ?? defaultRedirectPaths.plan,
}),
};
}
}
return { module, allowed: true };
}
export async function evaluateDashboardModuleGates({
request,
params,
subscription,
trial,
definitions = getDashboardModuleDefinitions(),
redirectPaths,
services,
serviceLoaders,
}: EvaluateDashboardModuleGatesInput): Promise<DashboardModuleGateDecision[]> {
return Promise.all(
definitions.map((module) =>
evaluateDashboardModuleGate({
module,
request,
params,
subscription,
trial,
redirectPaths,
services,
serviceLoaders,
}),
),
);
}
export function getVisibleDashboardModules(decisions: readonly DashboardModuleGateDecision[]): DashboardModuleDefinition[] {
return decisions.filter((decision) => decision.allowed).map((decision) => decision.module);
}
export function getDashboardModuleDiagnostics(decisions: readonly DashboardModuleGateDecision[]): DashboardModuleGateDiagnostic[] {
return decisions.flatMap((decision) => (decision.diagnostic ? [decision.diagnostic] : []));
}
@@ -0,0 +1,48 @@
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import type { FeatureFlagsFilterType } from "~/modules/featureFlags/dtos/FeatureFlagsFilterTypes";
export type DashboardModuleId = "summary-stats" | "priority-insights" | "subscription-health";
export interface DashboardModuleDefinition {
readonly id: DashboardModuleId;
readonly titleKey: string;
readonly descriptionKey: string;
readonly featureFlagKey?: FeatureFlagsFilterType;
readonly planFeatureKey?: DefaultFeatures | string;
}
export const dashboardModuleRegistry = Object.freeze([
{
id: "summary-stats",
titleKey: "app.dashboard.modules.summaryStats.title",
descriptionKey: "app.dashboard.modules.summaryStats.description",
},
{
id: "priority-insights",
titleKey: "app.dashboard.modules.priorityInsights.title",
descriptionKey: "app.dashboard.modules.priorityInsights.description",
planFeatureKey: DefaultFeatures.PrioritySupport,
},
{
id: "subscription-health",
titleKey: "app.dashboard.modules.subscriptionHealth.title",
descriptionKey: "app.dashboard.modules.subscriptionHealth.description",
featureFlagKey: "tenant.subscription.active",
},
] as const satisfies readonly DashboardModuleDefinition[]);
const dashboardModuleIds = dashboardModuleRegistry.map((module) => module.id) as readonly DashboardModuleId[];
const dashboardGateSources = Object.freeze(["feature-flag", "plan"] as const);
export const dashboardRegistryEvidence = Object.freeze({
registryName: "Tenant/Workspace Dashboard",
registryScope: "tenant-workspace-dashboard-modules",
expectedModuleIds: dashboardModuleIds,
gatingSourcesRepresented: dashboardGateSources,
redactionGuarantee:
"Dashboard registry evidence is static source metadata only and excludes request, tenant, subscription, user, token, environment, and raw feature input values.",
} as const);
export function getDashboardModuleDefinitions(): readonly DashboardModuleDefinition[] {
return dashboardModuleRegistry;
}
@@ -0,0 +1,120 @@
import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import { ScopedCommandAction } from "~/services/command-registry/commandRegistry";
import { filterCommandActions } from "./commandSearch";
function rootData(options?: { tenantApiKeys?: boolean; admin?: boolean }) {
return {
user: { id: "user_1", admin: options?.admin ?? false },
appConfiguration: {
app: { features: { tenantApiKeys: options?.tenantApiKeys ?? true } },
},
} as any;
}
function appData(options?: { admin?: boolean; permissions?: string[]; tenantSlug?: string }) {
return {
currentTenant: { id: "tenant_1", slug: options?.tenantSlug ?? "acme" },
permissions: options?.permissions ?? ["app.settings.members.view"],
isSuperAdmin: false,
user: { id: "user_1", admin: options?.admin ?? false },
} as any;
}
const actions = [
action({ id: "dashboard", name: "Dashboard", keywords: "home overview" }),
action({ id: "members", name: "Members", subtitle: "Settings", permission: "app.settings.members.view" }),
action({ id: "billing", name: "Billing", permission: "app.settings.subscription.view" }),
action({ id: "switch-to-admin", name: "Switch to admin", adminOnly: true }),
action({ id: "other-tenant", name: "Other tenant", tenantSlug: "globex" }),
action({ id: "apiKeys", name: "API Keys", featureFlag: "tenantApiKeys" }),
action({ id: "unknown-feature", name: "Unknown feature", featureFlag: "newFlag" }),
action({ id: "admin-dashboard", name: "Admin dashboard", layout: "admin", adminOnly: true }),
] satisfies ScopedCommandAction[];
function action(options: {
id: string;
name: string;
subtitle?: string;
keywords?: string;
layout?: "app" | "admin" | "docs";
tenantSlug?: string;
adminOnly?: boolean;
featureFlag?: string;
permission?: string;
}): ScopedCommandAction {
return {
id: options.id,
name: options.name,
subtitle: options.subtitle,
keywords: options.keywords,
shortcut: [],
scope: {
layout: options.layout ?? "app",
tenantSlug: options.tenantSlug ?? "acme",
adminOnly: options.adminOnly,
featureFlag: options.featureFlag,
permission: options.permission,
},
};
}
function search(query: string, options?: Parameters<typeof appData>[0] & { tenantApiKeys?: boolean; tenantSlug?: string }) {
return filterCommandActions({
actions,
query,
layout: "app",
tenantSlug: options?.tenantSlug ?? "acme",
appData: appData(options),
rootData: rootData({ tenantApiKeys: options?.tenantApiKeys, admin: options?.admin }),
}).map((result) => result.id);
}
describe("command search", () => {
it("returns all scope-allowed actions for a blank query", () => {
expect(search(" ", { admin: true, permissions: ["app.settings.members.view", "app.settings.subscription.view"] })).toEqual([
"dashboard",
"members",
"billing",
"switch-to-admin",
"apiKeys",
]);
});
it("matches query text case-insensitively across id, name, subtitle, and keywords", () => {
expect(search("dash")).toEqual(["dashboard"]);
expect(search("SETTINGS")).toEqual(["members"]);
expect(search("overview")).toEqual(["dashboard"]);
expect(search("apikeys")).toEqual(["apiKeys"]);
});
it("keeps search normalization independent from host locale", () => {
const source = readFileSync(`${__dirname}/commandSearch.ts`, "utf8");
expect(source).not.toContain("toLocaleLowerCase");
});
it("returns no results for unmatched query text", () => {
expect(search("does-not-exist", { admin: true, permissions: ["app.settings.members.view", "app.settings.subscription.view"] })).toEqual([]);
});
it("denies permission-scoped actions without the required permission", () => {
expect(search("", { permissions: [] })).not.toContain("members");
expect(search("", { permissions: [] })).not.toContain("billing");
});
it("denies admin-only actions for non-admin users and missing app context", () => {
expect(search("")).not.toContain("switch-to-admin");
expect(filterCommandActions({ actions, query: "", layout: "app", tenantSlug: "acme", rootData: rootData({ admin: true }) }).map((result) => result.id)).not.toContain("switch-to-admin");
});
it("denies tenant-scoped actions for the wrong tenant", () => {
expect(search("", { tenantSlug: "globex", admin: true, permissions: ["app.settings.members.view", "app.settings.subscription.view"] })).toEqual(["other-tenant"]);
});
it("denies disabled and unknown feature flags", () => {
const results = search("", { tenantApiKeys: false, admin: true, permissions: ["app.settings.members.view", "app.settings.subscription.view"] });
expect(results).not.toContain("apiKeys");
expect(results).not.toContain("unknown-feature");
});
});
@@ -0,0 +1,89 @@
import { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
import { ScopedCommandAction, CommandRegistryLayout } from "~/services/command-registry/commandRegistry";
import { AppLoaderData } from "~/utils/data/useAppData";
import { AppRootData } from "~/utils/data/useRootData";
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
export type CommandSearchInput = {
actions: ScopedCommandAction[];
query: string;
layout: CommandRegistryLayout;
tenantSlug?: string;
appData?: AppLoaderData;
rootData?: AppRootData;
};
export function filterCommandActions({ actions, query, layout, tenantSlug, appData, rootData }: CommandSearchInput): ScopedCommandAction[] {
const normalizedQuery = normalizeSearchTerm(query);
return actions.filter((action) => actionMatchesScope(action, { layout, tenantSlug, appData, rootData })).filter((action) => actionMatchesQuery(action, normalizedQuery));
}
function actionMatchesQuery(action: ScopedCommandAction, normalizedQuery: string) {
if (!normalizedQuery) {
return true;
}
return [action.id, action.name, action.subtitle, action.keywords].some((value) => normalizeSearchTerm(searchableText(value)).includes(normalizedQuery));
}
type ScopeContext = Pick<CommandSearchInput, "layout" | "tenantSlug" | "appData" | "rootData">;
function actionMatchesScope(action: ScopedCommandAction, { layout, tenantSlug, appData, rootData }: ScopeContext) {
const scope = action.scope;
if (scope.layout !== layout) {
return false;
}
if (scope.tenantSlug && (!tenantSlug || scope.tenantSlug !== tenantSlug)) {
return false;
}
if (scope.adminOnly && !isAdminContext(layout, appData, rootData)) {
return false;
}
if (scope.featureFlag && !featureFlagIsEnabled(scope.featureFlag, rootData)) {
return false;
}
if (scope.permission) {
if (!appData || !Array.isArray(appData.permissions)) {
return false;
}
return getUserHasPermission(appData, scope.permission as DefaultPermission);
}
return true;
}
function isAdminContext(layout: CommandRegistryLayout, appData?: AppLoaderData, rootData?: AppRootData) {
if (appData?.isSuperAdmin === true || userIsAdmin(appData?.user)) {
return true;
}
if (layout === "admin") {
return userIsAdmin(rootData?.user);
}
return false;
}
function userIsAdmin(user: unknown) {
return typeof user === "object" && user !== null && "admin" in user && (user as { admin?: unknown }).admin === true;
}
function featureFlagIsEnabled(featureFlag: string, rootData?: AppRootData) {
if (!rootData) {
return false;
}
if (featureFlag === "tenantApiKeys") {
return rootData.appConfiguration.app.features.tenantApiKeys === true;
}
return false;
}
function searchableText(value: unknown) {
if (Array.isArray(value)) {
return value.join(" ");
}
if (typeof value === "string" || typeof value === "number") {
return String(value);
}
return "";
}
function normalizeSearchTerm(value: string) {
return value.trim().toLowerCase();
}