feat: MFA (TOTP) und Self-Service-Profilseite
Backend Image / build-and-push (push) Successful in 2m57s
Frontend Image / build-and-push (push) Successful in 2m30s

Benutzer koennen jetzt selbst Zwei-Faktor-Authentifizierung einrichten
und ihr Profil verwalten (Name, E-Mail, Passwort, Profilbild).

Backend:
- Neues MfaModule (src/auth/mfa/): AES-256-GCM-verschluesselte
  TOTP-Secrets (otplib), QR-Code-Erzeugung, kurzlebige Setup-/
  Challenge-JWTs fuer den 2-Schritt-Login-Flow
- Neues ProfileModule (src/profile/): PATCH /profile,
  POST /profile/password, POST/DELETE/GET /profile/avatar,
  POST /profile/mfa/enroll(/confirm), POST /profile/mfa/disable -
  alle self-scoped ueber actor.id, ohne @RequirePermission (siehe
  ALLOWLIST in authorization-coverage.e2e-spec.ts)
- AuthService.login() zweistufig: bei aktivem MFA erst
  { mfaRequired, mfaToken } statt Tokens, neuer Endpunkt
  POST /auth/mfa/verify schliesst den Flow ab
- Admin-Recovery: POST /users/:id/mfa/reset (users:update) fuer
  verlorene MFA-Geraete, da es keinen E-Mail-Reset-Flow gibt

Frontend:
- Login-Seite mit zweitem Schritt fuer den TOTP-Code
- Neue Profilseite (/profile, ausserhalb des admin-only
  Settings-Bereichs): Profilbild, Name/E-Mail, Passwort, MFA-Ein-/
  Ausrichtung mit QR-Code-Dialog
- Header zeigt jetzt Avatar mit Dropdown (Profil/Abmelden) statt
  nur E-Mail-Text
- Admin-Users-Tabelle zeigt MFA-Status + Reset-Button

Haertung nach Security-Review (Backend/Frontend-Diff, kein CRITICAL,
mehrere MEDIUM behoben):
- Access-Token wird bei Passwortwechsel sofort ungueltig
  (User.passwordChangedAt + JWT-iat-Vergleich in
  PermissionResolverService.isTokenValid, vorher isUserActive) statt
  erst nach bis zu 15 Minuten
- E-Mail-Aenderung verlangt jetzt aktuelles Passwort
- POST /profile/password und /profile/mfa/disable haben jetzt das
  gleiche strikte Throttling wie Login (SENSITIVE_ACTION_THROTTLE)
- Kein stiller leerer Verschluesselungs-Key-Fallback mehr (wirft
  jetzt explizit)

Bewusst zurueckgestellt (dokumentiert, kein aktiver Exploit-Pfad):
dedizierter Verschluesselungs-Key fuer MFA-Secrets statt
JWT_ACCESS_SECRET-Ableitung, dedizierte users:mfa-reset-Permission
statt users:update, separate JWT-Secrets pro Token-Zweck.

Verifiziert: tsc/eslint clean, 297/297 Backend- + 31/31
Frontend-Unit-Tests, Build clean auf beiden Projekten. e2e weiterhin
durch bekanntes WSL2/Postgres-Problem blockiert. Unabhaengiges
Security- und Code-Quality-Review durchgefuehrt (0 CRITICAL, 0 HIGH).
This commit is contained in:
Nick Szaunig committed 2026-08-27 00:25:34 +02:00
1 parent 6776bdfe73
commit 62004483cf
55 files changed
+2876 -129

No files matched your search

+27 -1
View File
@@ -4,7 +4,18 @@ export interface AccessTokenResponse {
accessToken: string;
}
export async function loginRequest(email: string, password: string): Promise<AccessTokenResponse> {
export interface MfaRequiredResponse {
mfaRequired: true;
mfaToken: string;
}
export type LoginResponse = AccessTokenResponse | MfaRequiredResponse;
export function isMfaRequired(response: LoginResponse): response is MfaRequiredResponse {
return 'mfaRequired' in response && response.mfaRequired;
}
export async function loginRequest(email: string, password: string): Promise<LoginResponse> {
const response = await fetch(`${API_URL}/auth/login`, {
method: 'POST',
credentials: 'include',
@@ -14,6 +25,19 @@ export async function loginRequest(email: string, password: string): Promise<Acc
if (!response.ok) {
throw new Error('Login fehlgeschlagen. Bitte E-Mail und Passwort prüfen.');
}
return response.json() as Promise<LoginResponse>;
}
export async function verifyMfaRequest(mfaToken: string, code: string): Promise<AccessTokenResponse> {
const response = await fetch(`${API_URL}/auth/mfa/verify`, {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mfaToken, code }),
});
if (!response.ok) {
throw new Error('Code ungültig. Bitte erneut versuchen.');
}
return response.json() as Promise<AccessTokenResponse>;
}
@@ -56,6 +80,8 @@ export interface CurrentUserProfile {
roleKey: string;
roleName: string;
permissions: string[];
mfaEnabled: boolean;
hasAvatar: boolean;
}
export async function getCurrentUserRequest(accessToken: string): Promise<CurrentUserProfile> {
+40 -5
View File
@@ -1,8 +1,15 @@
'use client';
import { createContext, useCallback, useContext, useEffect, useState, ReactNode } from 'react';
import { getCurrentUserRequest, loginRequest, logoutRequest, refreshRequest } from './api';
import { setAccessToken as storeAccessToken } from './token-store';
import {
getCurrentUserRequest,
isMfaRequired,
loginRequest,
logoutRequest,
refreshRequest,
verifyMfaRequest,
} from './api';
import { getAccessToken, setAccessToken as storeAccessToken } from './token-store';
export interface AuthUser {
id: string;
@@ -11,14 +18,20 @@ export interface AuthUser {
roleKey: string;
roleName: string;
permissions: string[];
mfaEnabled: boolean;
hasAvatar: boolean;
}
export type LoginOutcome = { mfaRequired: false } | { mfaRequired: true; mfaToken: string };
interface AuthContextValue {
user: AuthUser | null;
isLoading: boolean;
login: (email: string, password: string) => Promise<void>;
login: (email: string, password: string) => Promise<LoginOutcome>;
verifyMfa: (mfaToken: string, code: string) => Promise<void>;
logout: () => Promise<void>;
hasPermission: (permission: string) => boolean;
refreshUser: () => Promise<void>;
}
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
@@ -49,8 +62,17 @@ export function AuthProvider({ children }: { children: ReactNode }) {
});
}, []);
const login = useCallback(async (email: string, password: string) => {
const login = useCallback(async (email: string, password: string): Promise<LoginOutcome> => {
const result = await loginRequest(email, password);
if (isMfaRequired(result)) {
return { mfaRequired: true, mfaToken: result.mfaToken };
}
setUser(await applyAccessToken(result.accessToken));
return { mfaRequired: false };
}, []);
const verifyMfa = useCallback(async (mfaToken: string, code: string) => {
const result = await verifyMfaRequest(mfaToken, code);
setUser(await applyAccessToken(result.accessToken));
}, []);
@@ -65,8 +87,21 @@ export function AuthProvider({ children }: { children: ReactNode }) {
[user],
);
// Re-fetches the profile with the access token already held in memory -
// no need to rotate the refresh-token cookie just to reflect a self-edit
// (name/email/avatar/MFA change) in the cached user.
const refreshUser = useCallback(async () => {
const token = getAccessToken();
if (!token) {
return;
}
setUser(await applyAccessToken(token));
}, []);
return (
<AuthContext.Provider value={{ user, isLoading, login, logout, hasPermission }}>
<AuthContext.Provider
value={{ user, isLoading, login, verifyMfa, logout, hasPermission, refreshUser }}
>
{children}
</AuthContext.Provider>
);
+57
View File
@@ -0,0 +1,57 @@
import { apiFetch, apiFetchBlob, apiFetchFormData } from "@/lib/auth/api-client";
import { MfaEnrollment, ProfileSummary, UpdateProfileInput } from "./types";
export function updateProfile(input: UpdateProfileInput): Promise<ProfileSummary> {
return apiFetch<ProfileSummary>("/profile", {
method: "PATCH",
body: JSON.stringify(input),
});
}
export function changePassword(currentPassword: string, newPassword: string): Promise<void> {
return apiFetch<void>("/profile/password", {
method: "POST",
body: JSON.stringify({ currentPassword, newPassword }),
});
}
export function uploadAvatar(file: File): Promise<void> {
const formData = new FormData();
formData.append("file", file);
return apiFetchFormData<void>("/profile/avatar", formData);
}
export function deleteAvatar(): Promise<void> {
return apiFetch<void>("/profile/avatar", { method: "DELETE" });
}
// Fetches the avatar as a blob (the endpoint requires the caller's own
// Bearer token, so a plain <img src="..."> can't hit it directly) and hands
// back an object URL for use as an <img> source. Returns null when the user
// has no avatar (404) or the request otherwise fails.
export async function fetchAvatarUrl(): Promise<string | null> {
try {
const { blob } = await apiFetchBlob("/profile/avatar", "avatar");
return URL.createObjectURL(blob);
} catch {
return null;
}
}
export function enrollMfa(): Promise<MfaEnrollment> {
return apiFetch<MfaEnrollment>("/profile/mfa/enroll", { method: "POST" });
}
export function confirmMfaEnrollment(setupToken: string, code: string): Promise<void> {
return apiFetch<void>("/profile/mfa/enroll/confirm", {
method: "POST",
body: JSON.stringify({ setupToken, code }),
});
}
export function disableMfa(currentPassword: string): Promise<void> {
return apiFetch<void>("/profile/mfa/disable", {
method: "POST",
body: JSON.stringify({ currentPassword }),
});
}
+19
View File
@@ -0,0 +1,19 @@
export interface ProfileSummary {
id: string;
email: string;
name: string;
}
export interface UpdateProfileInput {
name?: string;
email?: string;
/** Required by the backend when email is being changed; ignored otherwise. */
currentPassword?: string;
}
export interface MfaEnrollment {
secret: string;
qrCodeSvg: string;
otpauthUri: string;
setupToken: string;
}
+4
View File
@@ -19,3 +19,7 @@ export function deactivateUser(id: string): Promise<User> {
export function activateUser(id: string): Promise<User> {
return apiFetch<User>(`/users/${id}/activate`, { method: "POST" });
}
export function resetUserMfa(id: string): Promise<User> {
return apiFetch<User>(`/users/${id}/mfa/reset`, { method: "POST" });
}
+1
View File
@@ -8,6 +8,7 @@ export interface User {
isActive: boolean;
createdAt: string;
deactivatedAt: string | null;
mfaEnabled: boolean;
}
export interface CreateUserInput {