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

@ -4,6 +4,39 @@ Alle Änderungen werden hier dokumentiert. Format orientiert an
[Keep a Changelog](https://keepachangelog.com), Versionierung nach [Keep a Changelog](https://keepachangelog.com), Versionierung nach
[Semver](https://semver.org). [Semver](https://semver.org).
## [1.4.0] — 2026-05-14
Minor — 2FA-Enrollment (Mini-Sprint B). Setzt Mini-Sprint A
(`v1.3.0`) voraus. Komplett additiv.
### ManaCore — 2FA-Enrollment
- `TotpEnrollment` (public struct) — `totpURI` (für QR-Code-Display)
+ `backupCodes` (Liste).
- `AuthClient.enrollTotp(password:) -> TotpEnrollment` — aktiviert
TOTP-2FA; Server generiert Secret + Backup-Codes.
- `AuthClient.disableTotp(password:)` — deaktiviert wieder.
- `AuthClient.getTotpUri(password:) -> String` — Re-Display für
zweites Authenticator-Gerät.
- `AuthClient.regenerateBackupCodes(password:) -> [String]` — neue
Codes, alte werden ungültig.
Alle vier Methoden senden Bearer-Header mit Session-Token (Wire-
Konvention für mana-auth-Account-Endpoints).
### Server-Side Voraussetzung
`mana-auth` ≥ Commit der Wrapper-Endpoints:
- `POST /api/v1/auth/two-factor/enable`
- `POST /api/v1/auth/two-factor/disable`
- `POST /api/v1/auth/two-factor/get-totp-uri`
- `POST /api/v1/auth/two-factor/generate-backup-codes`
### Tests
- 7 neue Tests (Success-Pfade aller vier Methoden, leeres Passwort,
ohne Session, falsches Passwort). 66/66 grün.
## [1.3.0] — 2026-05-14 ## [1.3.0] — 2026-05-14
Minor — 2FA-Login-Challenge (Mini-Sprint A). Apps mit aktiviertem Minor — 2FA-Login-Challenge (Mini-Sprint A). Apps mit aktiviertem

View file

@ -481,3 +481,157 @@ private struct TwoFactorVerifyResponse: Decodable {
let accessToken: String? let accessToken: String?
let refreshToken: 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]?
}

View file

@ -0,0 +1,119 @@
import Foundation
import Testing
@testable import ManaCore
@Suite("AuthClient 2FA-Enrollment")
@MainActor
struct AuthClientTwoFactorEnrollmentTests {
/// Bringt den AuthClient in den `.signedIn`-Status mit einem
/// Session-Token für authenticated Calls.
private func signedInAuth() async -> MockedAuth {
let mocked = makeMockedAuth()
let access = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
mocked.setHandler { _ in
(200, Data(#"{"accessToken":"\#(access)","refreshToken":"session-tok"}"#.utf8))
}
await mocked.auth.signIn(email: "u@x.de", password: "pw")
return mocked
}
@Test("enrollTotp liefert URI + Backup-Codes")
func enrollSuccess() async throws {
let mocked = await signedInAuth()
let captured = MockURLProtocol.Capture()
mocked.setHandler { request in
captured.store(request)
return (200, Data(#"""
{"totpURI":"otpauth://totp/Mana:u@x.de?secret=ABC&issuer=Mana","backupCodes":["a-b-c","d-e-f","g-h-i"]}
"""#.utf8))
}
let enrollment = try await mocked.auth.enrollTotp(password: "pw")
#expect(enrollment.totpURI.hasPrefix("otpauth://totp/"))
#expect(enrollment.backupCodes == ["a-b-c", "d-e-f", "g-h-i"])
let request = try #require(captured.request)
#expect(request.url?.path == "/api/v1/auth/two-factor/enable")
// Bearer-Header trägt den Session-Token (nicht JWT)
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer session-tok")
}
@Test("enrollTotp mit leerem Passwort → validation, kein Server-Call")
func enrollEmptyPassword() async {
let mocked = await signedInAuth()
mocked.setHandler { _ in
Issue.record("Server darf nicht aufgerufen werden")
return (500, Data())
}
await #expect(throws: AuthError.validation(message: "Passwort ist erforderlich")) {
try await mocked.auth.enrollTotp(password: "")
}
}
@Test("enrollTotp ohne Session → notSignedIn")
func enrollNoSession() async {
let mocked = makeMockedAuth()
await #expect(throws: AuthError.notSignedIn) {
try await mocked.auth.enrollTotp(password: "pw")
}
}
@Test("disableTotp success")
func disableSuccess() async throws {
let mocked = await signedInAuth()
let captured = MockURLProtocol.Capture()
mocked.setHandler { request in
captured.store(request)
return (200, Data(#"{"success":true}"#.utf8))
}
try await mocked.auth.disableTotp(password: "pw")
let request = try #require(captured.request)
#expect(request.url?.path == "/api/v1/auth/two-factor/disable")
}
@Test("disableTotp mit falschem Passwort → invalidCredentials")
func disableWrongPassword() async {
let mocked = await signedInAuth()
mocked.setHandler { _ in
(401, Data(#"{"error":"INVALID_CREDENTIALS","status":401}"#.utf8))
}
await #expect(throws: AuthError.invalidCredentials) {
try await mocked.auth.disableTotp(password: "wrong")
}
}
@Test("getTotpUri liefert URI ohne Backup-Codes")
func getUriSuccess() async throws {
let mocked = await signedInAuth()
mocked.setHandler { _ in
(200, Data(#"""
{"totpURI":"otpauth://totp/Mana:u@x.de?secret=XYZ&issuer=Mana"}
"""#.utf8))
}
let uri = try await mocked.auth.getTotpUri(password: "pw")
#expect(uri.hasPrefix("otpauth://totp/"))
#expect(uri.contains("secret=XYZ"))
}
@Test("regenerateBackupCodes liefert neue Codes")
func regenerateSuccess() async throws {
let mocked = await signedInAuth()
let captured = MockURLProtocol.Capture()
mocked.setHandler { request in
captured.store(request)
return (200, Data(#"""
{"backupCodes":["new-1","new-2","new-3","new-4","new-5"]}
"""#.utf8))
}
let codes = try await mocked.auth.regenerateBackupCodes(password: "pw")
#expect(codes.count == 5)
#expect(codes.first == "new-1")
let request = try #require(captured.request)
#expect(request.url?.path == "/api/v1/auth/two-factor/generate-backup-codes")
}
}