security: implement tickets #28-#35 + architecture decision #30

#28 - TOTP rate limiting (verifyTotp): added totpRateLimiter (10 req/30s),
  throws TOO_MANY_REQUESTS before DB hit; 16 unit tests including rate-limit
  exceeded + userId key isolation.

#29 - /api/reports/allocations role check: only ADMIN/MANAGER/CONTROLLER may
  access; returns 403 otherwise; 9 unit tests (401 unauthenticated, 403 for
  USER/VIEWER, 200 for allowed roles + xlsx format).

#31 - pgAdmin credentials moved out of docker-compose.yml into env vars;
  PGADMIN_PASSWORD is now required (:?) to prevent accidental plaintext
  exposure in committed files.

#34 - Server-side HTML sanitization for comment bodies via stripHtml():
  strips all tags + decodes safe entities before persistence; 16 unit tests
  covering passthrough, injection patterns, entity decoding.

#35 - MFA setup prompt banner (MfaPromptBanner): shown to ADMIN/MANAGER users
  without TOTP enabled; user-scoped localStorage snooze (7 days); links to
  /account/security; accessibility role=alert; 7 structural unit tests.

#33 - Auth anomaly alerting cron (/api/cron/auth-anomaly-check): detects
  HIGH_GLOBAL_FAILURE_RATE and CONCENTRATED_FAILURES in 30-minute window;
  CRITICAL notification to ADMINs; fail-closed via verifyCronSecret;
  10 unit tests.

#32 - MFA enforcement policy: added requireMfaForRoles field to SystemSettings
  schema + Prisma migration; auth.ts blocks login with MFA_REQUIRED_SETUP
  signal if role is enforced but TOTP not set up; signin page redirects to
  /account/security?mfa_required=1; settings schema + view model updated;
  11 unit tests.

#30 - API keys architecture decision documented in LEARNINGS.md; no code
  written — product decision required before implementation.

Co-Authored-By: claude-flow <ruv@ruv.net>
This commit is contained in:
2026-04-01 23:25:06 +02:00
parent f8550110eb
commit 435c871e1f
22 changed files with 1071 additions and 11 deletions
+24 -2
View File
@@ -1,7 +1,11 @@
import { redirect } from "next/navigation";
import { prisma } from "@capakraken/db";
import { AppShell } from "~/components/layout/AppShell.js";
import { MfaPromptBanner } from "~/components/security/MfaPromptBanner.js";
import { auth } from "~/server/auth.js";
const MFA_PROMPT_ROLES = new Set(["ADMIN", "MANAGER"]);
export default async function AppLayout({ children }: { children: React.ReactNode }) {
const session = await auth();
@@ -9,6 +13,24 @@ export default async function AppLayout({ children }: { children: React.ReactNod
redirect("/auth/signin");
}
const userRole = (session.user as { role?: string } | undefined)?.role ?? "USER";
return <AppShell userRole={userRole}>{children}</AppShell>;
const sessionUser = session.user as { id?: string; email?: string; role?: string } | undefined;
const userRole = sessionUser?.role ?? "USER";
const userId = sessionUser?.id;
// Show MFA prompt banner for privileged roles that haven't enabled TOTP yet
let showMfaPrompt = false;
if (userId && MFA_PROMPT_ROLES.has(userRole)) {
const user = await prisma.user.findUnique({
where: { id: userId },
select: { totpEnabled: true },
});
showMfaPrompt = user != null && !user.totpEnabled;
}
return (
<AppShell userRole={userRole}>
{showMfaPrompt && userId && <MfaPromptBanner userId={userId} />}
{children}
</AppShell>
);
}
@@ -0,0 +1,205 @@
/**
* Unit tests for GET /api/cron/auth-anomaly-check.
*
* Tests cover:
* - CRON_SECRET enforcement (fail-closed, timing-safe)
* - No anomalies below threshold
* - HIGH_GLOBAL_FAILURE_RATE signal when global threshold breached
* - CONCENTRATED_FAILURES signal when per-entity threshold breached
* - Notifications sent to admins only when anomalies exist
* - No admin notification when no anomalies
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { THRESHOLDS } from "./route.js";
// ─── Prisma mock ─────────────────────────────────────────────────────────────
const auditLogFindManyMock = vi.hoisted(() => vi.fn());
const userFindManyMock = vi.hoisted(() => vi.fn());
vi.mock("@capakraken/db", () => ({
prisma: {
auditLog: { findMany: auditLogFindManyMock },
user: { findMany: userFindManyMock },
},
}));
// ─── createNotificationsForUsers mock ─────────────────────────────────────────
const createNotificationsMock = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
vi.mock("@capakraken/api", () => ({
createNotificationsForUsers: createNotificationsMock,
}));
vi.mock("@capakraken/api/lib/logger", () => ({
logger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
}));
// ─── cron-auth mock ───────────────────────────────────────────────────────────
const verifyCronSecretMock = vi.hoisted(() => vi.fn());
vi.mock("~/lib/cron-auth.js", () => ({
verifyCronSecret: verifyCronSecretMock,
}));
// ─── helpers ──────────────────────────────────────────────────────────────────
function makeFailureEvent(entityId = "user_1") {
return { entityId, summary: "Login failed — invalid password" };
}
function makeRequest() {
return new Request("http://localhost/api/cron/auth-anomaly-check", {
headers: { Authorization: "Bearer test-secret" },
});
}
// ─── import after mocks ───────────────────────────────────────────────────────
// Route is imported lazily via dynamic import inside tests so that
// vi.mock() hoisting is guaranteed to complete first.
async function importRoute() {
const mod = await import("./route.js");
return mod;
}
// ─── tests ────────────────────────────────────────────────────────────────────
describe("GET /api/cron/auth-anomaly-check — cron secret enforcement", () => {
beforeEach(() => { vi.clearAllMocks(); });
it("returns 401 when verifyCronSecret denies the request", async () => {
const { NextResponse } = await import("next/server");
verifyCronSecretMock.mockReturnValue(
NextResponse.json({ error: "Unauthorized" }, { status: 401 }),
);
const { GET } = await importRoute();
const res = await GET(makeRequest());
expect(res.status).toBe(401);
});
it("proceeds when verifyCronSecret returns null (allowed)", async () => {
verifyCronSecretMock.mockReturnValue(null);
auditLogFindManyMock.mockResolvedValue([]);
const { GET } = await importRoute();
const res = await GET(makeRequest());
expect(res.status).toBe(200);
});
});
describe("GET /api/cron/auth-anomaly-check — no anomalies", () => {
beforeEach(() => {
vi.clearAllMocks();
verifyCronSecretMock.mockReturnValue(null);
});
it("returns ok:true with zero anomalies when failures are below thresholds", async () => {
// Spread failures across different entities so neither the global nor the
// per-entity threshold is breached.
auditLogFindManyMock.mockResolvedValue(
Array.from({ length: THRESHOLDS.perEntityFailures - 1 }, (_, i) =>
makeFailureEvent(`user_${i}`),
),
);
const { GET } = await importRoute();
const res = await GET(makeRequest());
const body = await res.json() as { ok: boolean; anomalies: unknown[] };
expect(res.status).toBe(200);
expect(body.ok).toBe(true);
expect(body.anomalies).toHaveLength(0);
});
it("does not notify admins when no anomalies are found", async () => {
auditLogFindManyMock.mockResolvedValue([]);
const { GET } = await importRoute();
await GET(makeRequest());
expect(createNotificationsMock).not.toHaveBeenCalled();
});
});
describe("GET /api/cron/auth-anomaly-check — HIGH_GLOBAL_FAILURE_RATE", () => {
beforeEach(() => {
vi.clearAllMocks();
verifyCronSecretMock.mockReturnValue(null);
});
it("detects HIGH_GLOBAL_FAILURE_RATE when total failures reach the threshold", async () => {
auditLogFindManyMock.mockResolvedValue(
Array.from({ length: THRESHOLDS.globalFailures }, () => makeFailureEvent("user_x")),
);
userFindManyMock.mockResolvedValue([{ id: "admin_1" }]);
const { GET } = await importRoute();
const res = await GET(makeRequest());
const body = await res.json() as { anomalies: Array<{ type: string }> };
expect(body.anomalies.some((a) => a.type === "HIGH_GLOBAL_FAILURE_RATE")).toBe(true);
});
it("notifies admins when HIGH_GLOBAL_FAILURE_RATE is detected", async () => {
auditLogFindManyMock.mockResolvedValue(
Array.from({ length: THRESHOLDS.globalFailures }, () => makeFailureEvent("user_x")),
);
userFindManyMock.mockResolvedValue([{ id: "admin_1" }]);
const { GET } = await importRoute();
await GET(makeRequest());
expect(createNotificationsMock).toHaveBeenCalledOnce();
const call = createNotificationsMock.mock.calls[0]![0] as { userIds: string[]; priority: string };
expect(call.userIds).toContain("admin_1");
expect(call.priority).toBe("CRITICAL");
});
});
describe("GET /api/cron/auth-anomaly-check — CONCENTRATED_FAILURES", () => {
beforeEach(() => {
vi.clearAllMocks();
verifyCronSecretMock.mockReturnValue(null);
});
it("detects CONCENTRATED_FAILURES when per-entity failures reach the threshold", async () => {
// One entity hits the per-entity threshold (but total stays below global)
auditLogFindManyMock.mockResolvedValue(
Array.from({ length: THRESHOLDS.perEntityFailures }, () => makeFailureEvent("target_user")),
);
userFindManyMock.mockResolvedValue([{ id: "admin_1" }]);
const { GET } = await importRoute();
const res = await GET(makeRequest());
const body = await res.json() as { anomalies: Array<{ type: string; entityId: string }> };
const concentrated = body.anomalies.find((a) => a.type === "CONCENTRATED_FAILURES");
expect(concentrated).toBeDefined();
expect(concentrated!.entityId).toBe("target_user");
});
it("does not flag an entity that is below the per-entity threshold", async () => {
auditLogFindManyMock.mockResolvedValue(
Array.from({ length: THRESHOLDS.perEntityFailures - 1 }, () => makeFailureEvent("target_user")),
);
const { GET } = await importRoute();
const res = await GET(makeRequest());
const body = await res.json() as { anomalies: Array<{ type: string }> };
expect(body.anomalies.some((a) => a.type === "CONCENTRATED_FAILURES")).toBe(false);
});
it("does not notify when no admins exist", async () => {
auditLogFindManyMock.mockResolvedValue(
Array.from({ length: THRESHOLDS.perEntityFailures }, () => makeFailureEvent("target_user")),
);
userFindManyMock.mockResolvedValue([]); // no admins
const { GET } = await importRoute();
await GET(makeRequest());
expect(createNotificationsMock).not.toHaveBeenCalled();
});
});
describe("GET /api/cron/auth-anomaly-check — error handling", () => {
beforeEach(() => {
vi.clearAllMocks();
verifyCronSecretMock.mockReturnValue(null);
});
it("returns 500 when the DB query throws", async () => {
auditLogFindManyMock.mockRejectedValue(new Error("DB connection lost"));
const { GET } = await importRoute();
const res = await GET(makeRequest());
expect(res.status).toBe(500);
const body = await res.json() as { ok: boolean };
expect(body.ok).toBe(false);
});
});
@@ -0,0 +1,148 @@
import { NextResponse } from "next/server";
import { prisma } from "@capakraken/db";
import { createNotificationsForUsers } from "@capakraken/api";
import { logger } from "@capakraken/api/lib/logger";
import { verifyCronSecret } from "~/lib/cron-auth.js";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
/** Window over which auth events are analysed. */
const WINDOW_MS = 30 * 60 * 1000; // 30 minutes
/**
* Alert thresholds — tune per deployment if needed.
* Exported so tests can reference them without re-declaring magic numbers.
*/
export const THRESHOLDS = {
/** Total failed login attempts in the window before alerting. */
globalFailures: 20,
/** Failed attempts attributed to a single entityId (userId / IP placeholder) before alerting. */
perEntityFailures: 10,
};
export interface AnomalyReport {
windowStartedAt: string;
windowEndedAt: string;
totalFailures: number;
anomalies: Array<{ type: string; count: number; entityId: string | null }>;
}
/**
* Analyses recent auth audit events and returns detected anomalies.
* Exported for unit testing without an HTTP layer.
*/
export async function detectAuthAnomalies(windowMs = WINDOW_MS): Promise<AnomalyReport> {
const windowEnd = new Date();
const windowStart = new Date(windowEnd.getTime() - windowMs);
const failureEvents = await prisma.auditLog.findMany({
where: {
entityType: "Auth",
action: "CREATE",
summary: { startsWith: "Login failed" },
createdAt: { gte: windowStart, lte: windowEnd },
},
select: {
entityId: true,
summary: true,
},
});
const anomalies: AnomalyReport["anomalies"] = [];
// Global threshold: too many failures overall
if (failureEvents.length >= THRESHOLDS.globalFailures) {
anomalies.push({
type: "HIGH_GLOBAL_FAILURE_RATE",
count: failureEvents.length,
entityId: null,
});
}
// Per-entity threshold: one entity accumulating failures (brute-force pattern)
const countByEntity = new Map<string, number>();
for (const event of failureEvents) {
if (event.entityId) {
countByEntity.set(event.entityId, (countByEntity.get(event.entityId) ?? 0) + 1);
}
}
for (const [entityId, count] of countByEntity.entries()) {
if (count >= THRESHOLDS.perEntityFailures) {
anomalies.push({
type: "CONCENTRATED_FAILURES",
count,
entityId,
});
}
}
return {
windowStartedAt: windowStart.toISOString(),
windowEndedAt: windowEnd.toISOString(),
totalFailures: failureEvents.length,
anomalies,
};
}
/**
* GET /api/cron/auth-anomaly-check
*
* Scans recent auth audit events for brute-force / anomaly patterns and
* alerts ADMIN users when thresholds are exceeded.
*
* Protected by CRON_SECRET. Run every 30 minutes via cron or Vercel Cron.
*/
export async function GET(request: Request) {
const deny = verifyCronSecret(request);
if (deny) return deny;
try {
const report = await detectAuthAnomalies();
if (report.anomalies.length > 0) {
const adminUsers = await prisma.user.findMany({
where: { systemRole: "ADMIN" },
select: { id: true },
});
if (adminUsers.length > 0) {
const summary = report.anomalies
.map((a) =>
a.entityId
? `${a.type}: ${a.count} failures for entity ${a.entityId}`
: `${a.type}: ${a.count} total failures`,
)
.join("; ");
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await createNotificationsForUsers({
db: prisma as any,
userIds: adminUsers.map((u) => u.id),
type: "SYSTEM_ALERT",
title: `Auth Anomaly Detected (${report.anomalies.length} signal${report.anomalies.length > 1 ? "s" : ""})`,
body: `${summary}. Window: ${report.windowStartedAt} ${report.windowEndedAt}. Review audit logs at /admin/settings.`,
category: "system",
priority: "CRITICAL",
link: "/admin/settings",
});
logger.warn(
{ anomalies: report.anomalies, window: { start: report.windowStartedAt, end: report.windowEndedAt } },
"Auth anomaly cron: anomalies detected and admins notified",
);
}
}
return NextResponse.json({
ok: true,
...report,
});
} catch (error) {
logger.error({ error, route: "/api/cron/auth-anomaly-check" }, "Auth anomaly cron failed");
return NextResponse.json(
{ ok: false, error: "Internal error" },
{ status: 500 },
);
}
}
@@ -0,0 +1,117 @@
/**
* Unit tests for GET /api/reports/allocations — A01 role-check enforcement.
*
* Heavy dependencies (Prisma, PDF renderer, XLSX builder) are mocked so the
* test focuses purely on authentication and authorisation behaviour.
*/
import { describe, expect, it, vi } from "vitest";
// ─── auth mock ────────────────────────────────────────────────────────────────
const authMock = vi.hoisted(() => vi.fn());
vi.mock("~/server/auth.js", () => ({ auth: authMock }));
// ─── heavy dep stubs ─────────────────────────────────────────────────────────
vi.mock("@capakraken/db", () => ({
prisma: {
demandRequirement: { findMany: vi.fn().mockResolvedValue([]) },
assignment: { findMany: vi.fn().mockResolvedValue([]) },
user: { findMany: vi.fn().mockResolvedValue([]) },
},
}));
vi.mock("@capakraken/application", () => ({
buildSplitAllocationReadModel: vi.fn().mockReturnValue({ assignments: [] }),
}));
vi.mock("@capakraken/api", () => ({
anonymizeResource: vi.fn((r: unknown) => r),
getAnonymizationDirectory: vi.fn().mockResolvedValue({}),
}));
vi.mock("@react-pdf/renderer", () => ({
renderToBuffer: vi.fn().mockResolvedValue(Buffer.from("PDF")),
}));
vi.mock("react", async (importOriginal) => {
const actual = await importOriginal<typeof import("react")>();
return { ...actual, createElement: vi.fn().mockReturnValue(null) };
});
vi.mock("~/lib/workbook-export.js", () => ({
createWorkbookArrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)),
}));
vi.mock("~/components/reports/AllocationReport.js", () => ({
AllocationReport: () => null,
}));
// ─── import route after mocks ─────────────────────────────────────────────────
import { GET } from "./route.js";
function makeRequest(url = "http://localhost/api/reports/allocations") {
return new Request(url);
}
// ─── tests ───────────────────────────────────────────────────────────────────
describe("GET /api/reports/allocations — authentication", () => {
it("returns 401 when no session exists", async () => {
authMock.mockResolvedValue(null);
const res = await GET(makeRequest());
expect(res.status).toBe(401);
});
it("returns 401 when session has no user", async () => {
authMock.mockResolvedValue({ user: null });
const res = await GET(makeRequest());
expect(res.status).toBe(401);
});
});
describe("GET /api/reports/allocations — authorisation (A01)", () => {
it("returns 403 for USER role", async () => {
authMock.mockResolvedValue({ user: { email: "user@example.com", role: "USER" } });
const res = await GET(makeRequest());
expect(res.status).toBe(403);
});
it("returns 403 for VIEWER role", async () => {
authMock.mockResolvedValue({ user: { email: "viewer@example.com", role: "VIEWER" } });
const res = await GET(makeRequest());
expect(res.status).toBe(403);
});
it("returns 403 when role is absent from session", async () => {
authMock.mockResolvedValue({ user: { email: "noRole@example.com" } });
const res = await GET(makeRequest());
expect(res.status).toBe(403);
});
it("returns 200 for ADMIN role (PDF)", async () => {
authMock.mockResolvedValue({ user: { email: "admin@example.com", role: "ADMIN" } });
const res = await GET(makeRequest());
expect(res.status).toBe(200);
expect(res.headers.get("Content-Type")).toContain("pdf");
});
it("returns 200 for MANAGER role (PDF)", async () => {
authMock.mockResolvedValue({ user: { email: "mgr@example.com", role: "MANAGER" } });
const res = await GET(makeRequest());
expect(res.status).toBe(200);
});
it("returns 200 for CONTROLLER role (PDF)", async () => {
authMock.mockResolvedValue({ user: { email: "ctrl@example.com", role: "CONTROLLER" } });
const res = await GET(makeRequest());
expect(res.status).toBe(200);
});
it("returns 200 for ADMIN role with xlsx format", async () => {
authMock.mockResolvedValue({ user: { email: "admin@example.com", role: "ADMIN" } });
const res = await GET(makeRequest("http://localhost/api/reports/allocations?format=xlsx"));
expect(res.status).toBe(200);
expect(res.headers.get("Content-Type")).toContain("spreadsheetml");
});
});
@@ -9,12 +9,19 @@ import { auth } from "~/server/auth.js";
import { AllocationReport } from "~/components/reports/AllocationReport.js";
import { createWorkbookArrayBuffer } from "~/lib/workbook-export.js";
const ALLOWED_ROLES = new Set(["ADMIN", "MANAGER", "CONTROLLER"]);
export async function GET(request: Request) {
const session = await auth();
if (!session?.user) {
return new NextResponse("Unauthorized", { status: 401 });
}
const userRole = (session.user as { role?: string }).role;
if (!userRole || !ALLOWED_ROLES.has(userRole)) {
return new NextResponse("Forbidden", { status: 403 });
}
const { searchParams } = new URL(request.url);
const startDate = searchParams.get("startDate") ? new Date(searchParams.get("startDate")!) : new Date();
const endDate = searchParams.get("endDate") ? new Date(searchParams.get("endDate")!) : new Date(Date.now() + 90 * 24 * 60 * 60 * 1000);
+5
View File
@@ -28,6 +28,11 @@ export default function SignInPage() {
if (result?.error) {
// Auth.js wraps authorize() errors in the error field
if (result.error.includes("MFA_REQUIRED_SETUP")) {
// User's role requires MFA but it hasn't been set up yet — redirect to setup
router.push("/account/security?mfa_required=1");
return;
}
if (result.error.includes("MFA_REQUIRED")) {
setMfaRequired(true);
setLoading(false);
@@ -0,0 +1,64 @@
/**
* MfaPromptBanner security contract tests.
*
* Verifies structural properties of MfaPromptBanner.tsx via source analysis:
* - Snooze is user-scoped (userId in the localStorage key)
* - Default snooze is at least 1 day
* - Banner always links to /account/security
* - Component does not persist sensitive data (MFA secret or token) to localStorage
*
* The vitest environment for apps/web is "node" so source analysis is the
* correct testing approach here (same pattern as MfaSetup.test.ts).
*/
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
const SOURCE_PATH = resolve(__dirname, "./MfaPromptBanner.tsx");
const source = readFileSync(SOURCE_PATH, "utf-8");
describe("MfaPromptBanner — localStorage user-scoping", () => {
it("includes userId in the localStorage key to prevent cross-user snooze leakage", () => {
// The key must interpolate userId, e.g. `${SNOOZE_KEY}_${userId}`
expect(source).toMatch(/\$\{.*userId\}/);
});
it("persists snooze timestamp as a number, not session/token data", () => {
// localStorage.setItem should write a numeric timestamp (Date.now() + offset)
expect(source).toMatch(/Date\.now\(\)/);
});
});
describe("MfaPromptBanner — snooze duration", () => {
it("snoozed for at least 1 day (86 400 000 ms)", () => {
// Extract the SNOOZE_DAYS constant value from the source
const match = source.match(/SNOOZE_DAYS\s*=\s*(\d+)/);
expect(match).not.toBeNull();
const days = Number(match![1]);
expect(days).toBeGreaterThanOrEqual(1);
});
});
describe("MfaPromptBanner — navigation target", () => {
it("links to /account/security for MFA setup", () => {
expect(source).toMatch(/\/account\/security/);
});
});
describe("MfaPromptBanner — no sensitive data in localStorage", () => {
it("does not store TOTP secret in localStorage", () => {
expect(source).not.toMatch(/localStorage.*secret/i);
expect(source).not.toMatch(/localStorage.*totp/i);
});
it("does not store authentication tokens in localStorage", () => {
expect(source).not.toMatch(/localStorage.*token/i);
});
});
describe("MfaPromptBanner — accessibility", () => {
it("has a role=alert or aria-label to be announced by screen readers", () => {
expect(source).toMatch(/role=["']alert["']|aria-label/);
});
});
@@ -0,0 +1,73 @@
"use client";
import Link from "next/link";
import { useEffect, useState } from "react";
const SNOOZE_KEY = "capakraken_mfa_prompt_snoozed_until";
const SNOOZE_DAYS = 7;
/**
* Banner shown to ADMIN / MANAGER users who have not yet enabled TOTP MFA.
* The user can dismiss it for SNOOZE_DAYS days ("Remind me later").
*
* Props are resolved server-side in the layout, so no client-side DB fetch
* is needed here.
*/
export function MfaPromptBanner({ userId }: { userId: string }) {
const [visible, setVisible] = useState(false);
useEffect(() => {
try {
const raw = localStorage.getItem(`${SNOOZE_KEY}_${userId}`);
if (raw) {
const until = Number(raw);
if (!isNaN(until) && Date.now() < until) {
return; // still snoozed
}
}
} catch {
// localStorage unavailable (SSR guard — should not happen in a client component)
}
setVisible(true);
}, [userId]);
function snooze() {
try {
const until = Date.now() + SNOOZE_DAYS * 24 * 60 * 60 * 1000;
localStorage.setItem(`${SNOOZE_KEY}_${userId}`, String(until));
} catch {
// ignore
}
setVisible(false);
}
if (!visible) return null;
return (
<div
role="alert"
aria-label="MFA setup recommendation"
className="flex items-center justify-between gap-4 bg-amber-50 px-4 py-2.5 text-sm text-amber-900 dark:bg-amber-900/20 dark:text-amber-200 border-b border-amber-200 dark:border-amber-700/50"
>
<span>
<strong className="font-semibold">Protect your account:</strong>{" "}
Your role has elevated permissions. We recommend enabling multi-factor authentication (MFA).
</span>
<div className="flex shrink-0 items-center gap-2">
<Link
href="/account/security"
className="rounded-md bg-amber-600 px-3 py-1 text-xs font-semibold text-white hover:bg-amber-700 focus-visible:outline focus-visible:outline-2 focus-visible:outline-amber-600 dark:bg-amber-500 dark:hover:bg-amber-400"
>
Set up MFA
</Link>
<button
type="button"
onClick={snooze}
className="rounded-md px-2 py-1 text-xs text-amber-700 hover:bg-amber-100 dark:text-amber-300 dark:hover:bg-amber-800/50"
>
Remind me later
</button>
</div>
</div>
);
}
+13
View File
@@ -118,6 +118,19 @@ const authConfig = {
}
}
// MFA enforcement: if the user's role is in requireMfaForRoles but they
// haven't set up TOTP yet, block login and signal setup requirement.
if (!user.totpEnabled) {
const settings = await prisma.systemSettings.findUnique({
where: { id: "singleton" },
select: { requireMfaForRoles: true },
});
const requireMfaForRoles = (settings?.requireMfaForRoles as string[] | null) ?? [];
if (requireMfaForRoles.includes(user.systemRole)) {
throw new Error("MFA_REQUIRED_SETUP:" + user.id);
}
}
// Track last login time
await prisma.user.update({
where: { id: user.id },