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

+55 -5
View File
@@ -6,7 +6,7 @@ import { PrismaService } from '../prisma/prisma.service';
import { UsersService } from '../users/users.service';
import { AuditLogService } from '../audit/audit-log.service';
import { PermissionResolverService } from './permissions/permission-resolver.service';
import { AuthenticatedUser } from './types/authenticated-user';
import { MfaService } from './mfa/mfa.service';
import { parseDurationToMs } from './util/duration';
interface AuthTokens {
@@ -14,6 +14,10 @@ interface AuthTokens {
refreshToken: string;
}
export type LoginResult =
| ({ mfaRequired: false } & AuthTokens)
| { mfaRequired: true; mfaToken: string };
export interface CurrentUserProfile {
id: string;
email: string;
@@ -21,6 +25,8 @@ export interface CurrentUserProfile {
roleKey: string;
roleName: string;
permissions: string[];
mfaEnabled: boolean;
hasAvatar: boolean;
}
const REFRESH_TOKEN_BYTES = 40;
@@ -33,6 +39,7 @@ export class AuthService {
private readonly jwtService: JwtService,
private readonly auditLog: AuditLogService,
private readonly permissionResolver: PermissionResolverService,
private readonly mfaService: MfaService,
) {}
async getCurrentUserProfile(userId: string): Promise<CurrentUserProfile> {
@@ -48,6 +55,8 @@ export class AuthService {
roleKey: user.role.key,
roleName: user.role.name,
permissions: Array.from(permissions),
mfaEnabled: user.mfaEnabled,
hasAvatar: user.avatarPath !== null,
};
}
@@ -55,7 +64,7 @@ export class AuthService {
return crypto.createHash('sha256').update(token).digest('hex');
}
private signAccessToken(user: AuthenticatedUser): string {
private signAccessToken(user: { id: string; email: string }): string {
const expiresInSeconds = Math.floor(
parseDurationToMs(process.env.JWT_ACCESS_EXPIRES_IN ?? '15m') / 1000,
);
@@ -80,7 +89,7 @@ export class AuthService {
return token;
}
async login(email: string, password: string): Promise<AuthTokens> {
async login(email: string, password: string): Promise<LoginResult> {
const user = await this.usersService.findByEmail(email);
if (!user || !user.isActive) {
await this.auditLog.record({
@@ -101,7 +110,48 @@ export class AuthService {
});
throw new UnauthorizedException('Invalid credentials');
}
const authenticatedUser: AuthenticatedUser = {
if (user.mfaEnabled) {
return {
mfaRequired: true,
mfaToken: this.mfaService.signChallengeToken(user.id),
};
}
const authenticatedUser = {
id: user.id,
email: user.email,
};
const accessToken = this.signAccessToken(authenticatedUser);
const refreshToken = await this.issueRefreshToken(user.id);
await this.auditLog.record({
entityType: 'AuthSession',
entityId: user.id,
action: 'LOGIN',
userId: user.id,
});
return { mfaRequired: false, accessToken, refreshToken };
}
async verifyMfaAndLogin(mfaToken: string, code: string): Promise<AuthTokens> {
const { userId } = this.mfaService.verifyChallengeToken(mfaToken);
const user = await this.usersService.findById(userId);
if (!user.isActive || !user.mfaEnabled || !user.mfaSecret) {
throw new UnauthorizedException('MFA nicht verfügbar');
}
const isValid = await this.mfaService.verifyCode(
user.mfaSecret,
user.email,
code,
);
if (!isValid) {
await this.auditLog.record({
entityType: 'AuthSession',
entityId: user.id,
action: 'LOGIN_FAILED',
userId: user.id,
});
throw new UnauthorizedException('Code ungültig');
}
const authenticatedUser = {
id: user.id,
email: user.email,
};
@@ -132,7 +182,7 @@ export class AuthService {
where: { id: stored.id },
data: { revokedAt: new Date() },
});
const authenticatedUser: AuthenticatedUser = {
const authenticatedUser = {
id: user.id,
email: user.email,
};