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

@@ -6,9 +6,11 @@ import { PermissionResolverService } from '../permissions/permission-resolver.se
describe('JwtAuthGuard', () => {
let guard: JwtAuthGuard;
let reflector: { getAllAndOverride: jest.Mock };
let permissionResolver: { isUserActive: jest.Mock };
let permissionResolver: { isTokenValid: jest.Mock };
function contextWithUser(user: { id: string } | undefined): ExecutionContext {
function contextWithUser(
user: { id: string; tokenIssuedAt?: number } | undefined,
): ExecutionContext {
const request = { user };
return {
getHandler: () => ({}),
@@ -19,7 +21,7 @@ describe('JwtAuthGuard', () => {
beforeEach(() => {
reflector = { getAllAndOverride: jest.fn().mockReturnValue(false) };
permissionResolver = { isUserActive: jest.fn() };
permissionResolver = { isTokenValid: jest.fn() };
guard = new JwtAuthGuard(
reflector as unknown as Reflector,
permissionResolver as unknown as PermissionResolverService,
@@ -32,11 +34,11 @@ describe('JwtAuthGuard', () => {
await expect(guard.canActivate(contextWithUser(undefined))).resolves.toBe(
true,
);
expect(permissionResolver.isUserActive).not.toHaveBeenCalled();
expect(permissionResolver.isTokenValid).not.toHaveBeenCalled();
});
it('allows the request when the JWT is valid and the user is active', async () => {
const context = contextWithUser({ id: 'user-1' });
it('allows the request when the JWT is valid and the token is still valid for the user', async () => {
const context = contextWithUser({ id: 'user-1', tokenIssuedAt: 1000 });
jest
.spyOn(
Object.getPrototypeOf(JwtAuthGuard.prototype) as {
@@ -45,14 +47,17 @@ describe('JwtAuthGuard', () => {
'canActivate',
)
.mockReturnValue(true);
permissionResolver.isUserActive.mockResolvedValue(true);
permissionResolver.isTokenValid.mockResolvedValue(true);
await expect(guard.canActivate(context)).resolves.toBe(true);
expect(permissionResolver.isUserActive).toHaveBeenCalledWith('user-1');
expect(permissionResolver.isTokenValid).toHaveBeenCalledWith(
'user-1',
1000,
);
});
it('throws UnauthorizedException when the authenticated user has been deactivated', async () => {
const context = contextWithUser({ id: 'user-1' });
it('throws UnauthorizedException when the user is deactivated or the token predates a password change', async () => {
const context = contextWithUser({ id: 'user-1', tokenIssuedAt: 1000 });
jest
.spyOn(
Object.getPrototypeOf(JwtAuthGuard.prototype) as {
@@ -61,7 +66,7 @@ describe('JwtAuthGuard', () => {
'canActivate',
)
.mockReturnValue(true);
permissionResolver.isUserActive.mockResolvedValue(false);
permissionResolver.isTokenValid.mockResolvedValue(false);
await expect(guard.canActivate(context)).rejects.toBeInstanceOf(
UnauthorizedException,
@@ -14,13 +14,14 @@ interface RequestWithUser {
}
/**
* Enforces User.isActive on every authenticated request, not just ones
* gated by @RequirePermission. Without this, a deactivated user's
* still-valid access token would keep working on any route that carries no
* permission decorator until the token's own expiry (up to
* JWT_ACCESS_EXPIRES_IN). isUserActive shares PermissionsGuard's cache, so
* this check costs no extra query beyond what permission resolution already
* does.
* Enforces User.isActive and token freshness (issued after the last
* password change) on every authenticated request, not just ones gated by
* @RequirePermission. Without this, a deactivated user's still-valid access
* token - or one stolen before a password change - would keep working on
* any route that carries no permission decorator until the token's own
* expiry (up to JWT_ACCESS_EXPIRES_IN). isTokenValid shares
* PermissionsGuard's cache, so this check costs no extra query beyond what
* permission resolution already does.
*/
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
@@ -45,7 +46,10 @@ export class JwtAuthGuard extends AuthGuard('jwt') {
}
const request = context.switchToHttp().getRequest<RequestWithUser>();
const user = request.user;
if (!user || !(await this.permissionResolver.isUserActive(user.id))) {
if (
!user ||
!(await this.permissionResolver.isTokenValid(user.id, user.tokenIssuedAt))
) {
throw new UnauthorizedException();
}
return true;