Compare commits
4 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
216d9f8c65 | ||
|
|
fe607c15d2 | ||
|
|
0a79083b58 | ||
|
|
7526b807da |
7 changed files with 795 additions and 0 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -5,3 +5,4 @@
|
||||||
Package.resolved
|
Package.resolved
|
||||||
xcuserdata/
|
xcuserdata/
|
||||||
DerivedData/
|
DerivedData/
|
||||||
|
build/
|
||||||
|
|
|
||||||
91
CHANGELOG.md
91
CHANGELOG.md
|
|
@ -4,6 +4,97 @@ 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.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
|
||||||
|
TOTP-2FA können sich jetzt nativ einloggen. Komplett additiv.
|
||||||
|
|
||||||
|
### ManaCore — 2FA-Login
|
||||||
|
|
||||||
|
- `AuthClient.Status.twoFactorRequired(token: String, methods: [String], email: String)`
|
||||||
|
als neuer Case. Tritt nach `signIn(...)` auf, wenn der Account 2FA
|
||||||
|
aktiviert hat. `token` ist der opaque `two_factor`-Cookie-Wert vom
|
||||||
|
Server, den die App bei `verifyTotp(...)` zurückschickt.
|
||||||
|
- `AuthClient.verifyTotp(code:trustDevice:)` — verifiziert 6-stelligen
|
||||||
|
TOTP-Code. Bei Erfolg `.signedIn`, bei Fehler bleibt der Status im
|
||||||
|
Challenge (User kann retry).
|
||||||
|
- `AuthClient.verifyBackupCode(code:trustDevice:)` — Fallback wenn das
|
||||||
|
TOTP-Gerät verloren wurde. Backup-Codes sind einmalig.
|
||||||
|
- `signIn(...)` erkennt den Server-Pfad `{twoFactorRequired: true, ...}`
|
||||||
|
und routet automatisch zu `.twoFactorRequired`.
|
||||||
|
|
||||||
|
### Server-Side Voraussetzung
|
||||||
|
|
||||||
|
Setzt zwei neue Custom-Endpoints in `mana-auth` voraus:
|
||||||
|
- `POST /api/v1/auth/two-factor/verify-totp`
|
||||||
|
- `POST /api/v1/auth/two-factor/verify-backup-code`
|
||||||
|
|
||||||
|
Plus die `/api/v1/auth/login`-Erweiterung um den `twoFactorRequired`-
|
||||||
|
Pfad. Siehe `mana/services/mana-auth/src/routes/auth.ts`.
|
||||||
|
|
||||||
|
### Tests
|
||||||
|
|
||||||
|
- 5 neue Tests (signIn-Redirect, verifyTotp-Success/-Fail, ohne-Challenge-
|
||||||
|
Guard, verifyBackupCode). 59/59 grün.
|
||||||
|
|
||||||
|
### Bewusst NICHT in v1.3.0
|
||||||
|
|
||||||
|
- 2FA-**Enrollment** (TOTP-Setup) — eigener Mini-Sprint B mit
|
||||||
|
`enrollTotp()`, `disableTotp()`, `regenerateBackupCodes()`.
|
||||||
|
- Magic-Link, Passkey — eigene Sprints.
|
||||||
|
|
||||||
## [1.2.0] — 2026-05-13
|
## [1.2.0] — 2026-05-13
|
||||||
|
|
||||||
Minor — Guest-Mode + Auth-Resilience. Native-Apps werden gegen mana-auth-
|
Minor — Guest-Mode + Auth-Resilience. Native-Apps werden gegen mana-auth-
|
||||||
|
|
|
||||||
|
|
@ -388,3 +388,348 @@ private struct ChangePasswordRequest: Encodable {
|
||||||
private struct DeleteAccountRequest: Encodable {
|
private struct DeleteAccountRequest: Encodable {
|
||||||
let password: String
|
let password: String
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - Two-Factor (Login-Challenge)
|
||||||
|
|
||||||
|
public extension AuthClient {
|
||||||
|
/// Verifiziert einen TOTP-Code im 2FA-Login-Flow. Vorbedingung:
|
||||||
|
/// Status ist ``Status/twoFactorRequired(token:methods:email:)``
|
||||||
|
/// (typisch nach `signIn(...)`).
|
||||||
|
///
|
||||||
|
/// Bei Erfolg setzt der Server die Session, ManaCore persistiert
|
||||||
|
/// Tokens und der Status wird `.signedIn(email:)`.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - code: 6-stelliger TOTP-Code aus der Authenticator-App.
|
||||||
|
/// - trustDevice: Wenn `true`, setzt der Server einen
|
||||||
|
/// `trust_device`-Cookie. Bei Native heute ohne Effekt
|
||||||
|
/// (Cookies werden nicht persistiert) — wir spiegeln das Flag
|
||||||
|
/// trotzdem für künftige Erweiterungen.
|
||||||
|
///
|
||||||
|
/// - Throws: ``AuthError/twoFactorFailed`` bei falschem Code,
|
||||||
|
/// ``AuthError/tokenExpired`` wenn der Challenge-Token alt ist,
|
||||||
|
/// plus Standard-Netzwerk-Fehler.
|
||||||
|
func verifyTotp(code: String, trustDevice: Bool = false) async throws {
|
||||||
|
try await verifyTwoFactor(
|
||||||
|
path: "/api/v1/auth/two-factor/verify-totp",
|
||||||
|
code: code,
|
||||||
|
trustDevice: trustDevice
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verifiziert einen Backup-Code im 2FA-Login-Flow. Same Pre-/
|
||||||
|
/// Postconditions wie ``verifyTotp(code:trustDevice:)`` — der
|
||||||
|
/// Server entscheidet anhand des Endpoints, welches Verfahren er
|
||||||
|
/// nutzt. Backup-Codes werden vom Server beim Setup generiert
|
||||||
|
/// und einmalig konsumiert.
|
||||||
|
func verifyBackupCode(code: String, trustDevice: Bool = false) async throws {
|
||||||
|
try await verifyTwoFactor(
|
||||||
|
path: "/api/v1/auth/two-factor/verify-backup-code",
|
||||||
|
code: code,
|
||||||
|
trustDevice: trustDevice
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func verifyTwoFactor(
|
||||||
|
path: String,
|
||||||
|
code: String,
|
||||||
|
trustDevice: Bool
|
||||||
|
) async throws {
|
||||||
|
guard case let .twoFactorRequired(token, _, email) = status else {
|
||||||
|
throw AuthError.validation(
|
||||||
|
message: "Kein 2FA-Challenge aktiv — verifyTotp setzt eine vorherige signIn-Antwort mit .twoFactorRequired voraus"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
guard !code.isEmpty else {
|
||||||
|
throw AuthError.validation(message: "Code ist erforderlich")
|
||||||
|
}
|
||||||
|
|
||||||
|
let body = TwoFactorVerifyRequest(
|
||||||
|
code: code,
|
||||||
|
twoFactorToken: token,
|
||||||
|
trustDevice: trustDevice
|
||||||
|
)
|
||||||
|
let (data, http) = try await postJSON(path: path, body: body)
|
||||||
|
guard http.statusCode == 200 else {
|
||||||
|
throw AuthError.classify(
|
||||||
|
status: http.statusCode,
|
||||||
|
data: data,
|
||||||
|
retryAfterHeader: http.retryAfterSeconds
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
let token2 = try JSONDecoder().decode(TwoFactorVerifyResponse.self, from: data)
|
||||||
|
guard let access = token2.accessToken, let refresh = token2.refreshToken else {
|
||||||
|
// Server hat 200 zurück, aber keine Tokens. Sollte nicht
|
||||||
|
// passieren — UI bleibt im 2FA-Required-Zustand.
|
||||||
|
throw AuthError.decoding("Tokens fehlen in 2FA-Verify-Antwort")
|
||||||
|
}
|
||||||
|
|
||||||
|
try persistSession(email: email, accessToken: access, refreshToken: refresh)
|
||||||
|
CoreLog.auth.info("2FA verify successful — signed in")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct TwoFactorVerifyRequest: Encodable {
|
||||||
|
let code: String
|
||||||
|
let twoFactorToken: String
|
||||||
|
let trustDevice: Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct TwoFactorVerifyResponse: Decodable {
|
||||||
|
let success: Bool?
|
||||||
|
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?
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -28,6 +28,14 @@ public final class AuthClient {
|
||||||
/// Status erreichbar; schreibende Endpoints nicht.
|
/// Status erreichbar; schreibende Endpoints nicht.
|
||||||
case guest(id: String)
|
case guest(id: String)
|
||||||
case signingIn
|
case signingIn
|
||||||
|
/// Sign-In war erfolgreich aber der Account hat 2FA aktiviert.
|
||||||
|
/// UI fragt nun den TOTP-Code (oder einen Backup-Code) ab und
|
||||||
|
/// ruft `verifyTotp(code:trustDevice:)` / `verifyBackupCode(...)`
|
||||||
|
/// mit dem hier gespeicherten Token auf.
|
||||||
|
///
|
||||||
|
/// `token` ist der Better-Auth-`two_factor`-Cookie-Wert, vom
|
||||||
|
/// Server in der Login-Response als `twoFactorToken` mitgeliefert.
|
||||||
|
case twoFactorRequired(token: String, methods: [String], email: String)
|
||||||
case signedIn(email: String)
|
case signedIn(email: String)
|
||||||
case error(String)
|
case error(String)
|
||||||
}
|
}
|
||||||
|
|
@ -160,6 +168,23 @@ public final class AuthClient {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 2FA-Pfad: Server hat statt Tokens einen
|
||||||
|
// `twoFactorRequired`-Response geliefert. UI muss jetzt
|
||||||
|
// den TOTP-Code abfragen und `verifyTotp(...)` aufrufen.
|
||||||
|
if let twoFactor = try? JSONDecoder().decode(TwoFactorChallenge.self, from: data),
|
||||||
|
twoFactor.twoFactorRequired == true,
|
||||||
|
let tfToken = twoFactor.twoFactorToken
|
||||||
|
{
|
||||||
|
status = .twoFactorRequired(
|
||||||
|
token: tfToken,
|
||||||
|
methods: twoFactor.twoFactorMethods ?? ["totp"],
|
||||||
|
email: trimmed
|
||||||
|
)
|
||||||
|
lastError = nil
|
||||||
|
CoreLog.auth.info("Sign-in needs 2FA challenge")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
let token = try JSONDecoder().decode(TokenResponse.self, from: data)
|
let token = try JSONDecoder().decode(TokenResponse.self, from: data)
|
||||||
try keychain.setString(token.accessToken, for: .accessToken)
|
try keychain.setString(token.accessToken, for: .accessToken)
|
||||||
try keychain.setString(token.refreshToken, for: .refreshToken)
|
try keychain.setString(token.refreshToken, for: .refreshToken)
|
||||||
|
|
@ -339,6 +364,16 @@ struct TokenResponse: Decodable {
|
||||||
let refreshToken: String
|
let refreshToken: String
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 2FA-Pfad aus `/api/v1/auth/login`. Wenn `twoFactorRequired == true`,
|
||||||
|
/// kein Token-Paar — UI muss `verifyTotp(...)` / `verifyBackupCode(...)`
|
||||||
|
/// aufrufen. `twoFactorToken` ist der Server-injecten `two_factor`-Cookie-
|
||||||
|
/// Wert (opaque).
|
||||||
|
struct TwoFactorChallenge: Decodable {
|
||||||
|
let twoFactorRequired: Bool?
|
||||||
|
let twoFactorMethods: [String]?
|
||||||
|
let twoFactorToken: String?
|
||||||
|
}
|
||||||
|
|
||||||
extension HTTPURLResponse {
|
extension HTTPURLResponse {
|
||||||
/// Liest `Retry-After` als Anzahl Sekunden. Server schickt Integer-
|
/// Liest `Retry-After` als Anzahl Sekunden. Server schickt Integer-
|
||||||
/// Sekunden (siehe `lib/auth-errors.ts`). HTTP-Datum-Variante wird
|
/// Sekunden (siehe `lib/auth-errors.ts`). HTTP-Datum-Variante wird
|
||||||
|
|
|
||||||
77
Tests/ManaCoreTests/AuthClientProfileTests.swift
Normal file
77
Tests/ManaCoreTests/AuthClientProfileTests.swift
Normal file
|
|
@ -0,0 +1,77 @@
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
119
Tests/ManaCoreTests/AuthClientTwoFactorEnrollmentTests.swift
Normal file
119
Tests/ManaCoreTests/AuthClientTwoFactorEnrollmentTests.swift
Normal 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")
|
||||||
|
}
|
||||||
|
}
|
||||||
127
Tests/ManaCoreTests/AuthClientTwoFactorTests.swift
Normal file
127
Tests/ManaCoreTests/AuthClientTwoFactorTests.swift
Normal file
|
|
@ -0,0 +1,127 @@
|
||||||
|
import Foundation
|
||||||
|
import Testing
|
||||||
|
@testable import ManaCore
|
||||||
|
|
||||||
|
@Suite("AuthClient 2FA-Login-Challenge")
|
||||||
|
@MainActor
|
||||||
|
struct AuthClientTwoFactorTests {
|
||||||
|
@Test("signIn mit 2FA-Account → .twoFactorRequired statt .signedIn")
|
||||||
|
func signInRedirectsToTwoFactor() async {
|
||||||
|
let mocked = makeMockedAuth()
|
||||||
|
mocked.setHandler { _ in
|
||||||
|
(200, Data(#"""
|
||||||
|
{"twoFactorRequired":true,"twoFactorMethods":["totp"],"twoFactorToken":"tf-abc123"}
|
||||||
|
"""#.utf8))
|
||||||
|
}
|
||||||
|
|
||||||
|
await mocked.auth.signIn(email: "u@x.de", password: "pw")
|
||||||
|
if case let .twoFactorRequired(token, methods, email) = mocked.auth.status {
|
||||||
|
#expect(token == "tf-abc123")
|
||||||
|
#expect(methods == ["totp"])
|
||||||
|
#expect(email == "u@x.de")
|
||||||
|
} else {
|
||||||
|
Issue.record("Expected .twoFactorRequired, got \(mocked.auth.status)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("verifyTotp erfolgreich → .signedIn")
|
||||||
|
func verifyTotpSuccess() async throws {
|
||||||
|
let mocked = makeMockedAuth()
|
||||||
|
// Schritt 1: signIn liefert 2FA-Challenge.
|
||||||
|
mocked.setHandler { _ in
|
||||||
|
(200, Data(#"""
|
||||||
|
{"twoFactorRequired":true,"twoFactorMethods":["totp"],"twoFactorToken":"tf-xyz"}
|
||||||
|
"""#.utf8))
|
||||||
|
}
|
||||||
|
await mocked.auth.signIn(email: "u@x.de", password: "pw")
|
||||||
|
|
||||||
|
// Schritt 2: verifyTotp liefert Tokens.
|
||||||
|
let access = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
|
||||||
|
let captured = MockURLProtocol.Capture()
|
||||||
|
mocked.setHandler { request in
|
||||||
|
captured.store(request)
|
||||||
|
return (200, Data(#"""
|
||||||
|
{"success":true,"accessToken":"\#(access)","refreshToken":"r1"}
|
||||||
|
"""#.utf8))
|
||||||
|
}
|
||||||
|
|
||||||
|
try await mocked.auth.verifyTotp(code: "123456")
|
||||||
|
#expect(mocked.auth.status == .signedIn(email: "u@x.de"))
|
||||||
|
|
||||||
|
let request = try #require(captured.request)
|
||||||
|
#expect(request.url?.path == "/api/v1/auth/two-factor/verify-totp")
|
||||||
|
// Body trägt code + twoFactorToken aus dem Challenge-Status
|
||||||
|
let body = request.httpBody ?? request.bodyStreamData() ?? Data()
|
||||||
|
let json = try JSONSerialization.jsonObject(with: body) as? [String: Any] ?? [:]
|
||||||
|
#expect(json["code"] as? String == "123456")
|
||||||
|
#expect(json["twoFactorToken"] as? String == "tf-xyz")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("verifyTotp ohne aktiven 2FA-Challenge wirft validation")
|
||||||
|
func verifyTotpRequiresChallenge() async {
|
||||||
|
let mocked = makeMockedAuth()
|
||||||
|
// Status ist initial .unknown — kein 2FA-Challenge.
|
||||||
|
do {
|
||||||
|
try await mocked.auth.verifyTotp(code: "123456")
|
||||||
|
Issue.record("Expected throw")
|
||||||
|
} catch let AuthError.validation(message) {
|
||||||
|
#expect(message?.contains("2FA-Challenge") == true)
|
||||||
|
} catch {
|
||||||
|
Issue.record("Unexpected error: \(error)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("verifyTotp mit falschem Code → twoFactorFailed, bleibt im Challenge")
|
||||||
|
func verifyTotpWrongCode() async {
|
||||||
|
let mocked = makeMockedAuth()
|
||||||
|
mocked.setHandler { _ in
|
||||||
|
(200, Data(#"""
|
||||||
|
{"twoFactorRequired":true,"twoFactorMethods":["totp"],"twoFactorToken":"tf-xyz"}
|
||||||
|
"""#.utf8))
|
||||||
|
}
|
||||||
|
await mocked.auth.signIn(email: "u@x.de", password: "pw")
|
||||||
|
|
||||||
|
mocked.setHandler { _ in
|
||||||
|
(401, Data(#"{"error":"TWO_FACTOR_FAILED","status":401}"#.utf8))
|
||||||
|
}
|
||||||
|
|
||||||
|
do {
|
||||||
|
try await mocked.auth.verifyTotp(code: "000000")
|
||||||
|
Issue.record("Expected throw")
|
||||||
|
} catch AuthError.twoFactorFailed {
|
||||||
|
// Status bleibt im Challenge — User kann erneut versuchen
|
||||||
|
if case .twoFactorRequired = mocked.auth.status {
|
||||||
|
#expect(Bool(true))
|
||||||
|
} else {
|
||||||
|
Issue.record("Status should remain .twoFactorRequired, got \(mocked.auth.status)")
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
Issue.record("Unexpected error: \(error)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("verifyBackupCode erfolgreich → .signedIn")
|
||||||
|
func verifyBackupCodeSuccess() async throws {
|
||||||
|
let mocked = makeMockedAuth()
|
||||||
|
mocked.setHandler { _ in
|
||||||
|
(200, Data(#"""
|
||||||
|
{"twoFactorRequired":true,"twoFactorMethods":["totp"],"twoFactorToken":"tf-xyz"}
|
||||||
|
"""#.utf8))
|
||||||
|
}
|
||||||
|
await mocked.auth.signIn(email: "u@x.de", password: "pw")
|
||||||
|
|
||||||
|
let access = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
|
||||||
|
let captured = MockURLProtocol.Capture()
|
||||||
|
mocked.setHandler { request in
|
||||||
|
captured.store(request)
|
||||||
|
return (200, Data(#"""
|
||||||
|
{"success":true,"accessToken":"\#(access)","refreshToken":"r1"}
|
||||||
|
"""#.utf8))
|
||||||
|
}
|
||||||
|
|
||||||
|
try await mocked.auth.verifyBackupCode(code: "abc-def-ghi")
|
||||||
|
#expect(mocked.auth.status == .signedIn(email: "u@x.de"))
|
||||||
|
let request = try #require(captured.request)
|
||||||
|
#expect(request.url?.path == "/api/v1/auth/two-factor/verify-backup-code")
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue