diff --git a/.gitignore b/.gitignore index ccc51e2..9f37740 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,3 @@ Package.resolved xcuserdata/ DerivedData/ -build/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 30501d3..8376473 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,58 +4,6 @@ Alle Änderungen werden hier dokumentiert. Format orientiert an [Keep a Changelog](https://keepachangelog.com), Versionierung nach [Semver](https://semver.org). -## [1.5.0] — 2026-05-14 - -Minor — `getProfile()` + `ProfileInfo`. Apps können den 2FA-Status -des eingeloggten Users lesen, damit AccountView entscheidet ob -"Aktivieren" oder "Deaktivieren" angezeigt wird. - -### Neu - -- `ProfileInfo` (public struct) — `id`, `email`, `name`, - `emailVerified`, `twoFactorEnabled`. -- `AuthClient.getProfile() -> ProfileInfo` — lädt aktuelles Profil - vom Server (`GET /api/v1/auth/profile` → Better Auths - `/api/auth/get-session`). Nutzt Session-Token als Bearer. - -### Tests - -- 4 neue Tests (twoFactor-on, twoFactor-off, ohne Session, - unauthorized). 70/70 grün. - -## [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 Minor — 2FA-Login-Challenge (Mini-Sprint A). Apps mit aktiviertem diff --git a/Sources/ManaCore/Auth/AuthClient+Account.swift b/Sources/ManaCore/Auth/AuthClient+Account.swift index b717004..08a6a45 100644 --- a/Sources/ManaCore/Auth/AuthClient+Account.swift +++ b/Sources/ManaCore/Auth/AuthClient+Account.swift @@ -481,255 +481,3 @@ 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]? -} - -// MARK: - Profile - -/// Subset des Server-User-Profiles, das die Apps für UI-Entscheidungen -/// brauchen. Wird von ``AuthClient/getProfile()`` geliefert. -/// -/// Server-Quelle: `GET /api/v1/auth/profile` (→ Better Auths -/// `/api/auth/get-session`). Returnt `{user: {…}, session: {…}}`. -/// Wir nehmen nur die UI-relevanten Felder mit. -public struct ProfileInfo: Sendable, Equatable { - public let id: String - public let email: String - public let name: String? - public let emailVerified: Bool - /// `true` wenn der User TOTP-2FA aktiviert hat. Apps zeigen - /// dann den Disable-/Regenerate-Pfad statt des Enroll-Wizards. - public let twoFactorEnabled: Bool - - public init( - id: String, - email: String, - name: String?, - emailVerified: Bool, - twoFactorEnabled: Bool - ) { - self.id = id - self.email = email - self.name = name - self.emailVerified = emailVerified - self.twoFactorEnabled = twoFactorEnabled - } -} - -public extension AuthClient { - /// Lädt das aktuelle Profil des eingeloggten Users vom Server. - /// - /// - Important: Nutzt den Session-Token als Bearer (Wire-Konvention - /// für mana-auth-Endpoints, siehe Doc-Header dieser Datei). - /// - /// - Throws: ``AuthError/notSignedIn`` ohne Session, - /// ``AuthError/unauthorized`` wenn Server den Token rejected, - /// Netzwerk-Cases. - func getProfile() async throws -> ProfileInfo { - let token = try currentSessionToken() - let url = config.authBaseURL.appending(path: "/api/v1/auth/profile") - var request = URLRequest(url: url) - request.httpMethod = "GET" - request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") - - let (data, http): (Data, HTTPURLResponse) - do { - let (d, r) = try await session.data(for: request) - guard let h = r as? HTTPURLResponse else { - throw AuthError.networkFailure("Keine HTTP-Antwort") - } - data = d - http = h - } catch let error as URLError { - throw AuthError.networkFailure(error.localizedDescription) - } - - guard http.statusCode == 200 else { - throw AuthError.classify( - status: http.statusCode, - data: data, - retryAfterHeader: http.retryAfterSeconds - ) - } - - let envelope = try JSONDecoder().decode(ProfileEnvelope.self, from: data) - guard let user = envelope.user else { - throw AuthError.decoding("user-Feld fehlt in profile-Antwort") - } - - return ProfileInfo( - id: user.id, - email: user.email, - name: user.name, - emailVerified: user.emailVerified ?? false, - twoFactorEnabled: user.twoFactorEnabled ?? false - ) - } -} - -/// Wire-Format-Hülle für `GET /api/v1/auth/profile`. Better-Auth- -/// `/api/auth/get-session` returnt `{user: {...}, session: {...}}`; -/// wir lesen `user` und ignorieren `session`. -private struct ProfileEnvelope: Decodable { - let user: ProfileUser? -} - -private struct ProfileUser: Decodable { - let id: String - let email: String - let name: String? - let emailVerified: Bool? - let twoFactorEnabled: Bool? -} diff --git a/Tests/ManaCoreTests/AuthClientProfileTests.swift b/Tests/ManaCoreTests/AuthClientProfileTests.swift deleted file mode 100644 index 69c0daf..0000000 --- a/Tests/ManaCoreTests/AuthClientProfileTests.swift +++ /dev/null @@ -1,77 +0,0 @@ -import Foundation -import Testing -@testable import ManaCore - -@Suite("AuthClient getProfile") -@MainActor -struct AuthClientProfileTests { - 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("getProfile mit twoFactor on") - func profileTwoFactorOn() async throws { - let mocked = await signedInAuth() - let captured = MockURLProtocol.Capture() - mocked.setHandler { request in - captured.store(request) - return (200, Data(#""" - {"user":{"id":"u1","email":"u@x.de","name":"Test","emailVerified":true,"twoFactorEnabled":true}, - "session":{"id":"s1"}} - """#.utf8)) - } - - let profile = try await mocked.auth.getProfile() - #expect(profile.id == "u1") - #expect(profile.email == "u@x.de") - #expect(profile.name == "Test") - #expect(profile.emailVerified == true) - #expect(profile.twoFactorEnabled == true) - - let request = try #require(captured.request) - #expect(request.httpMethod == "GET") - #expect(request.url?.path == "/api/v1/auth/profile") - // Bearer-Header trägt den Session-Token - #expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer session-tok") - } - - @Test("getProfile mit twoFactor off (Feld fehlt)") - func profileTwoFactorOff() async throws { - let mocked = await signedInAuth() - mocked.setHandler { _ in - (200, Data(#""" - {"user":{"id":"u1","email":"u@x.de","name":null,"emailVerified":true}} - """#.utf8)) - } - - let profile = try await mocked.auth.getProfile() - #expect(profile.twoFactorEnabled == false) - #expect(profile.name == nil) - } - - @Test("getProfile ohne Session → notSignedIn") - func profileNoSession() async { - let mocked = makeMockedAuth() - await #expect(throws: AuthError.notSignedIn) { - try await mocked.auth.getProfile() - } - } - - @Test("getProfile mit abgelaufenem Token → unauthorized") - func profileUnauthorized() async { - let mocked = await signedInAuth() - mocked.setHandler { _ in - (401, Data(#"{"error":"UNAUTHORIZED","status":401}"#.utf8)) - } - - await #expect(throws: AuthError.unauthorized) { - try await mocked.auth.getProfile() - } - } -} diff --git a/Tests/ManaCoreTests/AuthClientTwoFactorEnrollmentTests.swift b/Tests/ManaCoreTests/AuthClientTwoFactorEnrollmentTests.swift deleted file mode 100644 index b749c28..0000000 --- a/Tests/ManaCoreTests/AuthClientTwoFactorEnrollmentTests.swift +++ /dev/null @@ -1,119 +0,0 @@ -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") - } -}