feat: enforce admin 2FA, step-up auth, stronger password policy

Implements OWASP audit recommendations P1-P3:

P1 - Two-factor authentication (TOTP) mandatory for admins:
- better-auth twoFactor plugin; new two_factor table + user flag
  (migration 0010, MUST run before deploying the app)
- requireAdmin throws TWO_FACTOR_REQUIRED without a finished setup;
  pages redirect to the new /zwei-faktor wizard which uses a weak
  guard (allowWithoutTwoFactor) so admins can never lock themselves
  out. Wizard lives outside /admin to avoid layout redirect loops.
- login flow handles twoFactorRedirect and asks for the TOTP code;
  backup codes are shown once during enablement

P2 - Step-up for destructive operations (ASVS 2.5.4):
- hardDeleteEditorialAction and resetUsageDataAction reject sessions
  older than 15 minutes (SESSION_STALE) with actionable German
  messages instead of throwing opaque digests

P3 - Password policy (NIST 800-63B):
- minimum length raised from 8 to 12 plus common-password denylist,
  enforced for registration AND reset/change via a before-hook
This commit is contained in:
Leon Tonhäuser committed 2026-08-25 02:30:58 +02:00
1 parent 9308b46d84
commit 0d939593c8
20 files changed
+2613 -29

No files matched your search

+2 -1
View File
@@ -5,8 +5,9 @@ import { cache } from "react";
import { headers } from "next/headers";
import { requirePageAccess } from "@/modules/auth/page-access";
import { requireAdmin } from "@/modules/auth/principal";
import { requireAdmin, requireAdminForSetup } from "@/modules/auth/principal";
/** Strict guard: valid admin session with finished two-factor setup. */
export const requireAdminPage = cache(async () =>
requirePageAccess(async () => requireAdmin(new Headers(await headers()))),
);
+50 -8
View File
@@ -7,7 +7,7 @@ import { eq } from "drizzle-orm";
import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema";
import { requireAdmin } from "@/modules/auth/principal";
import { requireAdmin, PrincipalAuthorizationError, DESTRUCTIVE_ACTION_MAX_SESSION_AGE_SECONDS } from "@/modules/auth/principal";
import { editorialService, EditorialServiceError } from "@/modules/editorials/service";
// Returned to the client form so failures surface as inline German text
@@ -65,23 +65,65 @@ export async function unarchiveEditorialAction(editorialId: string): Promise<voi
revalidatePath("/admin/redaktionen");
}
export async function hardDeleteEditorialAction(editorialId: string): Promise<void> {
await requireAdmin(new Headers(await headers()));
await editorialService.hardDeleteEditorial(editorialId);
export type ResetUsageResult = { ok: boolean; message: string };
/**
* Step-up guard for irreversible operations (OWASP ASVS 2.5.4): the session
* must be recent, otherwise the admin re-authenticates first.
*/
async function freshAdminPrincipal(): Promise<
Awaited<ReturnType<typeof requireAdmin>> | ResetUsageResult
> {
try {
return await requireAdmin(new Headers(await headers()), {
maxSessionAgeSeconds: DESTRUCTIVE_ACTION_MAX_SESSION_AGE_SECONDS,
});
} catch (error) {
if (error instanceof PrincipalAuthorizationError) {
return { ok: false, message: adminGuardMessage(error.code) };
}
throw error;
}
}
function adminGuardMessage(code: PrincipalAuthorizationError["code"]): string {
switch (code) {
case "SESSION_STALE":
return "Aus Sicherheitsgründen ist Ihre Sitzung zu alt für diese Aktion. Bitte melden Sie sich erneut an und wiederholen Sie den Schritt.";
case "TWO_FACTOR_REQUIRED":
return "Für diese Aktion ist Zwei-Faktor-Authentifizierung erforderlich.";
default:
return "Die Aktion ist fehlgeschlagen.";
}
}
function isPrincipal(result: unknown): result is Awaited<ReturnType<typeof requireAdmin>> {
return typeof result === "object" && result !== null && "userId" in result;
}
export async function hardDeleteEditorialAction(editorialId: string): Promise<ResetUsageResult> {
const safeEditorialId = requiredId(editorialId);
const principal = await freshAdminPrincipal();
if (!isPrincipal(principal)) {
return principal;
}
await editorialService.hardDeleteEditorial(safeEditorialId);
revalidatePath("/admin/redaktionen");
redirect("/admin/redaktionen");
}
export type ResetUsageResult = { ok: boolean; message: string };
export async function resetUsageDataAction(editorialId: string): Promise<ResetUsageResult> {
const admin = await requireAdmin(new Headers(await headers()));
const safeEditorialId = requiredId(editorialId);
const principal = await freshAdminPrincipal();
if (!isPrincipal(principal)) {
return principal;
}
try {
const result = await editorialService.resetUsageData({
editorialId: safeEditorialId,
adminUserId: admin.userId,
adminUserId: principal.userId,
});
revalidatePath(`/admin/redaktionen/${safeEditorialId}`);
revalidatePath("/admin/redaktionen");
+17
View File
@@ -0,0 +1,17 @@
import "server-only";
import { cache } from "react";
import { headers } from "next/headers";
import { requirePageAccess } from "@/modules/auth/page-access";
import { requireAdminForSetup } from "@/modules/auth/principal";
/**
* Weak guard for the two-factor wizard only: an authenticated ADMIN without
* a finished TOTP setup must be able to reach /zwei-faktor. Everything else
* in the portal uses requireAdminPage / requireAdmin (strict).
*/
export const requireTwoFactorSetupPage = cache(async () =>
requirePageAccess(async () => requireAdminForSetup(new Headers(await headers()))),
);
+33
View File
@@ -0,0 +1,33 @@
import { headers } from "next/headers";
import { PageHeader } from "@/components/ui/page-header";
import { auth } from "@/modules/auth/auth";
import { requireTwoFactorSetupPage } from "./access";
import { TwoFactorWizard } from "./wizard";
export default async function TwoFactorSetupPage() {
await requireTwoFactorSetupPage();
const session = await auth.api.getSession({ headers: new Headers(await headers()) });
const enabled =
(session?.user as { twoFactorEnabled?: unknown } | undefined)?.twoFactorEnabled === true;
return (
<div className="space-y-8 max-w-2xl mx-auto px-4 py-10 animate-in fade-in slide-in-from-bottom-4 duration-500">
<PageHeader kicker="Sicherheit" title="Zwei-Faktor-Authentifizierung" />
{enabled ? (
<p className="text-sm text-muted-foreground">
Zwei-Faktor ist aktiviert. Administrator-Bereiche erfordern bei der Anmeldung zusätzlich
einen Code Ihrer Authenticator-App.
</p>
) : (
<div className="bg-primary/10 border border-primary/30 p-4 rounded-md text-sm" role="status">
Für Administrator-Konten ist die Zwei-Faktor-Authentifizierung Pflicht. Richten Sie sie
jetzt ein, um auf den Admin-Bereich zuzugreifen.
</div>
)}
<TwoFactorWizard initiallyEnabled={enabled} />
</div>
);
}
+207
View File
@@ -0,0 +1,207 @@
"use client";
import { type FormEvent, useState } from "react";
import { Button } from "@/components/ui/button";
import { authClient } from "@/modules/auth/client";
type WizardStep = "password" | "scan" | "done";
export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolean }) {
const [enabled, setEnabled] = useState(initiallyEnabled);
const [step, setStep] = useState<WizardStep>("password");
const [secret, setSecret] = useState<string>();
const [backupCodes, setBackupCodes] = useState<string[]>([]);
const [error, setError] = useState<string>();
const [pending, setPending] = useState(false);
async function startSetup(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setPending(true);
setError(undefined);
const password = readPassword(event.currentTarget);
try {
const result = await authClient.twoFactor.enable({ password });
if (result.error) {
setError(twoFactorErrorMessage(result.error.code));
return;
}
const uri = result.data?.totpURI;
setSecret(uri ? new URL(uri).searchParams.get("secret") ?? undefined : undefined);
setBackupCodes(result.data?.backupCodes ?? []);
setStep("scan");
} catch {
setError("Das Einrichten ist fehlgeschlagen. Bitte versuchen Sie es erneut.");
} finally {
setPending(false);
}
}
async function confirmCode(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setPending(true);
setError(undefined);
try {
const formData = new FormData(event.currentTarget);
const code = String(formData.get("code") ?? "").replace(/\s+/g, "");
const result = await authClient.twoFactor.verifyTotp({ code });
if (result.error) {
setError("Der Code ist ungültig. Bitte prüfen Sie Ihre Authenticator-App.");
return;
}
setEnabled(true);
setStep("done");
} catch {
setError("Der Code konnte nicht geprüft werden. Bitte versuchen Sie es erneut.");
} finally {
setPending(false);
}
}
async function disable(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setPending(true);
setError(undefined);
try {
const password = readPassword(event.currentTarget);
const result = await authClient.twoFactor.disable({ password });
if (result.error) {
setError("Das Deaktivieren ist fehlgeschlagen. Passwort prüfen und erneut versuchen.");
return;
}
setEnabled(false);
setStep("password");
} catch {
setError("Das Deaktivieren ist fehlgeschlagen. Bitte versuchen Sie es erneut.");
} finally {
setPending(false);
}
}
return (
<div className="space-y-6">
{!enabled && step === "password" && (
<form onSubmit={startSetup} className="space-y-4">
<label className="block text-sm font-medium">
Passwort bestätigen, um die Einrichtung zu starten
<input
autoComplete="current-password"
className="mt-1 block w-full"
name="password"
required
type="password"
/>
</label>
<Button disabled={pending} type="submit">
{pending ? "Wird vorbereitet …" : "Einrichtung starten"}
</Button>
</form>
)}
{step === "scan" && secret && (
<div className="space-y-4">
<ol className="text-sm space-y-2 list-decimal list-inside text-muted-foreground">
<li>Öffnen Sie Ihre Authenticator-App (z. B. Google Authenticator, Aegis, 1Password).</li>
<li>
Fügen Sie einen neuen Eintrag hinzu und geben Sie diesen Schlüssel manuell ein:
<code className="block mt-2 rounded-md bg-muted p-3 font-mono text-base tracking-widest select-all break-all">
{secret}
</code>
<span className="text-xs mt-1 block">
Typ: zeitbasiert (TOTP) · 6 Ziffern · alle 30 Sekunden.
</span>
</li>
<li>Bestätigen Sie mit dem aktuell angezeigten Code.</li>
</ol>
{backupCodes.length > 0 && (
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 p-4 text-sm">
<p className="font-medium mb-2">Einmal-Codes (ersatzweise gültig, je einmal nutzbar)</p>
<div className="grid grid-cols-2 sm:grid-cols-3 gap-1 font-mono text-xs">
{backupCodes.map((code) => (
<span key={code}>{code}</span>
))}
</div>
<p className="text-xs mt-2 text-muted-foreground">
Bewahren Sie diese Codes sicher auf – sie werden nur jetzt angezeigt.
</p>
</div>
)}
<form onSubmit={confirmCode} className="space-y-4">
<label className="block text-sm font-medium">
Code aus der App
<input
autoComplete="one-time-code"
className="mt-1 block w-full max-w-[12rem]"
inputMode="numeric"
maxLength={6}
name="code"
pattern="[0-9]*"
required
type="text"
/>
</label>
<Button disabled={pending} type="submit">
{pending ? "Code wird geprüft …" : "Aktivieren"}
</Button>
</form>
</div>
)}
{step === "done" && (
<div className="rounded-md border border-emerald-600/40 bg-emerald-600/10 p-4 text-sm" role="status">
Zwei-Faktor-Authentifizierung ist aktiviert. Sie können sich ab jetzt nur noch mit
Passwort und Authenticator-Code anmelden.
<a className="primary-action inline-block mt-4" href="/admin">
Weiter zum Admin-Bereich
</a>
</div>
)}
{enabled && step !== "done" && (
<form onSubmit={disable} className="space-y-4 border-t pt-6">
<p className="text-sm text-muted-foreground">
Zwei-Faktor ist aktiviert. Zum Deaktivieren Ihr Passwort eingeben – danach muss die
Einrichtung neu erfolgen, bevor Admin-Bereiche wieder zugänglich sind.
</p>
<input
autoComplete="current-password"
name="password"
placeholder="Passwort"
required
type="password"
/>
<Button variant="outline" disabled={pending} type="submit">
{pending ? "Wird deaktiviert …" : "Zwei-Faktor deaktivieren"}
</Button>
</form>
)}
{error && (
<p className="field-error" role="alert">
{error}
</p>
)}
</div>
);
}
function readPassword(form: HTMLFormElement): string {
const value = new FormData(form).get("password");
return typeof value === "string" ? value : "";
}
function twoFactorErrorMessage(code: string | undefined): string {
switch (code) {
case "INVALID_PASSWORD":
return "Das Passwort ist nicht korrekt.";
case "TWO_FACTOR_ALREADY_ENABLED":
return "Zwei-Faktor ist für dieses Konto bereits aktiviert.";
default:
return "Das Einrichten ist fehlgeschlagen. Bitte versuchen Sie es erneut.";
}
}
+15
View File
@@ -10,10 +10,25 @@ export const users = pgTable("user", {
emailVerified: boolean("email_verified").notNull().default(false),
image: text("image"),
role: portalRole("role").notNull().default("EDITORIAL"),
// Better Auth two-factor plugin; secrets live in the two_factor table.
twoFactorEnabled: boolean("two_factor_enabled").notNull().default(false),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
});
// Better Auth two-factor plugin model ("twoFactor"). `secret` and
// `backupCodes` are stored encrypted by Better Auth (derived from
// BETTER_AUTH_SECRET).
export const twoFactors = pgTable("two_factor", {
id: uuid("id").defaultRandom().primaryKey(),
userId: uuid("user_id")
.notNull()
.unique()
.references(() => users.id, { onDelete: "restrict" }),
secret: text("secret").notNull(),
backupCodes: text("backup_codes"),
});
export const accounts = pgTable("account", {
id: uuid("id").defaultRandom().primaryKey(),
accountId: text("account_id").notNull(),
+52 -1
View File
@@ -1,12 +1,19 @@
import "server-only";
import { APIError } from "better-auth";
import { createAuthMiddleware } from "better-auth/api";
import { drizzleAdapter } from "@better-auth/drizzle-adapter";
import { betterAuth, type BetterAuthOptions } from "better-auth";
import { twoFactor } from "better-auth/plugins";
import { env } from "@/config/env";
import { db } from "@/db/client";
import { accounts, sessions, users, verifications } from "@/db/schema";
import { accounts, sessions, twoFactors, users, verifications } from "@/db/schema";
import { mailer } from "@/modules/mail/mailer";
import {
validatePasswordPolicy,
MIN_PASSWORD_LENGTH,
} from "@/modules/security/password-policy";
import { consumeRateLimit, registrationPolicy } from "@/modules/security/rate-limit";
import {
enforceRateLimit,
@@ -74,12 +81,29 @@ export function createPortalAuth({
defaultValue: "EDITORIAL",
input: false,
},
twoFactorEnabled: {
type: "boolean",
required: false,
defaultValue: false,
input: false,
},
},
},
plugins: [
twoFactor({
// TOTP + backup codes only: without `otpOptions.sendOTP` no OTP-e-mail
// surface exists, and trust-device stays off to keep the attack area
// small. Backup codes stay encrypted (plugin default).
}),
],
hooks: {
before: createPasswordPolicyHook(),
},
emailAndPassword: {
enabled: true,
requireEmailVerification: true,
autoSignIn: false,
minPasswordLength: MIN_PASSWORD_LENGTH,
resetPasswordTokenExpiresIn: 60 * 60,
revokeSessionsOnPasswordReset: true,
async sendResetPassword({ user, url }) {
@@ -129,6 +153,32 @@ export function createPortalAuth({
return { auth, registrationService };
}
export function createPasswordPolicyHook() {
// Applies the shared policy to password-reset and change-password flows,
// which bypass the registration validation. Registration is covered by
// validateRegistration(); sign-up additionally enforces Better Auth's
// minPasswordLength.
return createAuthMiddleware(async (ctx) => {
if (ctx.path !== "/reset-password" && ctx.path !== "/change-password") {
return;
}
const body = (ctx.body ?? {}) as { newPassword?: unknown; password?: unknown };
const candidate =
typeof body.newPassword === "string"
? body.newPassword
: typeof body.password === "string"
? body.password
: undefined;
if (candidate === undefined) {
return;
}
const result = validatePasswordPolicy(candidate);
if (!result.ok) {
throw new APIError("BAD_REQUEST", { message: result.reason });
}
});
}
const registrationRepository = createEditorialRegistrationRepository(db);
const portalAuth = createPortalAuth({
database: drizzleAdapter(db, {
@@ -138,6 +188,7 @@ const portalAuth = createPortalAuth({
account: accounts,
session: sessions,
verification: verifications,
twoFactor: twoFactors,
},
}),
mailerService: mailer,
+4 -1
View File
@@ -1,5 +1,8 @@
"use client";
import { createAuthClient } from "better-auth/react";
import { twoFactorClient } from "better-auth/client/plugins";
export const authClient = createAuthClient();
export const authClient = createAuthClient({
plugins: [twoFactorClient()],
});
+10 -5
View File
@@ -10,11 +10,16 @@ export async function requirePageAccess<T>(
try {
return await loadPrincipal();
} catch (error) {
if (
error instanceof PrincipalAuthorizationError &&
error.code === "AUTHENTICATION_REQUIRED"
) {
redirect("/anmelden");
if (error instanceof PrincipalAuthorizationError) {
if (error.code === "AUTHENTICATION_REQUIRED") {
redirect("/anmelden");
}
// Admins without a finished two-factor setup are routed to the wizard
// instead of an error page (the wizard itself uses the weak guard and
// lives outside the guarded /admin layout to avoid a redirect loop).
if (error.code === "TWO_FACTOR_REQUIRED") {
redirect("/zwei-faktor");
}
}
throw error;
}
+47
View File
@@ -4,6 +4,7 @@ import { createPrincipalGuard } from "./principal";
const editorialSession = {
user: { id: "editorial-user", role: "EDITORIAL" as const },
session: { createdAt: new Date() },
};
test("rejects a suspended editorial after session authentication", async () => {
@@ -44,3 +45,49 @@ test("rejects non-admin users from the admin guard", async () => {
await expect(guard.requireAdmin(new Headers())).rejects.toMatchObject({ code: "ADMIN_REQUIRED" });
});
test("rejects an admin session without finished two-factor setup", async () => {
const guard = createPrincipalGuard({
getSession: async () => ({
user: { id: "admin-user", role: "ADMIN" as const, twoFactorEnabled: false },
session: { createdAt: new Date() },
}),
getAccount: async () => null,
});
await expect(guard.requireAdmin(new Headers())).rejects.toMatchObject({
code: "TWO_FACTOR_REQUIRED",
});
// The setup wizard uses the weak guard so admins can configure TOTP.
await expect(
guard.requireAdmin(new Headers(), { allowWithoutTwoFactor: true }),
).resolves.toMatchObject({ userId: "admin-user" });
});
test("accepts an admin session with two-factor enabled", async () => {
const guard = createPrincipalGuard({
getSession: async () => ({
user: { id: "admin-user", role: "ADMIN" as const, twoFactorEnabled: true },
session: { createdAt: new Date() },
}),
getAccount: async () => null,
});
await expect(guard.requireAdmin(new Headers())).resolves.toMatchObject({ userId: "admin-user" });
});
test("rejects stale sessions for destructive operations (step-up)", async () => {
const guard = createPrincipalGuard({
getSession: async () => ({
user: { id: "admin-user", role: "ADMIN" as const, twoFactorEnabled: true },
session: { createdAt: new Date(Date.now() - 30 * 60 * 1000) },
}),
getAccount: async () => null,
});
await expect(
guard.requireAdmin(new Headers(), { maxSessionAgeSeconds: 15 * 60 }),
).rejects.toMatchObject({ code: "SESSION_STALE" });
// Without the freshness requirement the same session is fine.
await expect(guard.requireAdmin(new Headers())).resolves.toMatchObject({ userId: "admin-user" });
});
+46 -3
View File
@@ -16,9 +16,15 @@ export type PortalPrincipal = {
status: AccountStatus;
};
type Session = { user: { id: string; role: "ADMIN" | "EDITORIAL" } } | null;
type Session = {
user: { id: string; role: "ADMIN" | "EDITORIAL"; twoFactorEnabled?: boolean };
session: { createdAt?: Date };
} | null;
type EditorialAccount = { id: string; status: AccountStatus } | null;
/** Sessions older than this must re-authenticate before destructive actions. */
export const DESTRUCTIVE_ACTION_MAX_SESSION_AGE_SECONDS = 15 * 60;
export type PrincipalGuardDependencies = {
getSession(requestHeaders: Headers): Promise<Session>;
getAccount(userId: string): Promise<EditorialAccount>;
@@ -31,6 +37,8 @@ export class PrincipalAuthorizationError extends Error {
readonly code:
| "AUTHENTICATION_REQUIRED"
| "ADMIN_REQUIRED"
| "TWO_FACTOR_REQUIRED"
| "SESSION_STALE"
| "EDITORIAL_ACCOUNT_NOT_FOUND"
| "ACCOUNT_PENDING_EMAIL"
| "ACCOUNT_PENDING_APPROVAL"
@@ -51,11 +59,30 @@ export function createPrincipalGuard({ getSession, getAccount }: PrincipalGuardD
}
return {
async requireAdmin(requestHeaders: Headers): Promise<PortalPrincipal> {
/**
* Admin guard. Enforces two-factor authentication once configured
* (setup stays reachable via requireAdminForSetup to avoid lockout).
* Pass `maxSessionAgeSeconds` for step-up semantics on destructive
* operations (OWASP ASVS 2.5.4): older sessions are rejected.
*/
async requireAdmin(
requestHeaders: Headers,
options: { maxSessionAgeSeconds?: number; allowWithoutTwoFactor?: boolean } = {},
): Promise<PortalPrincipal> {
const session = await getAuthenticatedSession(requestHeaders);
if (session.user.role !== "ADMIN") {
throw new PrincipalAuthorizationError("ADMIN_REQUIRED");
}
if (!options.allowWithoutTwoFactor && !session.user.twoFactorEnabled) {
throw new PrincipalAuthorizationError("TWO_FACTOR_REQUIRED");
}
if (options.maxSessionAgeSeconds !== undefined && session.session.createdAt) {
const ageSeconds =
(Date.now() - new Date(session.session.createdAt).getTime()) / 1000;
if (ageSeconds > options.maxSessionAgeSeconds) {
throw new PrincipalAuthorizationError("SESSION_STALE");
}
}
return {
userId: session.user.id,
@@ -114,7 +141,15 @@ export const principalGuard = createPrincipalGuard({
if (role !== "ADMIN" && role !== "EDITORIAL") {
return null;
}
return { user: { id: session.user.id, role } };
return {
user: {
id: session.user.id,
role,
twoFactorEnabled:
(session.user as { twoFactorEnabled?: unknown }).twoFactorEnabled === true,
},
session: { createdAt: session.session.createdAt },
};
},
async getAccount(userId) {
@@ -129,3 +164,11 @@ export const principalGuard = createPrincipalGuard({
export const requireAdmin = principalGuard.requireAdmin;
export const requireActiveEditorial = principalGuard.requireActiveEditorial;
/**
* Weak admin guard for the two-factor setup surface only: an authenticated
* ADMIN without a finished TOTP setup must be able to reach the wizard.
* Everything else uses requireAdmin (which enforces two-factor).
*/
export const requireAdminForSetup: typeof principalGuard.requireAdmin = (headers, options) =>
principalGuard.requireAdmin(headers, { ...options, allowWithoutTwoFactor: true });
+51 -2
View File
@@ -67,7 +67,7 @@ export function RegistrationForm({
<FieldError message={state.errors?.email} />
<label>
Passwort
<input autoComplete="new-password" minLength={8} name="password" required type="password" />
<input autoComplete="new-password" minLength={12} name="password" required type="password" />
</label>
<FieldError message={state.errors?.password} />
<label>
@@ -146,6 +146,7 @@ export function RegistrationForm({
export function LoginForm() {
const [error, setError] = useState<string>();
const [pending, setPending] = useState(false);
const [awaitingTwoFactor, setAwaitingTwoFactor] = useState(false);
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
@@ -153,6 +154,20 @@ export function LoginForm() {
setError(undefined);
const formData = new FormData(event.currentTarget);
if (awaitingTwoFactor) {
const result = await authClient.twoFactor.verifyTotp({
code: readText(formData, "totp").replace(/\s+/g, ""),
});
if (result.error) {
setError("Der Code ist ungültig oder abgelaufen. Bitte erneut versuchen.");
setPending(false);
return;
}
window.location.assign("/");
return;
}
const result = await authClient.signIn.email({
email: readText(formData, "email").trim().toLowerCase(),
password: readText(formData, "password"),
@@ -165,9 +180,43 @@ export function LoginForm() {
return;
}
// Better Auth returns this flag instead of a session when TOTP is pending
// for the user; the typed SDK omits it, hence the narrow cast.
if ((result.data as { twoFactorRedirect?: boolean } | undefined)?.twoFactorRedirect) {
setAwaitingTwoFactor(true);
setPending(false);
return;
}
window.location.assign(result.data?.url ?? "/");
}
if (awaitingTwoFactor) {
return (
<form className="account-form" onSubmit={submit}>
<p className="form-note">
Geben Sie den aktuellen 6-stelligen Code aus Ihrer Authenticator-App ein.
</p>
<label>
Zwei-Faktor-Code
<input
autoComplete="one-time-code"
inputMode="numeric"
maxLength={6}
name="totp"
pattern="[0-9]*"
required
type="text"
/>
</label>
<FieldError message={error} />
<button className="primary-action" disabled={pending} type="submit">
{pending ? "Code wird geprüft …" : "Anmelden"}
</button>
</form>
);
}
return (
<form className="account-form" onSubmit={submit}>
<label>
@@ -270,7 +319,7 @@ export function PasswordResetForm({ token }: { token?: string }) {
<form className="account-form" onSubmit={submit}>
<label>
Neues Passwort
<input autoComplete="new-password" minLength={8} name="password" required type="password" />
<input autoComplete="new-password" minLength={12} name="password" required type="password" />
</label>
<FieldError message={error} />
<button className="primary-action" disabled={pending} type="submit">
+4 -5
View File
@@ -14,6 +14,7 @@ import {
verifications,
} from "@/db/schema";
import type * as schema from "@/db/schema";
import { validatePasswordPolicy } from "@/modules/security/password-policy";
export const CURRENT_TERMS_VERSION = "2026-08";
@@ -371,11 +372,9 @@ function validateRegistration(input: RegistrationInput): {
if (!password) {
throw new RegistrationValidationError("password", "Bitte geben Sie ein Passwort an.");
}
if (password.length < 8) {
throw new RegistrationValidationError(
"password",
"Bitte verwenden Sie ein Passwort mit mindestens acht Zeichen.",
);
const passwordPolicy = validatePasswordPolicy(password);
if (!passwordPolicy.ok) {
throw new RegistrationValidationError("password", passwordPolicy.reason);
}
const addressLine1 = trim(input.billingAddress?.addressLine1);
+15 -2
View File
@@ -16,12 +16,17 @@ export function DangerZone({ editorialId, editorialName }: DangerZoneProps) {
const [confirmText, setConfirmText] = useState("");
const [isPending, startTransition] = useTransition();
const [isDeleting, setIsDeleting] = useState(false);
const [result, setResult] = useState<{ ok: boolean; message: string } | null>(null);
const isConfirmed = confirmText === editorialName;
function handleArchive() {
if (!isConfirmed) return;
startTransition(async () => {
await archiveEditorialAction(editorialId);
try {
await archiveEditorialAction(editorialId);
} catch {
setResult({ ok: false, message: "Das Archivieren ist fehlgeschlagen." });
}
});
}
@@ -29,7 +34,10 @@ export function DangerZone({ editorialId, editorialName }: DangerZoneProps) {
if (!isConfirmed) return;
setIsDeleting(true);
startTransition(async () => {
await hardDeleteEditorialAction(editorialId);
const actionResult = await hardDeleteEditorialAction(editorialId);
// On success the action redirects; anything returned here is a failure.
setResult(actionResult);
setIsDeleting(false);
});
}
@@ -75,6 +83,11 @@ export function DangerZone({ editorialId, editorialName }: DangerZoneProps) {
{isDeleting ? "Wird gelöscht…" : "Endgültig löschen"}
</Button>
</div>
{result && !result.ok && (
<p className="text-sm text-destructive" role="alert">
{result.message}
</p>
)}
</CardContent>
</Card>
);
@@ -0,0 +1,27 @@
import { describe, expect, test } from "vitest";
import { MIN_PASSWORD_LENGTH, validatePasswordPolicy } from "./password-policy";
describe("validatePasswordPolicy", () => {
test(`requires at least ${MIN_PASSWORD_LENGTH} characters`, () => {
expect(validatePasswordPolicy("k".repeat(MIN_PASSWORD_LENGTH - 1))).toEqual({
ok: false,
reason: `Das Passwort muss mindestens ${MIN_PASSWORD_LENGTH} Zeichen lang sein.`,
});
expect(validatePasswordPolicy("k".repeat(MIN_PASSWORD_LENGTH))).toEqual({ ok: true });
});
test.each([
"passwort",
"Passwort1234",
"QWERTZUIOP",
"Password1",
"Sommer2025",
])("rejects the common password %s regardless of case", (candidate) => {
expect(validatePasswordPolicy(candidate).ok).toBe(false);
});
test("accepts a long unique password", () => {
expect(validatePasswordPolicy("korrekt-geratener-langer-satz-42")).toEqual({ ok: true });
});
});
+76
View File
@@ -0,0 +1,76 @@
import "server-only";
/**
* OWASP Authentication Cheat Sheet §Password Security: reject short passwords
* and passwords on common/breached lists. Length is additionally enforced by
* Better Auth (minPasswordLength) — this module adds the denylist layer and a
* single source of truth for all password-setting flows (registration,
* password reset via e-mail token, change password).
*/
export const MIN_PASSWORD_LENGTH = 12;
const COMMON_PASSWORDS = new Set([
"123456",
"123456789",
"12345678",
"1234567890",
"passwort",
"passwort123",
"passwort1234",
"password",
"password1",
"password123",
"qwerty",
"qwertz",
"qwertzuiop",
"123abc",
"abc123",
"letmein",
"welcome",
"admin",
"admin123",
"administrator",
"iloveyou",
"sunshine",
"princess",
"dragon",
"monkey",
"football",
"fussball",
"sommer2020",
"sommer2021",
"sommer2022",
"sommer2023",
"sommer2024",
"sommer2025",
"sommer2026",
"hallo",
"hallihallo",
"geheim",
"geheimnis",
"changeme",
"change-me",
"test",
"test123",
"test1234",
"asdasd",
"zaq12wsx",
]);
export type PasswordPolicyResult = { ok: true } | { ok: false; reason: string };
export function validatePasswordPolicy(password: string): PasswordPolicyResult {
if (!Number.isInteger(MIN_PASSWORD_LENGTH) || password.length < MIN_PASSWORD_LENGTH) {
return {
ok: false,
reason: `Das Passwort muss mindestens ${MIN_PASSWORD_LENGTH} Zeichen lang sein.`,
};
}
if (COMMON_PASSWORDS.has(password.trim().toLowerCase())) {
return {
ok: false,
reason: "Dieses Passwort ist zu häufig genutzt. Bitte wähle ein einzigartigeres Passwort.",
};
}
return { ok: true };
}