feat: MFA (TOTP) und Self-Service-Profilseite
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:
1 parent
6776bdfe73
commit
62004483cf
55 files changed
+2876
-129
No files matched your search
@@ -0,0 +1,239 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import * as crypto from 'node:crypto';
|
||||
import * as fs from 'node:fs/promises';
|
||||
import * as path from 'node:path';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { AuditLogService } from '../audit/audit-log.service';
|
||||
import { MfaService, MfaEnrollment } from '../auth/mfa/mfa.service';
|
||||
import { PermissionResolverService } from '../auth/permissions/permission-resolver.service';
|
||||
import {
|
||||
ALLOWED_AVATAR_MIME_TYPES,
|
||||
mimeTypeForExtension,
|
||||
} from './avatar-mime-types';
|
||||
import { UpdateProfileDto } from './dto/update-profile.dto';
|
||||
|
||||
const BCRYPT_SALT_ROUNDS = 12;
|
||||
|
||||
export interface ProfileSummary {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
function avatarStorageRoot(): string {
|
||||
return path.join(
|
||||
process.env.DOCUMENTS_STORAGE_PATH ?? './uploads',
|
||||
'avatars',
|
||||
);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ProfileService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly auditLog: AuditLogService,
|
||||
private readonly mfaService: MfaService,
|
||||
private readonly permissionResolver: PermissionResolverService,
|
||||
) {}
|
||||
|
||||
private async requireUser(userId: string) {
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
async updateProfile(
|
||||
userId: string,
|
||||
dto: UpdateProfileDto,
|
||||
): Promise<ProfileSummary> {
|
||||
const before = await this.requireUser(userId);
|
||||
if (dto.email && dto.email !== before.email) {
|
||||
const currentMatches =
|
||||
dto.currentPassword &&
|
||||
(await bcrypt.compare(dto.currentPassword, before.passwordHash));
|
||||
if (!currentMatches) {
|
||||
throw new UnauthorizedException(
|
||||
'Aktuelles Passwort erforderlich, um die E-Mail-Adresse zu ändern',
|
||||
);
|
||||
}
|
||||
const existing = await this.prisma.user.findUnique({
|
||||
where: { email: dto.email },
|
||||
});
|
||||
if (existing) {
|
||||
throw new ConflictException('Email already in use');
|
||||
}
|
||||
}
|
||||
const user = await this.prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { name: dto.name, email: dto.email },
|
||||
});
|
||||
await this.auditLog.record({
|
||||
entityType: 'User',
|
||||
entityId: userId,
|
||||
action: 'UPDATE',
|
||||
userId,
|
||||
beforeData: { name: before.name, email: before.email },
|
||||
afterData: { name: user.name, email: user.email },
|
||||
});
|
||||
return { id: user.id, email: user.email, name: user.name };
|
||||
}
|
||||
|
||||
async changePassword(
|
||||
userId: string,
|
||||
currentPassword: string,
|
||||
newPassword: string,
|
||||
): Promise<void> {
|
||||
const user = await this.requireUser(userId);
|
||||
const currentMatches = await bcrypt.compare(
|
||||
currentPassword,
|
||||
user.passwordHash,
|
||||
);
|
||||
if (!currentMatches) {
|
||||
throw new UnauthorizedException('Aktuelles Passwort ist falsch');
|
||||
}
|
||||
const passwordHash = await bcrypt.hash(newPassword, BCRYPT_SALT_ROUNDS);
|
||||
await this.prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { passwordHash, passwordChangedAt: new Date() },
|
||||
});
|
||||
// A changed password should invalidate any session issued before the
|
||||
// change, on this device or any other: refresh tokens are revoked
|
||||
// outright, and the permission cache is cleared so JwtAuthGuard picks
|
||||
// up the new passwordChangedAt within this request cycle instead of
|
||||
// waiting out the cache TTL - that's what makes a still-live access
|
||||
// token stop working immediately (see PermissionResolverService).
|
||||
await this.prisma.refreshToken.updateMany({
|
||||
where: { userId, revokedAt: null },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
this.permissionResolver.invalidateUser(userId);
|
||||
await this.auditLog.record({
|
||||
entityType: 'User',
|
||||
entityId: userId,
|
||||
action: 'UPDATE',
|
||||
userId,
|
||||
});
|
||||
}
|
||||
|
||||
async uploadAvatar(userId: string, file: Express.Multer.File): Promise<void> {
|
||||
if (!(file.mimetype in ALLOWED_AVATAR_MIME_TYPES)) {
|
||||
throw new BadRequestException('Nicht unterstützter Dateityp');
|
||||
}
|
||||
const user = await this.requireUser(userId);
|
||||
const extension = ALLOWED_AVATAR_MIME_TYPES[file.mimetype];
|
||||
const directory = avatarStorageRoot();
|
||||
await fs.mkdir(directory, { recursive: true });
|
||||
const avatarPath = path.join(
|
||||
directory,
|
||||
`${crypto.randomUUID()}${extension}`,
|
||||
);
|
||||
await fs.writeFile(avatarPath, file.buffer);
|
||||
if (user.avatarPath) {
|
||||
await fs.unlink(user.avatarPath).catch(() => undefined);
|
||||
}
|
||||
await this.prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { avatarPath },
|
||||
});
|
||||
await this.auditLog.record({
|
||||
entityType: 'User',
|
||||
entityId: userId,
|
||||
action: 'UPDATE',
|
||||
userId,
|
||||
});
|
||||
}
|
||||
|
||||
async deleteAvatar(userId: string): Promise<void> {
|
||||
const user = await this.requireUser(userId);
|
||||
if (!user.avatarPath) {
|
||||
return;
|
||||
}
|
||||
await fs.unlink(user.avatarPath).catch(() => undefined);
|
||||
await this.prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { avatarPath: null },
|
||||
});
|
||||
await this.auditLog.record({
|
||||
entityType: 'User',
|
||||
entityId: userId,
|
||||
action: 'UPDATE',
|
||||
userId,
|
||||
});
|
||||
}
|
||||
|
||||
async getAvatar(
|
||||
userId: string,
|
||||
): Promise<{ buffer: Buffer; mimeType: string }> {
|
||||
const user = await this.requireUser(userId);
|
||||
if (!user.avatarPath) {
|
||||
throw new NotFoundException('No avatar set');
|
||||
}
|
||||
const buffer = await fs.readFile(user.avatarPath);
|
||||
return {
|
||||
buffer,
|
||||
mimeType: mimeTypeForExtension(path.extname(user.avatarPath)),
|
||||
};
|
||||
}
|
||||
|
||||
async enrollMfa(userId: string, email: string): Promise<MfaEnrollment> {
|
||||
const user = await this.requireUser(userId);
|
||||
if (user.mfaEnabled) {
|
||||
throw new ConflictException('MFA is already enabled');
|
||||
}
|
||||
return this.mfaService.startEnrollment(userId, email);
|
||||
}
|
||||
|
||||
async confirmMfaEnrollment(
|
||||
userId: string,
|
||||
email: string,
|
||||
setupToken: string,
|
||||
code: string,
|
||||
): Promise<void> {
|
||||
const { encryptedSecret } = await this.mfaService.confirmEnrollment(
|
||||
userId,
|
||||
setupToken,
|
||||
email,
|
||||
code,
|
||||
);
|
||||
await this.prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { mfaEnabled: true, mfaSecret: encryptedSecret },
|
||||
});
|
||||
await this.auditLog.record({
|
||||
entityType: 'User',
|
||||
entityId: userId,
|
||||
action: 'MFA_ENABLED',
|
||||
userId,
|
||||
});
|
||||
}
|
||||
|
||||
async disableMfa(userId: string, currentPassword: string): Promise<void> {
|
||||
const user = await this.requireUser(userId);
|
||||
const currentMatches = await bcrypt.compare(
|
||||
currentPassword,
|
||||
user.passwordHash,
|
||||
);
|
||||
if (!currentMatches) {
|
||||
throw new UnauthorizedException('Aktuelles Passwort ist falsch');
|
||||
}
|
||||
await this.prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { mfaEnabled: false, mfaSecret: null },
|
||||
});
|
||||
await this.auditLog.record({
|
||||
entityType: 'User',
|
||||
entityId: userId,
|
||||
action: 'MFA_DISABLED',
|
||||
userId,
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user