v1.4.0 — 2FA-Enrollment

Mini-Sprint B des 2FA-Vollausbaus. Apps können jetzt TOTP-2FA für
ihre User aktivieren und verwalten. Komplett additiv.

Neuer Public-Struct:
- TotpEnrollment { totpURI, backupCodes }

Neue Methoden in AuthClient+Account:
- enrollTotp(password:) -> TotpEnrollment — aktiviert 2FA, liefert
  otpauth-URI (für QR) + Backup-Codes (einmalig)
- disableTotp(password:) — deaktiviert wieder
- getTotpUri(password:) -> String — Re-Display für zweites Gerät
- regenerateBackupCodes(password:) -> [String] — alte werden ungültig

Alle vier nutzen den authenticated-Pfad (Session-Token als Bearer).
Setzt mana-auth ≥ v1.3.0 + die neuen Wrapper-Endpoints für
/api/v1/auth/two-factor/{enable,disable,get-totp-uri,generate-backup-codes}
voraus.

7 neue Tests, 66/66 grün.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Till JS 2026-05-14 00:38:38 +02:00
parent 7526b807da
commit 0a79083b58
3 changed files with 306 additions and 0 deletions

View file

@ -481,3 +481,157 @@ private struct TwoFactorVerifyResponse: Decodable {
let accessToken: String?
let refreshToken: String?
}
// MARK: - Two-Factor (Enrollment)
/// Ergebnis von ``AuthClient/enrollTotp(password:)``: enthält die
/// otpauth-URI (für QR-Code-Display) und die Backup-Codes. Backup-
/// Codes sind einmalig nutzbar und sollten dem User zum Sichern
/// (Kopieren/Drucken) angeboten werden der Server zeigt sie nie
/// mehr.
public struct TotpEnrollment: Sendable, Equatable {
/// `otpauth://totp/Issuer:email?secret=...&...`-URI. Direkt als
/// QR-Code rendern (z.B. via `CIFilter.qrCodeGenerator`).
public let totpURI: String
/// Liste der Backup-Codes (üblich 10 Stück). Der User sollte sie
/// sicher aufbewahren bei Verlust des TOTP-Geräts sind sie der
/// einzige Fallback. Server merkt sich nur Hashes; bei Verbrauch
/// werden sie als consumed markiert.
public let backupCodes: [String]
}
public extension AuthClient {
/// Aktiviert TOTP-2FA für den aktuellen Account.
///
/// Re-Auth via aktuellem Passwort. Bei Erfolg generiert der Server
/// ein TOTP-Secret und gibt die otpauth-URI + Backup-Codes zurück.
/// Die App rendert die URI als QR-Code, der User scannt mit
/// Authenticator-App und gibt zur Bestätigung den ersten Code ein
/// dieser zweite Schritt läuft über die regulären
/// ``verifyTotp(code:trustDevice:)``-Methode oder einen Re-Auth
/// signIn twoFactorRequired-Flow (der Server entscheidet).
///
/// - Important: Nutzt den Session-Token als Bearer (Wire-Konvention
/// für mana-auth-Account-Endpoints, siehe Doc-Header dieser Datei).
func enrollTotp(password: String) async throws -> TotpEnrollment {
guard !password.isEmpty else {
throw AuthError.validation(message: "Passwort ist erforderlich")
}
let body = TotpEnableRequest(password: password)
let (data, http) = try await postJSON(
path: "/api/v1/auth/two-factor/enable",
body: body,
authenticated: true
)
guard http.statusCode == 200 else {
throw AuthError.classify(
status: http.statusCode,
data: data,
retryAfterHeader: http.retryAfterSeconds
)
}
let decoded = try JSONDecoder().decode(TotpEnableResponse.self, from: data)
guard let uri = decoded.totpURI else {
throw AuthError.decoding("totpURI fehlt in Enroll-Antwort")
}
CoreLog.auth.info("2FA TOTP enrollment initiated")
return TotpEnrollment(totpURI: uri, backupCodes: decoded.backupCodes ?? [])
}
/// Deaktiviert TOTP-2FA für den aktuellen Account. Re-Auth via
/// Passwort.
func disableTotp(password: String) async throws {
guard !password.isEmpty else {
throw AuthError.validation(message: "Passwort ist erforderlich")
}
let body = TotpEnableRequest(password: password)
let (data, http) = try await postJSON(
path: "/api/v1/auth/two-factor/disable",
body: body,
authenticated: true
)
guard http.statusCode == 200 else {
throw AuthError.classify(
status: http.statusCode,
data: data,
retryAfterHeader: http.retryAfterSeconds
)
}
CoreLog.auth.info("2FA TOTP disabled")
}
/// Liefert die otpauth-URI des aktuellen TOTP-Secrets. Nützlich
/// wenn der User den QR-Code erneut sehen will (z.B. zweites
/// Gerät einrichten). Re-Auth via Passwort.
///
/// - Returns: `otpauth://totp/`-URI, direkt als QR-Code renderbar.
func getTotpUri(password: String) async throws -> String {
guard !password.isEmpty else {
throw AuthError.validation(message: "Passwort ist erforderlich")
}
let body = TotpEnableRequest(password: password)
let (data, http) = try await postJSON(
path: "/api/v1/auth/two-factor/get-totp-uri",
body: body,
authenticated: true
)
guard http.statusCode == 200 else {
throw AuthError.classify(
status: http.statusCode,
data: data,
retryAfterHeader: http.retryAfterSeconds
)
}
let decoded = try JSONDecoder().decode(TotpEnableResponse.self, from: data)
guard let uri = decoded.totpURI else {
throw AuthError.decoding("totpURI fehlt in get-totp-uri-Antwort")
}
return uri
}
/// Regeneriert die Backup-Codes. Alte Codes werden ungültig. Der
/// User sollte die neuen direkt sichern.
func regenerateBackupCodes(password: String) async throws -> [String] {
guard !password.isEmpty else {
throw AuthError.validation(message: "Passwort ist erforderlich")
}
let body = TotpEnableRequest(password: password)
let (data, http) = try await postJSON(
path: "/api/v1/auth/two-factor/generate-backup-codes",
body: body,
authenticated: true
)
guard http.statusCode == 200 else {
throw AuthError.classify(
status: http.statusCode,
data: data,
retryAfterHeader: http.retryAfterSeconds
)
}
let decoded = try JSONDecoder().decode(TotpEnableResponse.self, from: data)
guard let codes = decoded.backupCodes else {
throw AuthError.decoding("backupCodes fehlen in Antwort")
}
return codes
}
}
private struct TotpEnableRequest: Encodable {
let password: String
}
/// Antwort-Format für alle Enrollment-Endpoints. Felder sind optional
/// damit derselbe Type für `enable` (beide), `get-totp-uri` (nur URI)
/// und `generate-backup-codes` (nur Codes) dekodierbar ist.
private struct TotpEnableResponse: Decodable {
let totpURI: String?
let backupCodes: [String]?
}