Compare commits
8 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
216d9f8c65 | ||
|
|
fe607c15d2 | ||
|
|
0a79083b58 | ||
|
|
7526b807da | ||
|
|
923b5d06b5 | ||
|
|
3459c78731 | ||
|
|
716509e10e | ||
|
|
74aee8d47f |
14 changed files with 2574 additions and 42 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -5,3 +5,4 @@
|
|||
Package.resolved
|
||||
xcuserdata/
|
||||
DerivedData/
|
||||
build/
|
||||
|
|
|
|||
273
CHANGELOG.md
273
CHANGELOG.md
|
|
@ -4,6 +4,279 @@ 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
|
||||
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
|
||||
|
||||
Minor — Guest-Mode + Auth-Resilience. Native-Apps werden gegen mana-auth-
|
||||
Downtime gehärtet und können jetzt einen anonymen Local-First-Modus
|
||||
anbieten. Komplett additiv — keine Breaking Changes für bestehende
|
||||
Konsumenten (Memoro, Cards, Manaspur, Nutriphi).
|
||||
|
||||
### ManaCore — Guest-Identität
|
||||
|
||||
- `AuthClient.Status` um Case `.guest(id: String)` erweitert. Persistente
|
||||
lokale UUID ohne Server-Account; gleichberechtigt mit `.signedIn` als
|
||||
„App ist nutzbar"-Zustand. Apps können in diesem Modus alles Lokale
|
||||
und alle unauthenticated-Server-Endpoints anbieten, schreibende
|
||||
Endpoints poppen Auth-Sheet.
|
||||
- `AuthClient.enterGuestMode() throws -> String` — idempotent, erzeugt
|
||||
oder reuse die Guest-UUID aus Keychain. Wechselt den Status nur,
|
||||
wenn aktuell `.signedOut`/`.unknown` (eine aktive Session bleibt
|
||||
unangetastet, App kann die Guest-ID parallel lesen).
|
||||
- `AuthClient.currentGuestId() -> String?` — Lookup unabhängig vom Status.
|
||||
Genutzt z.B. um lokale Guest-Daten beim Sign-In dem neuen Server-
|
||||
Account zuzuordnen.
|
||||
- `AuthClient.clearGuestId()` — entfernt die Guest-ID, etwa nach
|
||||
erfolgreicher Migration der lokalen Daten auf einen Server-Account.
|
||||
- `AuthClient.signOut(keepGuestMode: Bool = false)` — Default-Verhalten
|
||||
unverändert (`false` löscht alles, Status `.signedOut`). Mit `true`
|
||||
bleibt die App im anonymen Modus weiter nutzbar.
|
||||
- `KeychainStore.Key.guestId` als neuer Key. `wipe()` löscht jetzt
|
||||
*nur* Session-Felder (accessToken/refreshToken/email) — die Guest-ID
|
||||
überlebt. Für komplettes Vergessen: neue `wipeAll()`.
|
||||
|
||||
### ManaCore — Refresh-Resilience
|
||||
|
||||
- `refreshAccessToken()` wipt nicht mehr blind den Keychain bei jedem
|
||||
Nicht-200. Stattdessen Heuristik via `AuthError.invalidatesSession`:
|
||||
- **Wipe** bei `.invalidCredentials`, `.unauthorized`, `.tokenExpired`,
|
||||
`.tokenInvalid`, `.emailNotVerified` — Session ist tatsächlich tot.
|
||||
- **Behalten** bei `.serviceUnavailable` (503), `.serverInternal`
|
||||
(500), `.networkFailure`, `.rateLimited`, weiteren transienten
|
||||
Fehlern. Apps werden bei mana-auth-Downtime nicht mehr in den
|
||||
Login-Screen geworfen.
|
||||
- Beim Wipe-Pfad fällt der Status auf `.guest(id)` zurück, falls eine
|
||||
Guest-Identität existiert; sonst auf `.signedOut`.
|
||||
- `AuthError.invalidatesSession: Bool` — public computed Property,
|
||||
auch von Apps direkt nutzbar (z.B. um auf Transport-Fehler zu
|
||||
reagieren).
|
||||
|
||||
### Tests
|
||||
|
||||
- 15 neue Tests: Guest-Mode (Idempotenz, Bootstrap-Priorität, Status-
|
||||
Übergänge), signOut(keepGuestMode:) in beiden Modi, Refresh-Verhalten
|
||||
bei 401/429/500/503/Network, invalidatesSession-Partitionierung.
|
||||
|
||||
### Migration für Apps
|
||||
|
||||
Bestehende Apps brauchen **keine** Änderung — Default-Verhalten ist
|
||||
identisch. Wer den anonymen Modus nutzen will:
|
||||
|
||||
```swift
|
||||
// Beim App-Start nach bootstrap():
|
||||
auth.bootstrap()
|
||||
if case .signedOut = auth.status {
|
||||
try? auth.enterGuestMode() // Statt sofort Login-Screen
|
||||
}
|
||||
|
||||
// In Aktionen, die einen Account brauchen:
|
||||
guard case .signedIn = auth.status else {
|
||||
presentLoginSheet()
|
||||
return
|
||||
}
|
||||
```
|
||||
|
||||
## [1.1.1] — 2026-05-13
|
||||
|
||||
Patch — Wire-Konvention für authenticated Account-Calls geklärt.
|
||||
|
||||
### Geändert
|
||||
|
||||
- `AuthClient.changeEmail`, `changePassword`, `deleteAccount` senden
|
||||
jetzt den Session-Token (`refreshToken`-Feldwert) statt des JWT als
|
||||
`Authorization: Bearer`. Hintergrund: Server-seitig wurde in
|
||||
`mana-auth` Better Auths `bearer`-Plugin aktiviert
|
||||
(`requireSignature: false`), das Session-Tokens zu Session-Cookies
|
||||
konvertiert. Damit funktionieren `auth.api.changeEmail` etc. für
|
||||
Native-Apps ohne Cookie-Container.
|
||||
- `AuthClient.currentSessionToken()` als public Helper hinzu. Symmetrisch
|
||||
zu `currentAccessToken()`.
|
||||
|
||||
### Trade-Off bewusst akzeptiert
|
||||
|
||||
Session-Token wird bei jedem Account-Call versendet (vorher nur beim
|
||||
`/refresh`). Mit TLS-Baseline akzeptables Risiko; Compromise-Surface
|
||||
nicht relevant größer als JWT-Leak. Alternative wäre ein Custom-
|
||||
Bearer-JWT-to-Cookie-Resolver im Server (40+ Zeilen Hono-Middleware,
|
||||
HMAC-Cookie-Synthese) — bewusst nicht gewählt, weil der bearer-Plugin
|
||||
genau für diesen Use-Case existiert.
|
||||
|
||||
### Tests
|
||||
|
||||
- Test `changePassword schickt Bearer-Header` umbenannt auf
|
||||
`schickt Session-Token als Bearer (nicht JWT)` und geupdated.
|
||||
|
||||
## [1.1.0] — 2026-05-13
|
||||
|
||||
Phase 1 aus dem Native-Auth-Vollausbau-Plan (Option A — alles nativ,
|
||||
siehe `mana/docs/MANA_SWIFT.md`). Erweitert `ManaCore` um die
|
||||
Account-Lifecycle-Methoden, die jede native Verein-App für eine
|
||||
vollständige Auth-Reise braucht.
|
||||
|
||||
### ManaCore — Neue API (additiv, keine Breaking Changes)
|
||||
|
||||
- `AuthClient.register(email:password:name:sourceAppUrl:)` — Sign-Up
|
||||
gegen `POST /api/v1/auth/register`. Persistiert eine Session
|
||||
automatisch, wenn der Server Tokens mitliefert; sonst still und
|
||||
wartend auf Email-Verifikation.
|
||||
- `AuthClient.forgotPassword(email:resetUniversalLink:)` — Passwort-
|
||||
Reset-Mail anfordern gegen `POST /api/v1/auth/forgot-password`.
|
||||
Server antwortet immer 200 (keine User-Enumeration).
|
||||
- `AuthClient.resetPassword(token:newPassword:)` — Passwort mit Token
|
||||
aus Reset-Mail setzen.
|
||||
- `AuthClient.resendVerification(email:sourceAppUrl:)` — Verify-Mail
|
||||
erneut versenden, aufzurufen nach ``AuthError/emailNotVerified``.
|
||||
- `AuthClient.changeEmail(newEmail:callbackUniversalLink:)` — Email
|
||||
ändern (verschickt Verify-Mail an neue Adresse). **Aktuell server-
|
||||
seitig nicht Bearer-fähig** — siehe Doc-Header von
|
||||
`AuthClient+Account.swift`.
|
||||
- `AuthClient.changePassword(currentPassword:newPassword:)` — Passwort
|
||||
ändern. Gleiche Bearer-Einschränkung wie `changeEmail`.
|
||||
- `AuthClient.deleteAccount(password:)` — Account löschen
|
||||
(App-Store-Guideline 5.1.1(v) Pflicht). Wiped Keychain bei Erfolg.
|
||||
Gleiche Bearer-Einschränkung wie oben.
|
||||
|
||||
### ManaCore — `AuthError` ausgebaut
|
||||
|
||||
- Präzise Cases pro Server-`AuthErrorCode`: `.emailNotVerified`,
|
||||
`.emailAlreadyRegistered`, `.weakPassword(message:)`,
|
||||
`.accountLocked(retryAfter:)`, `.signupLimitReached`,
|
||||
`.rateLimited(retryAfter:)`, `.tokenExpired`, `.tokenInvalid`,
|
||||
`.twoFactorRequired`, `.twoFactorFailed`, `.passkeyNotEnabled`,
|
||||
`.passkeyCancelled`, `.passkeyVerificationFailed`,
|
||||
`.validation(message:)`, `.unauthorized`, `.notFound`,
|
||||
`.serviceUnavailable`, `.serverInternal`.
|
||||
- `AuthError.classify(status:data:retryAfterHeader:)` — public,
|
||||
klassifiziert mana-auth-Fehler-Antworten in den passenden Case.
|
||||
Auch genutzt von `signIn` und `refreshAccessToken` (vorher: einfache
|
||||
`.error(String)`-Strings).
|
||||
- `AuthError` ist jetzt `Equatable` — erleichtert UI-Logik und Tests.
|
||||
- Alte Cases `.invalidCredentials`, `.networkFailure`, `.encoding`,
|
||||
`.keychain`, `.decoding`, `.notSignedIn` bleiben unverändert.
|
||||
- **Breaking-Vermeidung:** `serverError(status:message:)` wurde zu
|
||||
`serverError(status:code:message:)` (zusätzliches `code`-Argument).
|
||||
Theoretisch breaking, praktisch nutzt es niemand außerhalb von
|
||||
ManaCore selbst. Wenn ein App-Konsument darauf gepattern-matched
|
||||
hat, ist das ein Compile-Fehler, kein Runtime-Bug.
|
||||
|
||||
### Tests
|
||||
|
||||
- 14 neue Tests für `AuthError.classify` (jeder ErrorCode + Status-
|
||||
Heuristik + Retry-After-Header + kaputter Body).
|
||||
- 12 neue Tests für die neuen `AuthClient`-Methoden via
|
||||
`URLProtocol`-Mock (Wire-Format, Status-Mapping, Bearer-Header,
|
||||
Session-Persistenz bei `register`, Session-Wipe bei `deleteAccount`).
|
||||
|
||||
### Bekannte Einschränkungen
|
||||
|
||||
- `changeEmail`, `changePassword`, `deleteAccount` brauchen Server-
|
||||
seitig den `bearer`-Plugin von Better Auth oder einen Custom-
|
||||
Bearer-Resolver. Heute mountet `mana-auth` nur den Cookie-Pfad.
|
||||
Phase-3-Server-PR im `mana`-Repo dokumentiert.
|
||||
- 2FA-Verify, Magic-Link und Passkey-Flows sind in dieser Version
|
||||
bewusst NICHT enthalten. Laufen Server-seitig über Better-Auth-
|
||||
Native (`/api/auth/*`, Cookie) und brauchen eigene JWT-Pfade.
|
||||
Folgt in v1.2.0 zusammen mit dem Server-PR.
|
||||
|
||||
## [1.0.1] — 2026-05-13
|
||||
|
||||
### Behoben
|
||||
|
||||
- `AuthenticatedTransport`: `URL.appending(path:)` URL-encoded das `?`
|
||||
in Query-Strings zu `%3F`, was den Server-Route-Match brechen ließ
|
||||
(404 für `/healthz?…`). Ersetzt durch String-Concat; Caller liefert
|
||||
den Path inkl. führendem `/` und optionaler Query.
|
||||
|
||||
## [1.0.0] — 2026-05-12
|
||||
|
||||
Initiale Extraktion aus `memoro-native` (Phase α aus
|
||||
|
|
|
|||
|
|
@ -40,7 +40,15 @@ public actor AuthenticatedTransport {
|
|||
contentType: String,
|
||||
token: String
|
||||
) async throws -> (Data, HTTPURLResponse) {
|
||||
var request = URLRequest(url: baseURL.appending(path: path))
|
||||
// String-Konkatenation statt `baseURL.appending(path:)`, weil
|
||||
// letzteres das `?` in Query-Strings als Path-Component
|
||||
// behandelt und URL-encoded (`?` → `%3F`) — der Server-Routes-
|
||||
// Match scheitert dann mit 404. Caller liefert path inkl.
|
||||
// führendem `/` und optionaler Query.
|
||||
guard let url = URL(string: baseURL.absoluteString + path) else {
|
||||
throw AuthError.networkFailure("Ungültige URL: \(path)")
|
||||
}
|
||||
var request = URLRequest(url: url)
|
||||
request.httpMethod = method
|
||||
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
||||
if let body {
|
||||
|
|
|
|||
735
Sources/ManaCore/Auth/AuthClient+Account.swift
Normal file
735
Sources/ManaCore/Auth/AuthClient+Account.swift
Normal file
|
|
@ -0,0 +1,735 @@
|
|||
import Foundation
|
||||
|
||||
/// Account-Lifecycle-Methoden: Registrierung, Passwort-Reset,
|
||||
/// Email-Verifikation, Account-Management.
|
||||
///
|
||||
/// Diese Methoden ergänzen die Login-/Refresh-Maschine in ``AuthClient``
|
||||
/// um die Flows, die eine native App für eine vollständige Auth-Reise
|
||||
/// braucht (vergleichbar mit `mana-auth-web` aber API-basiert statt
|
||||
/// Cookie-basiert).
|
||||
///
|
||||
/// **Server-Endpoints (alle JSON, alle unter `/api/v1/auth/*`):**
|
||||
/// - `POST /register` — Sign-Up + (je nach Config) email-verify-required
|
||||
/// - `POST /forgot-password` — Reset-Mail anfordern (immer 200, kein Enum-Leak)
|
||||
/// - `POST /reset-password` — neues PW mit Token aus Reset-Mail
|
||||
/// - `POST /resend-verification` — Verify-Mail erneut senden
|
||||
/// - `POST /change-email` — Email ändern (verschickt Verify-Mail an neue Adresse)
|
||||
/// - `POST /change-password` — Passwort ändern (current + new)
|
||||
/// - `DELETE /account` — Account löschen (App-Store-Pflicht 5.1.1(v))
|
||||
///
|
||||
/// **Wire-Konvention für authenticated Account-Calls:**
|
||||
/// `change-email`, `change-password` und `DELETE /account` forwarden
|
||||
/// die Original-Request-Headers an Better Auth (`auth.api.changeEmail`
|
||||
/// etc.). Better Auth's `bearer`-Plugin (seit 2026-05-13 in mana-auth
|
||||
/// aktiv) konvertiert `Authorization: Bearer <session-token>` in
|
||||
/// einen synthetischen Session-Cookie. **Native-Apps senden hier den
|
||||
/// Session-Token (`refreshToken`-Feldwert aus /login bzw. /refresh),
|
||||
/// NICHT den JWT.** Der JWT bleibt für app-eigene Backends
|
||||
/// (memoro-api, cardecky-api etc.) der richtige Header.
|
||||
///
|
||||
/// Trade-Off: Session-Token wird häufiger versendet als der reine
|
||||
/// Refresh-Pfad. Bei TLS-only-Baseline akzeptabel; Compromise-Surface
|
||||
/// nicht relevant größer als JWT-Leak.
|
||||
public extension AuthClient {
|
||||
// MARK: - Registrierung
|
||||
|
||||
/// Registriert einen neuen Account.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - email: Email-Adresse, wird als Login-Identifier genutzt.
|
||||
/// - password: Klartext-Passwort, Server hasht via Better Auth.
|
||||
/// - name: Anzeige-Name. Wenn nil, nutzt der Server den Email-Local-Part.
|
||||
/// - sourceAppUrl: Basis-URL für den Verify-Email-Klick-Redirect.
|
||||
/// Per-App-spezifisch — z.B. `https://cardecky.mana.how/auth/verify`
|
||||
/// für einen Universal-Link-Handler. Der Server hängt `?token=…` an.
|
||||
///
|
||||
/// Bei Erfolg ist mit Default-Server-Config (`requireEmailVerification: true`)
|
||||
/// noch **kein Login** gemacht — der User muss erst die Verify-Mail
|
||||
/// klicken. Ein anschließendes `signIn(...)` mit denselben Credentials
|
||||
/// liefert dann `.emailNotVerified` bis der Klick passiert.
|
||||
///
|
||||
/// Wenn der Server in der Antwort doch Tokens schickt (kann passieren
|
||||
/// wenn Email-Verifikation off ist), wird die Session persistiert und
|
||||
/// der Status auf `.signedIn` gesetzt.
|
||||
///
|
||||
/// - Throws: ``AuthError/emailAlreadyRegistered``,
|
||||
/// ``AuthError/weakPassword(message:)``, ``AuthError/signupLimitReached``,
|
||||
/// ``AuthError/validation(message:)`` und Netzwerk-Cases.
|
||||
func register(
|
||||
email: String,
|
||||
password: String,
|
||||
name: String? = nil,
|
||||
sourceAppUrl: URL? = nil
|
||||
) async throws {
|
||||
let trimmed = email.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty, !password.isEmpty else {
|
||||
throw AuthError.validation(message: "Email und Passwort sind erforderlich")
|
||||
}
|
||||
|
||||
let body = RegisterRequest(
|
||||
email: trimmed,
|
||||
password: password,
|
||||
name: name,
|
||||
sourceAppUrl: sourceAppUrl?.absoluteString
|
||||
)
|
||||
let (data, http) = try await postJSON(path: "/api/v1/auth/register", body: body)
|
||||
guard http.statusCode == 200 else {
|
||||
throw AuthError.classify(
|
||||
status: http.statusCode,
|
||||
data: data,
|
||||
retryAfterHeader: http.retryAfterSeconds
|
||||
)
|
||||
}
|
||||
|
||||
let decoded = try JSONDecoder().decode(RegisterResponse.self, from: data)
|
||||
if let access = decoded.accessToken, let refresh = decoded.refreshToken {
|
||||
try persistSession(email: trimmed, accessToken: access, refreshToken: refresh)
|
||||
CoreLog.auth.info("Register successful — auto-signed-in")
|
||||
} else {
|
||||
CoreLog.auth.info("Register successful — awaiting email verification")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Passwort-Reset
|
||||
|
||||
/// Fordert eine Passwort-Reset-Email an.
|
||||
///
|
||||
/// Der Server antwortet **immer mit 200**, unabhängig davon ob die
|
||||
/// Email existiert (bewusst, um User-Enumeration zu verhindern).
|
||||
/// Die UI sollte daher generisch melden ("Wenn dein Account existiert,
|
||||
/// ist eine Email unterwegs").
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - email: Email-Adresse des Accounts.
|
||||
/// - resetUniversalLink: Universal-Link der App, der die
|
||||
/// Reset-Seite öffnet. Z.B. `https://cardecky.mana.how/auth/reset`.
|
||||
/// Der Server hängt `?token=…` an und nutzt diesen Link im
|
||||
/// Mail-Template.
|
||||
///
|
||||
/// - Throws: nur Netzwerk-Fehler. Server-Fehler werden vom Server
|
||||
/// geschluckt (200 trotzdem).
|
||||
func forgotPassword(email: String, resetUniversalLink: URL) async throws {
|
||||
let trimmed = email.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty else {
|
||||
throw AuthError.validation(message: "Email ist erforderlich")
|
||||
}
|
||||
|
||||
let body = ForgotPasswordRequest(email: trimmed, redirectTo: resetUniversalLink.absoluteString)
|
||||
let (data, http) = try await postJSON(path: "/api/v1/auth/forgot-password", body: body)
|
||||
guard http.statusCode == 200 else {
|
||||
throw AuthError.classify(
|
||||
status: http.statusCode,
|
||||
data: data,
|
||||
retryAfterHeader: http.retryAfterSeconds
|
||||
)
|
||||
}
|
||||
CoreLog.auth.info("Password reset requested")
|
||||
}
|
||||
|
||||
/// Setzt das Passwort mit einem Reset-Token aus der Reset-Email.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - token: Reset-Token aus der Email (Query-Param `?token=…`).
|
||||
/// - newPassword: Neues Klartext-Passwort.
|
||||
///
|
||||
/// Nach Erfolg ist der User **nicht** automatisch eingeloggt — der
|
||||
/// `signIn(...)`-Call muss separat passieren.
|
||||
///
|
||||
/// - Throws: ``AuthError/tokenExpired``, ``AuthError/tokenInvalid``,
|
||||
/// ``AuthError/weakPassword(message:)`` und Netzwerk-Cases.
|
||||
func resetPassword(token: String, newPassword: String) async throws {
|
||||
guard !token.isEmpty, !newPassword.isEmpty else {
|
||||
throw AuthError.validation(message: "Token und neues Passwort sind erforderlich")
|
||||
}
|
||||
|
||||
let body = ResetPasswordRequest(token: token, newPassword: newPassword)
|
||||
let (data, http) = try await postJSON(path: "/api/v1/auth/reset-password", body: body)
|
||||
guard http.statusCode == 200 else {
|
||||
throw AuthError.classify(
|
||||
status: http.statusCode,
|
||||
data: data,
|
||||
retryAfterHeader: http.retryAfterSeconds
|
||||
)
|
||||
}
|
||||
CoreLog.auth.info("Password reset completed")
|
||||
}
|
||||
|
||||
// MARK: - Email-Verifikation
|
||||
|
||||
/// Sendet die Email-Verifikations-Mail erneut.
|
||||
///
|
||||
/// Aufzurufen wenn `signIn(...)` mit ``AuthError/emailNotVerified``
|
||||
/// zurückkommt — die UI bietet einen "Mail erneut senden"-Button.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - email: Email-Adresse des Accounts.
|
||||
/// - sourceAppUrl: Universal-Link für den Verify-Klick. Gleiche
|
||||
/// Semantik wie bei ``register(email:password:name:sourceAppUrl:)``.
|
||||
///
|
||||
/// - Throws: ``AuthError/notFound`` wenn die Email nicht existiert,
|
||||
/// ``AuthError/rateLimited(retryAfter:)`` bei zu vielen Versuchen.
|
||||
func resendVerification(email: String, sourceAppUrl: URL? = nil) async throws {
|
||||
let trimmed = email.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty else {
|
||||
throw AuthError.validation(message: "Email ist erforderlich")
|
||||
}
|
||||
|
||||
let body = ResendVerificationRequest(
|
||||
email: trimmed,
|
||||
sourceAppUrl: sourceAppUrl?.absoluteString
|
||||
)
|
||||
let (data, http) = try await postJSON(path: "/api/v1/auth/resend-verification", body: body)
|
||||
guard http.statusCode == 200 else {
|
||||
throw AuthError.classify(
|
||||
status: http.statusCode,
|
||||
data: data,
|
||||
retryAfterHeader: http.retryAfterSeconds
|
||||
)
|
||||
}
|
||||
CoreLog.auth.info("Verification email resent")
|
||||
}
|
||||
|
||||
// MARK: - Account-Management (erfordert eingeloggte Session)
|
||||
|
||||
/// Ändert die Email des aktuell eingeloggten Accounts.
|
||||
///
|
||||
/// Der Server schickt eine Verifikations-Mail an die **neue** Adresse.
|
||||
/// Bis der User klickt, bleibt die alte Email aktiv.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - newEmail: Neue Email-Adresse.
|
||||
/// - callbackUniversalLink: Universal-Link, der nach erfolgter
|
||||
/// Verifikation geöffnet wird (z.B.
|
||||
/// `https://cardecky.mana.how/auth/email-changed`).
|
||||
///
|
||||
/// - Important: Aktuell server-seitig nicht Bearer-fähig — siehe
|
||||
/// Doc-Header dieser Datei.
|
||||
func changeEmail(newEmail: String, callbackUniversalLink: URL? = nil) async throws {
|
||||
let trimmed = newEmail.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty else {
|
||||
throw AuthError.validation(message: "Neue Email ist erforderlich")
|
||||
}
|
||||
|
||||
let body = ChangeEmailRequest(
|
||||
newEmail: trimmed,
|
||||
callbackURL: callbackUniversalLink?.absoluteString
|
||||
)
|
||||
let (data, http) = try await postJSON(
|
||||
path: "/api/v1/auth/change-email",
|
||||
body: body,
|
||||
authenticated: true
|
||||
)
|
||||
guard http.statusCode == 200 else {
|
||||
throw AuthError.classify(
|
||||
status: http.statusCode,
|
||||
data: data,
|
||||
retryAfterHeader: http.retryAfterSeconds
|
||||
)
|
||||
}
|
||||
CoreLog.auth.info("Email change requested — verification email sent")
|
||||
}
|
||||
|
||||
/// Ändert das Passwort des aktuell eingeloggten Accounts.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - currentPassword: Aktuelles Klartext-Passwort (Re-Auth).
|
||||
/// - newPassword: Neues Klartext-Passwort.
|
||||
///
|
||||
/// - Important: Aktuell server-seitig nicht Bearer-fähig — siehe
|
||||
/// Doc-Header dieser Datei.
|
||||
func changePassword(currentPassword: String, newPassword: String) async throws {
|
||||
guard !currentPassword.isEmpty, !newPassword.isEmpty else {
|
||||
throw AuthError.validation(message: "Aktuelles und neues Passwort sind erforderlich")
|
||||
}
|
||||
|
||||
let body = ChangePasswordRequest(currentPassword: currentPassword, newPassword: newPassword)
|
||||
let (data, http) = try await postJSON(
|
||||
path: "/api/v1/auth/change-password",
|
||||
body: body,
|
||||
authenticated: true
|
||||
)
|
||||
guard http.statusCode == 200 else {
|
||||
throw AuthError.classify(
|
||||
status: http.statusCode,
|
||||
data: data,
|
||||
retryAfterHeader: http.retryAfterSeconds
|
||||
)
|
||||
}
|
||||
CoreLog.auth.info("Password changed")
|
||||
}
|
||||
|
||||
/// Löscht den aktuell eingeloggten Account vollständig.
|
||||
///
|
||||
/// Server löscht alle User-Daten (Auth, Credits, Sync-DB-Records).
|
||||
/// Bei Erfolg wird der lokale Keychain gewiped und der Status auf
|
||||
/// `.signedOut` gesetzt.
|
||||
///
|
||||
/// **App-Store-Pflicht 5.1.1(v):** jede App mit Account-Erstellung
|
||||
/// muss eine Account-Löschung anbieten.
|
||||
///
|
||||
/// - Parameter password: Aktuelles Klartext-Passwort als Re-Auth.
|
||||
///
|
||||
/// - Important: Aktuell server-seitig nicht Bearer-fähig — siehe
|
||||
/// Doc-Header dieser Datei.
|
||||
func deleteAccount(password: String) async throws {
|
||||
guard !password.isEmpty else {
|
||||
throw AuthError.validation(message: "Passwort ist erforderlich")
|
||||
}
|
||||
|
||||
let body = DeleteAccountRequest(password: password)
|
||||
let (data, http) = try await postJSON(
|
||||
path: "/api/v1/auth/account",
|
||||
method: "DELETE",
|
||||
body: body,
|
||||
authenticated: true
|
||||
)
|
||||
guard http.statusCode == 200 else {
|
||||
throw AuthError.classify(
|
||||
status: http.statusCode,
|
||||
data: data,
|
||||
retryAfterHeader: http.retryAfterSeconds
|
||||
)
|
||||
}
|
||||
clearSession()
|
||||
CoreLog.auth.notice("Account deleted")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private Helpers
|
||||
|
||||
extension AuthClient {
|
||||
/// Generischer JSON-POST/DELETE-Helper. Wenn `authenticated == true`,
|
||||
/// wird der Session-Token (`refreshToken`-Feldwert, von Better Auth
|
||||
/// als Session-ID interpretierbar via `bearer`-Plugin) als Bearer-
|
||||
/// Header mitgeschickt — NICHT der JWT. Siehe Doc-Header dieser Datei.
|
||||
fileprivate func postJSON<Body: Encodable>(
|
||||
path: String,
|
||||
method: String = "POST",
|
||||
body: Body,
|
||||
authenticated: Bool = false
|
||||
) async throws -> (Data, HTTPURLResponse) {
|
||||
let url = config.authBaseURL.appending(path: path)
|
||||
var request = URLRequest(url: url)
|
||||
request.httpMethod = method
|
||||
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
if authenticated {
|
||||
let token = try currentSessionToken()
|
||||
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
||||
}
|
||||
do {
|
||||
request.httpBody = try JSONEncoder().encode(body)
|
||||
} catch {
|
||||
throw AuthError.encoding
|
||||
}
|
||||
|
||||
do {
|
||||
let (data, response) = try await session.data(for: request)
|
||||
guard let http = response as? HTTPURLResponse else {
|
||||
throw AuthError.networkFailure("Keine HTTP-Antwort")
|
||||
}
|
||||
return (data, http)
|
||||
} catch let error as URLError {
|
||||
throw AuthError.networkFailure(error.localizedDescription)
|
||||
} catch let error as AuthError {
|
||||
throw error
|
||||
} catch {
|
||||
throw AuthError.networkFailure(String(describing: error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Wire-Format
|
||||
|
||||
private struct RegisterRequest: Encodable {
|
||||
let email: String
|
||||
let password: String
|
||||
let name: String?
|
||||
let sourceAppUrl: String?
|
||||
}
|
||||
|
||||
/// Server-Antwort auf `/register`. Tokens sind optional weil
|
||||
/// `requireEmailVerification: true` (Default) keine Session liefert.
|
||||
private struct RegisterResponse: Decodable {
|
||||
let user: RegisterUser?
|
||||
let accessToken: String?
|
||||
let refreshToken: String?
|
||||
}
|
||||
|
||||
private struct RegisterUser: Decodable {
|
||||
let id: String
|
||||
let email: String?
|
||||
}
|
||||
|
||||
private struct ForgotPasswordRequest: Encodable {
|
||||
let email: String
|
||||
let redirectTo: String
|
||||
}
|
||||
|
||||
private struct ResetPasswordRequest: Encodable {
|
||||
let token: String
|
||||
let newPassword: String
|
||||
}
|
||||
|
||||
private struct ResendVerificationRequest: Encodable {
|
||||
let email: String
|
||||
let sourceAppUrl: String?
|
||||
}
|
||||
|
||||
private struct ChangeEmailRequest: Encodable {
|
||||
let newEmail: String
|
||||
let callbackURL: String?
|
||||
}
|
||||
|
||||
private struct ChangePasswordRequest: Encodable {
|
||||
let currentPassword: String
|
||||
let newPassword: String
|
||||
}
|
||||
|
||||
private struct DeleteAccountRequest: Encodable {
|
||||
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?
|
||||
}
|
||||
|
|
@ -6,22 +6,55 @@ import Observation
|
|||
///
|
||||
/// Eine Instanz pro App, beim App-Start initialisiert. `bootstrap()`
|
||||
/// füllt den Status aus dem Keychain (offline möglich).
|
||||
///
|
||||
/// Die Methoden für Sign-Up, Passwort-Reset, Account-Management etc.
|
||||
/// leben in ``AuthClient+Account`` — gleiche Klasse, separate Datei
|
||||
/// damit dieser File die Status-Maschine und den Login/Logout/Refresh-
|
||||
/// Kern hält.
|
||||
@MainActor
|
||||
@Observable
|
||||
public final class AuthClient {
|
||||
public enum Status: Equatable, Sendable {
|
||||
/// Vor `bootstrap()` — Keychain noch nicht ausgewertet.
|
||||
case unknown
|
||||
/// Kein Account, keine Guest-Identität. UI sollte Login/Sign-Up
|
||||
/// anbieten oder via `enterGuestMode()` einen anonymen Modus
|
||||
/// starten.
|
||||
case signedOut
|
||||
/// Anonyme lokale Identität ohne Server-Account. Apps können
|
||||
/// lokale Daten unter dieser UUID persistieren und sie später
|
||||
/// beim Sign-In einem Server-Account zuordnen. Read-only-
|
||||
/// Server-Endpoints, die keinen User brauchen, sind in diesem
|
||||
/// Status erreichbar; schreibende Endpoints nicht.
|
||||
case guest(id: String)
|
||||
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 error(String)
|
||||
}
|
||||
|
||||
public private(set) var status: Status = .unknown
|
||||
|
||||
private let config: ManaAppConfig
|
||||
private let keychain: KeychainStore
|
||||
private let session: URLSession
|
||||
/// Strukturierter Fehler des letzten Sign-In-/Refresh-/Account-
|
||||
/// Operations. Wird beim nächsten `signIn(...)`-Aufruf gelöscht.
|
||||
///
|
||||
/// Ergänzt `status == .error(String)`: während `status` einen für
|
||||
/// die UI angezeigten Text trägt (deutsche Lokalisierung), liefert
|
||||
/// `lastError` den klassifizierten ``AuthError``-Case — z.B. um
|
||||
/// `.emailNotVerified` programmatisch zu erkennen und den Resend-
|
||||
/// Mail-Gate freizuschalten.
|
||||
public private(set) var lastError: AuthError?
|
||||
|
||||
let config: ManaAppConfig
|
||||
let keychain: KeychainStore
|
||||
let session: URLSession
|
||||
|
||||
public init(config: ManaAppConfig, session: URLSession = .shared) {
|
||||
self.config = config
|
||||
|
|
@ -34,23 +67,83 @@ public final class AuthClient {
|
|||
return nil
|
||||
}
|
||||
|
||||
/// Liest den persistierten Auth-Zustand aus dem Keychain. Reihenfolge:
|
||||
/// vollwertige Session > Guest-Identität > komplett ausgeloggt.
|
||||
///
|
||||
/// Keine Server-Roundtrips — Apps starten offline-fähig und mana-auth-
|
||||
/// Downtime kann den letzten gültigen Zustand nicht überschreiben.
|
||||
/// Token-Gültigkeit wird erst beim nächsten authentifizierten Call
|
||||
/// geprüft (siehe ``refreshAccessToken()``).
|
||||
public func bootstrap() {
|
||||
let email = keychain.getString(for: .email)
|
||||
let hasToken = keychain.getString(for: .accessToken) != nil
|
||||
if let email, hasToken {
|
||||
status = .signedIn(email: email)
|
||||
} else if let guestId = keychain.getString(for: .guestId) {
|
||||
status = .guest(id: guestId)
|
||||
} else {
|
||||
status = .signedOut
|
||||
}
|
||||
}
|
||||
|
||||
/// Aktive Guest-Identität, falls vorhanden. Persistiert über
|
||||
/// App-Starts hinweg. Existiert sowohl im ``Status/guest(id:)`` als
|
||||
/// auch parallel zu einer eingeloggten Session — letzteres erlaubt
|
||||
/// es einer App, beim Sign-In die zuvor lokal gesammelten anonymen
|
||||
/// Daten dem neuen Server-Account zuzuordnen.
|
||||
public func currentGuestId() -> String? {
|
||||
keychain.getString(for: .guestId)
|
||||
}
|
||||
|
||||
/// Setzt die App in den anonymen Modus. Idempotent: liefert eine
|
||||
/// bestehende Guest-ID zurück, wenn schon eine im Keychain liegt;
|
||||
/// sonst wird eine neue UUID erzeugt und persistiert.
|
||||
///
|
||||
/// Ändert den Status nur, wenn aktuell `.signedOut` oder `.unknown`
|
||||
/// vorliegt. Bei aktiver Session (`.signedIn`/`.signingIn`) bleibt
|
||||
/// der Status unverändert — die App kann trotzdem `currentGuestId()`
|
||||
/// nutzen, um die anonyme ID zu lesen, ohne die Session zu stören.
|
||||
///
|
||||
/// - Throws: ``AuthError/keychain(_:)`` wenn der Keychain-Write
|
||||
/// scheitert.
|
||||
@discardableResult
|
||||
public func enterGuestMode() throws -> String {
|
||||
if let existing = keychain.getString(for: .guestId) {
|
||||
if case .signedIn = status {} else if case .signingIn = status {} else {
|
||||
status = .guest(id: existing)
|
||||
}
|
||||
return existing
|
||||
}
|
||||
let newId = UUID().uuidString
|
||||
try keychain.setString(newId, for: .guestId)
|
||||
if case .signedIn = status {} else if case .signingIn = status {} else {
|
||||
status = .guest(id: newId)
|
||||
}
|
||||
CoreLog.auth.info("Entered guest mode")
|
||||
return newId
|
||||
}
|
||||
|
||||
/// Löscht die Guest-Identität aus dem Keychain. Genutzt nach einer
|
||||
/// erfolgreichen Migration der lokalen Guest-Daten auf einen
|
||||
/// Server-Account — die anonyme ID wird dann nicht mehr gebraucht.
|
||||
/// Wenn der Status aktuell `.guest` ist, wechselt er auf `.signedOut`.
|
||||
public func clearGuestId() {
|
||||
keychain.remove(for: .guestId)
|
||||
if case .guest = status {
|
||||
status = .signedOut
|
||||
}
|
||||
}
|
||||
|
||||
public func signIn(email: String, password: String) async {
|
||||
let trimmed = email.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty, !password.isEmpty else {
|
||||
status = .error("Email und Passwort sind erforderlich")
|
||||
let err = AuthError.validation(message: "Email und Passwort sind erforderlich")
|
||||
lastError = err
|
||||
status = .error(err.errorDescription ?? "")
|
||||
return
|
||||
}
|
||||
|
||||
lastError = nil
|
||||
status = .signingIn
|
||||
do {
|
||||
let url = config.authBaseURL.appending(path: "/api/v1/auth/login")
|
||||
|
|
@ -65,13 +158,30 @@ public final class AuthClient {
|
|||
return
|
||||
}
|
||||
guard http.statusCode == 200 else {
|
||||
let message = (try? JSONDecoder().decode(ServerError.self, from: data))?.message
|
||||
if http.statusCode == 401 {
|
||||
status = .error("Email oder Passwort falsch")
|
||||
} else {
|
||||
status =
|
||||
.error("Login fehlgeschlagen (HTTP \(http.statusCode))" + (message.map { " — \($0)" } ?? ""))
|
||||
}
|
||||
let err = AuthError.classify(
|
||||
status: http.statusCode,
|
||||
data: data,
|
||||
retryAfterHeader: http.retryAfterSeconds
|
||||
)
|
||||
lastError = err
|
||||
status = .error(err.errorDescription ?? "Login fehlgeschlagen")
|
||||
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
|
||||
}
|
||||
|
||||
|
|
@ -80,17 +190,30 @@ public final class AuthClient {
|
|||
try keychain.setString(token.refreshToken, for: .refreshToken)
|
||||
try keychain.setString(trimmed, for: .email)
|
||||
status = .signedIn(email: trimmed)
|
||||
lastError = nil
|
||||
CoreLog.auth.info("Sign-in successful")
|
||||
} catch let error as URLError {
|
||||
status = .error("Netzwerk: \(error.localizedDescription)")
|
||||
let err = AuthError.networkFailure(error.localizedDescription)
|
||||
lastError = err
|
||||
status = .error(err.errorDescription ?? "Netzwerk-Fehler")
|
||||
CoreLog.auth.error("Sign-in network error: \(error.localizedDescription, privacy: .public)")
|
||||
} catch {
|
||||
status = .error(String(describing: error))
|
||||
let err = AuthError.networkFailure(String(describing: error))
|
||||
lastError = err
|
||||
status = .error(err.errorDescription ?? String(describing: error))
|
||||
CoreLog.auth.error("Sign-in error: \(String(describing: error), privacy: .public)")
|
||||
}
|
||||
}
|
||||
|
||||
public func signOut() async {
|
||||
/// Logged den User aus. Versucht den Server zu informieren (Logout-
|
||||
/// Endpoint), wischt den lokalen Keychain und setzt den Status.
|
||||
///
|
||||
/// - Parameter keepGuestMode: Wenn `true`, bleibt die App in einem
|
||||
/// anonymen Local-First-Modus aktiv. Eine bestehende Guest-ID
|
||||
/// wird beibehalten oder eine neue erzeugt; der Status wechselt
|
||||
/// auf ``Status/guest(id:)``. Default `false` für strict-Logout
|
||||
/// (Status → `.signedOut`, auch Guest-ID gelöscht).
|
||||
public func signOut(keepGuestMode: Bool = false) async {
|
||||
if let token = keychain.getString(for: .accessToken) {
|
||||
let url = config.authBaseURL.appending(path: "/api/v1/auth/logout")
|
||||
var request = URLRequest(url: url)
|
||||
|
|
@ -99,8 +222,20 @@ public final class AuthClient {
|
|||
_ = try? await session.data(for: request)
|
||||
}
|
||||
keychain.wipe()
|
||||
status = .signedOut
|
||||
CoreLog.auth.info("Signed out")
|
||||
if keepGuestMode {
|
||||
if let existing = keychain.getString(for: .guestId) {
|
||||
status = .guest(id: existing)
|
||||
} else {
|
||||
let newId = UUID().uuidString
|
||||
try? keychain.setString(newId, for: .guestId)
|
||||
status = .guest(id: newId)
|
||||
}
|
||||
CoreLog.auth.info("Signed out — kept guest mode")
|
||||
} else {
|
||||
keychain.remove(for: .guestId)
|
||||
status = .signedOut
|
||||
CoreLog.auth.info("Signed out")
|
||||
}
|
||||
}
|
||||
|
||||
public func currentAccessToken() throws -> String {
|
||||
|
|
@ -110,6 +245,19 @@ public final class AuthClient {
|
|||
return token
|
||||
}
|
||||
|
||||
/// Liefert den Session-Token (das wire-protocol `refreshToken`-Feld).
|
||||
/// Wird von Better-Auth-`auth.api.*`-Endpoints akzeptiert wenn der
|
||||
/// `bearer`-Plugin server-seitig aktiv ist — z.B. für `changeEmail`,
|
||||
/// `changePassword`, `deleteAccount`. Der App-eigene JWT (aus
|
||||
/// `currentAccessToken`) gilt für app-spezifische Backends, der
|
||||
/// Session-Token nur für mana-auths Account-Aktionen.
|
||||
public func currentSessionToken() throws -> String {
|
||||
guard let token = keychain.getString(for: .refreshToken) else {
|
||||
throw AuthError.notSignedIn
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
/// Liefert einen Access-Token, der nicht innerhalb der nächsten
|
||||
/// `refreshLeeway` Sekunden abläuft. Refreshed proaktiv, wenn nötig.
|
||||
public func freshAccessToken(refreshLeeway: TimeInterval = 300) async throws -> String {
|
||||
|
|
@ -136,12 +284,30 @@ public final class AuthClient {
|
|||
throw AuthError.networkFailure("Keine HTTP-Antwort")
|
||||
}
|
||||
guard http.statusCode == 200 else {
|
||||
keychain.wipe()
|
||||
status = .signedOut
|
||||
throw AuthError.serverError(
|
||||
let err = AuthError.classify(
|
||||
status: http.statusCode,
|
||||
message: (try? JSONDecoder().decode(ServerError.self, from: data))?.message
|
||||
data: data,
|
||||
retryAfterHeader: http.retryAfterSeconds
|
||||
)
|
||||
// Wipe nur bei tatsächlich invalidierter Session. Transiente
|
||||
// Fehler (5xx, Rate-Limit) lassen den Token erhalten — sonst
|
||||
// wirft jeder mana-auth-Downtime-Moment alle Apps in den
|
||||
// Login-Screen. Falls eine Guest-Identität existiert, wird
|
||||
// beim Wipe in den Guest-Status zurückgefallen statt in
|
||||
// strict `.signedOut`.
|
||||
if err.invalidatesSession {
|
||||
keychain.wipe()
|
||||
if let guestId = keychain.getString(for: .guestId) {
|
||||
status = .guest(id: guestId)
|
||||
} else {
|
||||
status = .signedOut
|
||||
}
|
||||
} else {
|
||||
CoreLog.auth.notice(
|
||||
"Refresh failed transiently (\(http.statusCode, privacy: .public)) — keeping session"
|
||||
)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
let token = try JSONDecoder().decode(TokenResponse.self, from: data)
|
||||
|
|
@ -151,22 +317,73 @@ public final class AuthClient {
|
|||
}
|
||||
return token.accessToken
|
||||
}
|
||||
|
||||
// MARK: - Internal Helpers (used by AuthClient+Account)
|
||||
|
||||
/// Persistiert ein frisch erhaltenes Token-Paar und setzt den Status
|
||||
/// auf `.signedIn`. Genutzt von ``AuthClient+Account``-Flows, die
|
||||
/// in den eingeloggten Zustand führen (z.B. `register` wenn der
|
||||
/// Server bereits eine Session liefert).
|
||||
func persistSession(email: String, accessToken: String, refreshToken: String) throws {
|
||||
try keychain.setString(accessToken, for: .accessToken)
|
||||
try keychain.setString(refreshToken, for: .refreshToken)
|
||||
try keychain.setString(email, for: .email)
|
||||
status = .signedIn(email: email)
|
||||
}
|
||||
|
||||
/// Setzt den Status auf `.signedOut` und wirft den Keychain
|
||||
/// vollständig leer — inklusive Guest-ID. Genutzt nach
|
||||
/// `deleteAccount()`: Account ist gelöscht, also auch die
|
||||
/// (potenziell verknüpfte) anonyme Identität.
|
||||
func clearSession() {
|
||||
keychain.wipeAll()
|
||||
status = .signedOut
|
||||
}
|
||||
}
|
||||
|
||||
private struct LoginRequest: Encodable {
|
||||
// MARK: - Wire-Format
|
||||
|
||||
struct LoginRequest: Encodable {
|
||||
let email: String
|
||||
let password: String
|
||||
}
|
||||
|
||||
private struct RefreshRequest: Encodable {
|
||||
struct RefreshRequest: Encodable {
|
||||
let refreshToken: String
|
||||
}
|
||||
|
||||
private struct TokenResponse: Decodable {
|
||||
/// Antwort von `/login`, `/refresh` und (manchmal) `/register`.
|
||||
///
|
||||
/// `register` liefert je nach Server-Konfig:
|
||||
/// - mit `requireEmailVerification: true` (Default): nur `user`, keine Tokens
|
||||
/// - mit `false`: vollständiges Token-Paar
|
||||
///
|
||||
/// Optionale Felder sind explizit `Optional` damit beide Pfade dekodierbar sind.
|
||||
struct TokenResponse: Decodable {
|
||||
let accessToken: String
|
||||
let refreshToken: String
|
||||
}
|
||||
|
||||
private struct ServerError: Decodable {
|
||||
let message: 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 {
|
||||
/// Liest `Retry-After` als Anzahl Sekunden. Server schickt Integer-
|
||||
/// Sekunden (siehe `lib/auth-errors.ts`). HTTP-Datum-Variante wird
|
||||
/// nicht unterstützt — mana-auth nutzt sie nicht.
|
||||
var retryAfterSeconds: TimeInterval? {
|
||||
guard let raw = value(forHTTPHeaderField: "Retry-After"),
|
||||
let seconds = TimeInterval(raw)
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
return seconds
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,31 +1,248 @@
|
|||
import Foundation
|
||||
|
||||
/// Fehler-Typen des Auth- und Transport-Layers.
|
||||
public enum AuthError: Error, LocalizedError, Sendable {
|
||||
///
|
||||
/// Server-Fehler-Codes folgen `AuthErrorCode` aus
|
||||
/// `mana/services/mana-auth/src/lib/auth-errors.ts`. Jeder dort
|
||||
/// definierte Code hat hier einen passenden Case — neue Codes
|
||||
/// auf Server-Seite brauchen einen Minor-Bump dieses Pakets.
|
||||
public enum AuthError: Error, LocalizedError, Sendable, Equatable {
|
||||
// MARK: - Client-Side
|
||||
|
||||
/// Kein Token im Keychain — User muss sich einloggen.
|
||||
case notSignedIn
|
||||
case invalidCredentials
|
||||
case networkFailure(String)
|
||||
case serverError(status: Int, message: String?)
|
||||
case decoding(String)
|
||||
case keychain(OSStatus)
|
||||
/// Lokales Encoding (z.B. UTF-8-Konvertierung) gescheitert.
|
||||
case encoding
|
||||
/// Keychain-Operation gescheitert mit OSStatus.
|
||||
case keychain(OSStatus)
|
||||
/// Antwort konnte nicht dekodiert werden.
|
||||
case decoding(String)
|
||||
/// Netzwerk-Schicht hat geworfen.
|
||||
case networkFailure(String)
|
||||
|
||||
// MARK: - Server-Side (Mapping zu AuthErrorCode in mana-auth)
|
||||
|
||||
/// `INVALID_CREDENTIALS` — Email oder Passwort falsch.
|
||||
case invalidCredentials
|
||||
/// `EMAIL_NOT_VERIFIED` — Account existiert, Email muss bestätigt
|
||||
/// werden. UI bietet "Bestätigungs-Mail erneut senden" an.
|
||||
case emailNotVerified
|
||||
/// `EMAIL_ALREADY_REGISTERED` — Sign-Up mit existierender Email.
|
||||
case emailAlreadyRegistered
|
||||
/// `WEAK_PASSWORD` — Passwort erfüllt Mindest-Policy nicht.
|
||||
case weakPassword(message: String?)
|
||||
/// `ACCOUNT_LOCKED` — zu viele Fehlversuche. `retryAfter` in Sekunden.
|
||||
case accountLocked(retryAfter: TimeInterval?)
|
||||
/// `SIGNUP_LIMIT_REACHED` — tägliches Registrierungs-Limit aus.
|
||||
case signupLimitReached
|
||||
/// `RATE_LIMITED` — generelles Rate-Limit. `retryAfter` in Sekunden.
|
||||
case rateLimited(retryAfter: TimeInterval?)
|
||||
/// `TOKEN_EXPIRED` — z.B. Reset-Token, Verify-Token.
|
||||
case tokenExpired
|
||||
/// `TOKEN_INVALID` — Token nicht parsebar / nicht gefunden.
|
||||
case tokenInvalid
|
||||
/// `TWO_FACTOR_REQUIRED` — Login erfolgreich, aber 2FA-Challenge offen.
|
||||
case twoFactorRequired
|
||||
/// `TWO_FACTOR_FAILED` — TOTP- oder Backup-Code falsch.
|
||||
case twoFactorFailed
|
||||
/// `PASSKEY_NOT_ENABLED` — User hat keinen Passkey registriert.
|
||||
case passkeyNotEnabled
|
||||
/// `PASSKEY_CANCELLED` — User hat den Plattform-Dialog abgebrochen.
|
||||
case passkeyCancelled
|
||||
/// `PASSKEY_VERIFICATION_FAILED` — WebAuthn-Verifikation gescheitert.
|
||||
case passkeyVerificationFailed
|
||||
/// `VALIDATION` — Request-Body ungültig (z.B. fehlendes Feld).
|
||||
case validation(message: String?)
|
||||
/// `UNAUTHORIZED` — fehlender oder ungültiger Authorization-Header.
|
||||
case unauthorized
|
||||
/// `NOT_FOUND` — referenzierte Ressource existiert nicht.
|
||||
case notFound
|
||||
/// `SERVICE_UNAVAILABLE` — Server temporär nicht erreichbar.
|
||||
case serviceUnavailable
|
||||
/// `INTERNAL` — Server-interner Fehler ohne weitere Klassifikation.
|
||||
case serverInternal
|
||||
|
||||
/// Fallback für Server-Fehler ohne bekannten `AuthErrorCode`.
|
||||
case serverError(status: Int, code: String?, message: String?)
|
||||
|
||||
public var errorDescription: String? {
|
||||
switch self {
|
||||
case .notSignedIn:
|
||||
"Nicht angemeldet"
|
||||
case .invalidCredentials:
|
||||
"Ungültige Anmeldedaten"
|
||||
case let .networkFailure(message):
|
||||
"Netzwerkfehler: \(message)"
|
||||
case let .serverError(status, message):
|
||||
"Server-Fehler (\(status))" + (message.map { ": \($0)" } ?? "")
|
||||
case let .decoding(detail):
|
||||
"Antwort konnte nicht gelesen werden: \(detail)"
|
||||
case let .keychain(status):
|
||||
"Keychain-Fehler (OSStatus \(status))"
|
||||
case .encoding:
|
||||
"Datenkodierung fehlgeschlagen"
|
||||
case let .keychain(status):
|
||||
"Keychain-Fehler (OSStatus \(status))"
|
||||
case let .decoding(detail):
|
||||
"Antwort konnte nicht gelesen werden: \(detail)"
|
||||
case let .networkFailure(message):
|
||||
"Netzwerkfehler: \(message)"
|
||||
case .invalidCredentials:
|
||||
"Email oder Passwort falsch"
|
||||
case .emailNotVerified:
|
||||
"Bitte bestätige deine Email-Adresse, bevor du dich anmeldest."
|
||||
case .emailAlreadyRegistered:
|
||||
"Diese Email ist bereits registriert."
|
||||
case let .weakPassword(message):
|
||||
message ?? "Passwort erfüllt die Mindest-Anforderungen nicht."
|
||||
case let .accountLocked(retryAfter):
|
||||
retryAfter
|
||||
.map { "Account temporär gesperrt. Erneut versuchen in \(Int($0))s." }
|
||||
?? "Account temporär gesperrt."
|
||||
case .signupLimitReached:
|
||||
"Das tägliche Registrierungslimit ist erreicht. Versuche es morgen wieder."
|
||||
case let .rateLimited(retryAfter):
|
||||
retryAfter
|
||||
.map { "Zu viele Versuche. Bitte warte \(Int($0))s." }
|
||||
?? "Zu viele Versuche. Bitte warte einen Moment."
|
||||
case .tokenExpired:
|
||||
"Der Link ist abgelaufen. Bitte fordere einen neuen an."
|
||||
case .tokenInvalid:
|
||||
"Der Link ist ungültig."
|
||||
case .twoFactorRequired:
|
||||
"Zwei-Faktor-Code erforderlich."
|
||||
case .twoFactorFailed:
|
||||
"Zwei-Faktor-Code falsch."
|
||||
case .passkeyNotEnabled:
|
||||
"Für diesen Account ist kein Passkey eingerichtet."
|
||||
case .passkeyCancelled:
|
||||
"Passkey-Eingabe abgebrochen."
|
||||
case .passkeyVerificationFailed:
|
||||
"Passkey konnte nicht verifiziert werden."
|
||||
case let .validation(message):
|
||||
message ?? "Eingabe ungültig."
|
||||
case .unauthorized:
|
||||
"Nicht autorisiert."
|
||||
case .notFound:
|
||||
"Nicht gefunden."
|
||||
case .serviceUnavailable:
|
||||
"Server temporär nicht erreichbar. Bitte später erneut versuchen."
|
||||
case .serverInternal:
|
||||
"Server-Fehler. Bitte später erneut versuchen."
|
||||
case let .serverError(status, code, message):
|
||||
"Server-Fehler (\(status))"
|
||||
+ (code.map { " — \($0)" } ?? "")
|
||||
+ (message.map { ": \($0)" } ?? "")
|
||||
}
|
||||
}
|
||||
|
||||
/// `true` wenn dieser Fehler bedeutet, dass die gespeicherten
|
||||
/// Tokens nicht mehr gültig sind und die App den Nutzer ausloggen
|
||||
/// muss. `false` für *transiente* Fehler (Server-Downtime, Netzwerk-
|
||||
/// Fehler, Rate-Limiting), bei denen die Session erhalten bleiben
|
||||
/// soll — die App sollte den Versuch nur wiederholen.
|
||||
///
|
||||
/// Genutzt von ``AuthClient/refreshAccessToken()`` um zu entscheiden,
|
||||
/// ob der Keychain gewiped werden muss. Apps können denselben
|
||||
/// Test auf Fehler aus ``AuthenticatedTransport`` anwenden, um
|
||||
/// zwischen "neuer Login nötig" und "später nochmal probieren" zu
|
||||
/// unterscheiden.
|
||||
public var invalidatesSession: Bool {
|
||||
switch self {
|
||||
case .invalidCredentials,
|
||||
.unauthorized,
|
||||
.tokenExpired,
|
||||
.tokenInvalid,
|
||||
.emailNotVerified:
|
||||
true
|
||||
case .notSignedIn,
|
||||
.encoding,
|
||||
.keychain,
|
||||
.decoding,
|
||||
.networkFailure,
|
||||
.emailAlreadyRegistered,
|
||||
.weakPassword,
|
||||
.accountLocked,
|
||||
.signupLimitReached,
|
||||
.rateLimited,
|
||||
.twoFactorRequired,
|
||||
.twoFactorFailed,
|
||||
.passkeyNotEnabled,
|
||||
.passkeyCancelled,
|
||||
.passkeyVerificationFailed,
|
||||
.validation,
|
||||
.notFound,
|
||||
.serviceUnavailable,
|
||||
.serverInternal,
|
||||
.serverError:
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Klassifiziert eine `mana-auth`-Fehler-Antwort. `data` ist der
|
||||
/// Response-Body, `status` der HTTP-Status, `retryAfterHeader` der
|
||||
/// `Retry-After`-Header-Wert in Sekunden (falls vorhanden).
|
||||
///
|
||||
/// Mapping zu `AuthErrorCode` in
|
||||
/// `mana/services/mana-auth/src/lib/auth-errors.ts`. Unbekannte Codes
|
||||
/// fallen auf ``serverError(status:code:message:)`` zurück.
|
||||
public static func classify(
|
||||
status: Int,
|
||||
data: Data,
|
||||
retryAfterHeader: TimeInterval? = nil
|
||||
) -> AuthError {
|
||||
let body = try? JSONDecoder().decode(ServerErrorBody.self, from: data)
|
||||
let message = body?.message
|
||||
let retryAfter = body?.retryAfterSec ?? retryAfterHeader
|
||||
|
||||
switch body?.error {
|
||||
case "INVALID_CREDENTIALS":
|
||||
return .invalidCredentials
|
||||
case "EMAIL_NOT_VERIFIED":
|
||||
return .emailNotVerified
|
||||
case "EMAIL_ALREADY_REGISTERED":
|
||||
return .emailAlreadyRegistered
|
||||
case "WEAK_PASSWORD":
|
||||
return .weakPassword(message: message)
|
||||
case "ACCOUNT_LOCKED":
|
||||
return .accountLocked(retryAfter: retryAfter)
|
||||
case "SIGNUP_LIMIT_REACHED":
|
||||
return .signupLimitReached
|
||||
case "RATE_LIMITED":
|
||||
return .rateLimited(retryAfter: retryAfter)
|
||||
case "TOKEN_EXPIRED":
|
||||
return .tokenExpired
|
||||
case "TOKEN_INVALID":
|
||||
return .tokenInvalid
|
||||
case "TWO_FACTOR_REQUIRED":
|
||||
return .twoFactorRequired
|
||||
case "TWO_FACTOR_FAILED":
|
||||
return .twoFactorFailed
|
||||
case "PASSKEY_NOT_ENABLED":
|
||||
return .passkeyNotEnabled
|
||||
case "PASSKEY_CANCELLED":
|
||||
return .passkeyCancelled
|
||||
case "PASSKEY_VERIFICATION_FAILED":
|
||||
return .passkeyVerificationFailed
|
||||
case "VALIDATION":
|
||||
return .validation(message: message)
|
||||
case "UNAUTHORIZED":
|
||||
return .unauthorized
|
||||
case "NOT_FOUND":
|
||||
return .notFound
|
||||
case "SERVICE_UNAVAILABLE":
|
||||
return .serviceUnavailable
|
||||
case "INTERNAL":
|
||||
return .serverInternal
|
||||
default:
|
||||
// Status-Heuristik wenn kein Code geliefert wurde.
|
||||
switch status {
|
||||
case 401: return .invalidCredentials
|
||||
case 403: return .emailNotVerified
|
||||
case 404: return .notFound
|
||||
case 429: return .rateLimited(retryAfter: retryAfter)
|
||||
case 503: return .serviceUnavailable
|
||||
default: return .serverError(status: status, code: body?.error, message: message)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wire-Format der `mana-auth`-Fehler-Antwort. Spiegelt
|
||||
/// `AuthErrorResponseBody` aus `lib/auth-errors.ts`.
|
||||
struct ServerErrorBody: Decodable, Sendable {
|
||||
let error: String?
|
||||
let message: String?
|
||||
let status: Int?
|
||||
let retryAfterSec: TimeInterval?
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,10 +5,18 @@ import Security
|
|||
/// pro `ManaAppConfig`.
|
||||
public final class KeychainStore: Sendable {
|
||||
/// Bekannte Keys für mana-auth-Tokens.
|
||||
///
|
||||
/// `.guestId` ist eine lokal generierte anonyme UUID für Apps mit
|
||||
/// Local-First-/Guest-Modus. Sie wird unabhängig von den Session-
|
||||
/// Tokens persistiert und vom Default-``wipe()`` *nicht* gelöscht —
|
||||
/// damit eine App nach einem Logout im Guest-Modus weiterlaufen
|
||||
/// kann, ohne dass die lokalen anonymen Daten ihre Besitzer-Spur
|
||||
/// verlieren. Vollständiger Reset über ``wipeAll()``.
|
||||
public enum Key: String, Sendable {
|
||||
case accessToken = "access_token"
|
||||
case refreshToken = "refresh_token"
|
||||
case email
|
||||
case guestId = "guest_id"
|
||||
}
|
||||
|
||||
private let service: String
|
||||
|
|
@ -64,12 +72,22 @@ public final class KeychainStore: Sendable {
|
|||
SecItemDelete(query as CFDictionary)
|
||||
}
|
||||
|
||||
/// Löscht Session-Daten (accessToken, refreshToken, email). Behält
|
||||
/// die ``Key/guestId``, damit lokale Guest-Daten nach einem Logout
|
||||
/// erhalten bleiben können.
|
||||
public func wipe() {
|
||||
remove(for: .accessToken)
|
||||
remove(for: .refreshToken)
|
||||
remove(for: .email)
|
||||
}
|
||||
|
||||
/// Löscht *alles* inklusive der Guest-Identität. Genutzt nach
|
||||
/// `deleteAccount()` oder bei explizitem "anonyme Daten vergessen".
|
||||
public func wipeAll() {
|
||||
wipe()
|
||||
remove(for: .guestId)
|
||||
}
|
||||
|
||||
private func baseQuery(for key: Key) -> [CFString: Any] {
|
||||
var query: [CFString: Any] = [
|
||||
kSecClass: kSecClassGenericPassword,
|
||||
|
|
|
|||
216
Tests/ManaCoreTests/AuthClientAccountTests.swift
Normal file
216
Tests/ManaCoreTests/AuthClientAccountTests.swift
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
import Foundation
|
||||
import Testing
|
||||
@testable import ManaCore
|
||||
|
||||
@Suite("AuthClient+Account")
|
||||
@MainActor
|
||||
struct AuthClientAccountTests {
|
||||
private func recordedBody(_ request: URLRequest) -> [String: Any] {
|
||||
guard let body = request.httpBody ?? request.bodyStreamData(),
|
||||
let json = try? JSONSerialization.jsonObject(with: body) as? [String: Any]
|
||||
else { return [:] }
|
||||
return json
|
||||
}
|
||||
|
||||
// MARK: - register
|
||||
|
||||
@Test("register schickt POST /api/v1/auth/register mit JSON-Body")
|
||||
func registerSendsCorrectRequest() async throws {
|
||||
let mocked = makeMockedAuth()
|
||||
mocked.setHandler { request in
|
||||
#expect(request.httpMethod == "POST")
|
||||
#expect(request.url?.path == "/api/v1/auth/register")
|
||||
#expect(request.value(forHTTPHeaderField: "Content-Type") == "application/json")
|
||||
return (200, Data(#"{"user":{"id":"u1","email":"new@x.de"}}"#.utf8))
|
||||
}
|
||||
|
||||
try await mocked.auth.register(
|
||||
email: "new@x.de",
|
||||
password: "Aa-123456789",
|
||||
name: "Neu",
|
||||
sourceAppUrl: URL(string: "https://cardecky.mana.how/auth/verify")
|
||||
)
|
||||
if case .signedIn = mocked.auth.status {
|
||||
Issue.record("Expected not-signed-in after register without tokens")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("register mit Token-Antwort führt direkt zu signedIn")
|
||||
func registerWithTokensSignsIn() async throws {
|
||||
let mocked = makeMockedAuth()
|
||||
let access = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
|
||||
let refresh = "refresh-token-value"
|
||||
mocked.setHandler { _ in
|
||||
(200, Data(#"""
|
||||
{"user":{"id":"u1","email":"new@x.de"},"accessToken":"\#(access)","refreshToken":"\#(refresh)"}
|
||||
"""#.utf8))
|
||||
}
|
||||
|
||||
try await mocked.auth.register(email: "new@x.de", password: "Aa-123456789")
|
||||
#expect(mocked.auth.status == .signedIn(email: "new@x.de"))
|
||||
}
|
||||
|
||||
@Test("register mit existierender Email wirft emailAlreadyRegistered")
|
||||
func registerEmailAlreadyRegistered() async {
|
||||
let mocked = makeMockedAuth()
|
||||
mocked.setHandler { _ in
|
||||
(409, Data(#"{"error":"EMAIL_ALREADY_REGISTERED","status":409}"#.utf8))
|
||||
}
|
||||
|
||||
await #expect(throws: AuthError.emailAlreadyRegistered) {
|
||||
try await mocked.auth.register(email: "old@x.de", password: "Aa-123456789")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("register mit leerer Email wirft validation ohne Server-Call")
|
||||
func registerValidatesEmptyEmail() async {
|
||||
let mocked = makeMockedAuth()
|
||||
mocked.setHandler { _ in
|
||||
Issue.record("Server darf nicht aufgerufen werden")
|
||||
return (500, Data())
|
||||
}
|
||||
|
||||
await #expect(throws: (any Error).self) {
|
||||
try await mocked.auth.register(email: " ", password: "Aa-123456789")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - forgotPassword
|
||||
|
||||
@Test("forgotPassword schickt email + redirectTo")
|
||||
func forgotPasswordPayload() async throws {
|
||||
let mocked = makeMockedAuth()
|
||||
let capturedURL = MockURLProtocol.Capture()
|
||||
mocked.setHandler { request in
|
||||
capturedURL.store(request)
|
||||
return (200, Data(#"{"success":true}"#.utf8))
|
||||
}
|
||||
|
||||
try await mocked.auth.forgotPassword(
|
||||
email: "user@x.de",
|
||||
resetUniversalLink: URL(string: "https://cardecky.mana.how/auth/reset")!
|
||||
)
|
||||
let captured = try #require(capturedURL.request)
|
||||
let json = recordedBody(captured)
|
||||
#expect(json["email"] as? String == "user@x.de")
|
||||
#expect(json["redirectTo"] as? String == "https://cardecky.mana.how/auth/reset")
|
||||
#expect(captured.url?.path == "/api/v1/auth/forgot-password")
|
||||
}
|
||||
|
||||
// MARK: - resetPassword
|
||||
|
||||
@Test("resetPassword schickt token + newPassword")
|
||||
func resetPasswordPayload() async throws {
|
||||
let mocked = makeMockedAuth()
|
||||
let captured = MockURLProtocol.Capture()
|
||||
mocked.setHandler { request in
|
||||
captured.store(request)
|
||||
return (200, Data(#"{"success":true}"#.utf8))
|
||||
}
|
||||
|
||||
try await mocked.auth.resetPassword(token: "tok123", newPassword: "Neu-987654321")
|
||||
let request = try #require(captured.request)
|
||||
let json = recordedBody(request)
|
||||
#expect(json["token"] as? String == "tok123")
|
||||
#expect(json["newPassword"] as? String == "Neu-987654321")
|
||||
#expect(request.url?.path == "/api/v1/auth/reset-password")
|
||||
}
|
||||
|
||||
@Test("resetPassword mit abgelaufenem Token wirft tokenExpired")
|
||||
func resetPasswordTokenExpired() async {
|
||||
let mocked = makeMockedAuth()
|
||||
mocked.setHandler { _ in
|
||||
(400, Data(#"{"error":"TOKEN_EXPIRED","status":400}"#.utf8))
|
||||
}
|
||||
|
||||
await #expect(throws: AuthError.tokenExpired) {
|
||||
try await mocked.auth.resetPassword(token: "old", newPassword: "Neu-987654321")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - resendVerification
|
||||
|
||||
@Test("resendVerification schickt email + sourceAppUrl")
|
||||
func resendVerificationPayload() async throws {
|
||||
let mocked = makeMockedAuth()
|
||||
let captured = MockURLProtocol.Capture()
|
||||
mocked.setHandler { request in
|
||||
captured.store(request)
|
||||
return (200, Data(#"{"success":true}"#.utf8))
|
||||
}
|
||||
|
||||
try await mocked.auth.resendVerification(
|
||||
email: "user@x.de",
|
||||
sourceAppUrl: URL(string: "https://cardecky.mana.how/auth/verify")
|
||||
)
|
||||
let request = try #require(captured.request)
|
||||
let json = recordedBody(request)
|
||||
#expect(json["email"] as? String == "user@x.de")
|
||||
#expect(json["sourceAppUrl"] as? String == "https://cardecky.mana.how/auth/verify")
|
||||
}
|
||||
|
||||
@Test("resendVerification mit Rate-Limit liefert retryAfter")
|
||||
func resendVerificationRateLimited() async {
|
||||
let mocked = makeMockedAuth()
|
||||
mocked.setHandler { _ in
|
||||
(
|
||||
429,
|
||||
Data(#"{"error":"RATE_LIMITED","retryAfterSec":42,"status":429}"#.utf8),
|
||||
["Retry-After": "42"]
|
||||
)
|
||||
}
|
||||
|
||||
do {
|
||||
try await mocked.auth.resendVerification(email: "user@x.de")
|
||||
Issue.record("Expected throw")
|
||||
} catch let AuthError.rateLimited(retryAfter) {
|
||||
#expect(retryAfter == 42)
|
||||
} catch {
|
||||
Issue.record("Unexpected error: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Authenticated calls (require signed-in state)
|
||||
|
||||
@Test("changeEmail ohne Login wirft notSignedIn")
|
||||
func changeEmailRequiresSession() async {
|
||||
let mocked = makeMockedAuth()
|
||||
await #expect(throws: AuthError.notSignedIn) {
|
||||
try await mocked.auth.changeEmail(newEmail: "neu@x.de")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("changePassword schickt Session-Token als Bearer (nicht JWT)")
|
||||
func changePasswordSendsBearer() async throws {
|
||||
let mocked = makeMockedAuth()
|
||||
let access = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
|
||||
let session = "session-token-value"
|
||||
try mocked.auth.persistSession(email: "u@x.de", accessToken: access, refreshToken: session)
|
||||
|
||||
let captured = MockURLProtocol.Capture()
|
||||
mocked.setHandler { request in
|
||||
captured.store(request)
|
||||
return (200, Data(#"{"success":true}"#.utf8))
|
||||
}
|
||||
|
||||
try await mocked.auth.changePassword(currentPassword: "alt", newPassword: "neu")
|
||||
let request = try #require(captured.request)
|
||||
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer \(session)")
|
||||
#expect(request.url?.path == "/api/v1/auth/change-password")
|
||||
}
|
||||
|
||||
@Test("deleteAccount wiped Session bei Erfolg")
|
||||
func deleteAccountClearsSession() async throws {
|
||||
let mocked = makeMockedAuth()
|
||||
let access = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
|
||||
try mocked.auth.persistSession(email: "u@x.de", accessToken: access, refreshToken: "r")
|
||||
#expect(mocked.auth.status == .signedIn(email: "u@x.de"))
|
||||
|
||||
mocked.setHandler { request in
|
||||
#expect(request.httpMethod == "DELETE")
|
||||
return (200, Data(#"{"success":true}"#.utf8))
|
||||
}
|
||||
try await mocked.auth.deleteAccount(password: "pw")
|
||||
#expect(mocked.auth.status == .signedOut)
|
||||
}
|
||||
}
|
||||
230
Tests/ManaCoreTests/AuthClientGuestAndResilienceTests.swift
Normal file
230
Tests/ManaCoreTests/AuthClientGuestAndResilienceTests.swift
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
import Foundation
|
||||
import Testing
|
||||
@testable import ManaCore
|
||||
|
||||
@Suite("AuthClient Guest-Mode + Resilience")
|
||||
@MainActor
|
||||
struct AuthClientGuestAndResilienceTests {
|
||||
// MARK: - enterGuestMode / currentGuestId
|
||||
|
||||
@Test("enterGuestMode aus signedOut erzeugt UUID und setzt .guest")
|
||||
func enterGuestModeFromSignedOut() throws {
|
||||
let mocked = makeMockedAuth()
|
||||
mocked.auth.bootstrap()
|
||||
#expect(mocked.auth.status == .signedOut)
|
||||
|
||||
let id = try mocked.auth.enterGuestMode()
|
||||
#expect(!id.isEmpty)
|
||||
#expect(mocked.auth.status == .guest(id: id))
|
||||
#expect(mocked.auth.currentGuestId() == id)
|
||||
}
|
||||
|
||||
@Test("enterGuestMode ist idempotent")
|
||||
func enterGuestModeIdempotent() throws {
|
||||
let mocked = makeMockedAuth()
|
||||
let first = try mocked.auth.enterGuestMode()
|
||||
let second = try mocked.auth.enterGuestMode()
|
||||
#expect(first == second)
|
||||
#expect(mocked.auth.status == .guest(id: first))
|
||||
}
|
||||
|
||||
@Test("enterGuestMode stört aktive Session nicht")
|
||||
func enterGuestModeKeepsSignedIn() throws {
|
||||
let mocked = makeMockedAuth()
|
||||
try mocked.auth.persistSession(email: "u@x.de", accessToken: "a", refreshToken: "r")
|
||||
#expect(mocked.auth.status == .signedIn(email: "u@x.de"))
|
||||
|
||||
let id = try mocked.auth.enterGuestMode()
|
||||
#expect(mocked.auth.status == .signedIn(email: "u@x.de"))
|
||||
#expect(mocked.auth.currentGuestId() == id)
|
||||
}
|
||||
|
||||
@Test("clearGuestId aus .guest fällt auf .signedOut")
|
||||
func clearGuestIdFromGuest() throws {
|
||||
let mocked = makeMockedAuth()
|
||||
_ = try mocked.auth.enterGuestMode()
|
||||
mocked.auth.clearGuestId()
|
||||
#expect(mocked.auth.status == .signedOut)
|
||||
#expect(mocked.auth.currentGuestId() == nil)
|
||||
}
|
||||
|
||||
@Test("clearGuestId aus .signedIn behält Status")
|
||||
func clearGuestIdKeepsSignedIn() throws {
|
||||
let mocked = makeMockedAuth()
|
||||
_ = try mocked.auth.enterGuestMode()
|
||||
try mocked.auth.persistSession(email: "u@x.de", accessToken: "a", refreshToken: "r")
|
||||
mocked.auth.clearGuestId()
|
||||
#expect(mocked.auth.status == .signedIn(email: "u@x.de"))
|
||||
#expect(mocked.auth.currentGuestId() == nil)
|
||||
}
|
||||
|
||||
// MARK: - bootstrap
|
||||
|
||||
@Test("bootstrap erkennt nur-Guest-Keychain als .guest")
|
||||
func bootstrapDetectsGuest() throws {
|
||||
let mocked = makeMockedAuth()
|
||||
_ = try mocked.auth.enterGuestMode()
|
||||
mocked.auth.bootstrap()
|
||||
if case let .guest(id) = mocked.auth.status {
|
||||
#expect(!id.isEmpty)
|
||||
} else {
|
||||
Issue.record("Expected .guest after bootstrap, got \(mocked.auth.status)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("bootstrap priorisiert Session über Guest")
|
||||
func bootstrapPrioritisesSession() throws {
|
||||
let mocked = makeMockedAuth()
|
||||
_ = try mocked.auth.enterGuestMode()
|
||||
try mocked.auth.persistSession(email: "u@x.de", accessToken: "a", refreshToken: "r")
|
||||
mocked.auth.bootstrap()
|
||||
#expect(mocked.auth.status == .signedIn(email: "u@x.de"))
|
||||
}
|
||||
|
||||
// MARK: - signOut(keepGuestMode:)
|
||||
|
||||
@Test("signOut Default löscht alles inkl. Guest-ID")
|
||||
func signOutDefaultClearsGuest() async throws {
|
||||
let mocked = makeMockedAuth()
|
||||
_ = try mocked.auth.enterGuestMode()
|
||||
try mocked.auth.persistSession(email: "u@x.de", accessToken: "a", refreshToken: "r")
|
||||
mocked.setHandler { _ in (200, Data()) }
|
||||
|
||||
await mocked.auth.signOut()
|
||||
#expect(mocked.auth.status == .signedOut)
|
||||
#expect(mocked.auth.currentGuestId() == nil)
|
||||
}
|
||||
|
||||
@Test("signOut(keepGuestMode: true) behält existierende Guest-ID")
|
||||
func signOutKeepsExistingGuest() async throws {
|
||||
let mocked = makeMockedAuth()
|
||||
let id = try mocked.auth.enterGuestMode()
|
||||
try mocked.auth.persistSession(email: "u@x.de", accessToken: "a", refreshToken: "r")
|
||||
mocked.setHandler { _ in (200, Data()) }
|
||||
|
||||
await mocked.auth.signOut(keepGuestMode: true)
|
||||
#expect(mocked.auth.status == .guest(id: id))
|
||||
#expect(mocked.auth.currentGuestId() == id)
|
||||
}
|
||||
|
||||
@Test("signOut(keepGuestMode: true) erzeugt neue Guest-ID wenn keine existiert")
|
||||
func signOutCreatesGuestWhenMissing() async throws {
|
||||
let mocked = makeMockedAuth()
|
||||
try mocked.auth.persistSession(email: "u@x.de", accessToken: "a", refreshToken: "r")
|
||||
mocked.setHandler { _ in (200, Data()) }
|
||||
|
||||
await mocked.auth.signOut(keepGuestMode: true)
|
||||
if case let .guest(id) = mocked.auth.status {
|
||||
#expect(!id.isEmpty)
|
||||
#expect(mocked.auth.currentGuestId() == id)
|
||||
} else {
|
||||
Issue.record("Expected .guest after signOut(keepGuestMode:), got \(mocked.auth.status)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - refreshAccessToken Resilience
|
||||
|
||||
@Test("refresh 503 wirft serviceUnavailable, behält Session")
|
||||
func refreshKeepsSessionOn503() async throws {
|
||||
let mocked = makeMockedAuth()
|
||||
try mocked.auth.persistSession(email: "u@x.de", accessToken: "a", refreshToken: "r")
|
||||
mocked.setHandler { _ in
|
||||
(503, Data(#"{"error":"SERVICE_UNAVAILABLE","status":503}"#.utf8))
|
||||
}
|
||||
|
||||
do {
|
||||
_ = try await mocked.auth.refreshAccessToken()
|
||||
Issue.record("Expected throw on 503")
|
||||
} catch let err as AuthError {
|
||||
#expect(err == .serviceUnavailable)
|
||||
}
|
||||
#expect(mocked.auth.status == .signedIn(email: "u@x.de"))
|
||||
}
|
||||
|
||||
@Test("refresh 500 wirft serverInternal, behält Session")
|
||||
func refreshKeepsSessionOn500() async throws {
|
||||
let mocked = makeMockedAuth()
|
||||
try mocked.auth.persistSession(email: "u@x.de", accessToken: "a", refreshToken: "r")
|
||||
mocked.setHandler { _ in
|
||||
(500, Data(#"{"error":"INTERNAL","status":500}"#.utf8))
|
||||
}
|
||||
|
||||
do {
|
||||
_ = try await mocked.auth.refreshAccessToken()
|
||||
Issue.record("Expected throw on 500")
|
||||
} catch let err as AuthError {
|
||||
#expect(err == .serverInternal)
|
||||
}
|
||||
#expect(mocked.auth.status == .signedIn(email: "u@x.de"))
|
||||
}
|
||||
|
||||
@Test("refresh 429 wirft rateLimited, behält Session")
|
||||
func refreshKeepsSessionOnRateLimit() async throws {
|
||||
let mocked = makeMockedAuth()
|
||||
try mocked.auth.persistSession(email: "u@x.de", accessToken: "a", refreshToken: "r")
|
||||
mocked.setHandler { _ in
|
||||
(429, Data(#"{"error":"RATE_LIMITED","retryAfterSec":30,"status":429}"#.utf8))
|
||||
}
|
||||
|
||||
do {
|
||||
_ = try await mocked.auth.refreshAccessToken()
|
||||
Issue.record("Expected throw on 429")
|
||||
} catch let err as AuthError {
|
||||
if case let .rateLimited(retryAfter) = err {
|
||||
#expect(retryAfter == 30)
|
||||
} else {
|
||||
Issue.record("Expected .rateLimited, got \(err)")
|
||||
}
|
||||
}
|
||||
#expect(mocked.auth.status == .signedIn(email: "u@x.de"))
|
||||
}
|
||||
|
||||
@Test("refresh 401 invalidiert Session ohne Guest → .signedOut")
|
||||
func refreshInvalidates401NoGuest() async throws {
|
||||
let mocked = makeMockedAuth()
|
||||
try mocked.auth.persistSession(email: "u@x.de", accessToken: "a", refreshToken: "r")
|
||||
mocked.setHandler { _ in
|
||||
(401, Data(#"{"error":"UNAUTHORIZED","status":401}"#.utf8))
|
||||
}
|
||||
|
||||
do {
|
||||
_ = try await mocked.auth.refreshAccessToken()
|
||||
Issue.record("Expected throw on 401")
|
||||
} catch let err as AuthError {
|
||||
#expect(err.invalidatesSession)
|
||||
}
|
||||
#expect(mocked.auth.status == .signedOut)
|
||||
}
|
||||
|
||||
@Test("refresh 401 mit Guest-ID fällt auf .guest zurück")
|
||||
func refreshInvalidates401WithGuest() async throws {
|
||||
let mocked = makeMockedAuth()
|
||||
let id = try mocked.auth.enterGuestMode()
|
||||
try mocked.auth.persistSession(email: "u@x.de", accessToken: "a", refreshToken: "r")
|
||||
mocked.setHandler { _ in
|
||||
(401, Data(#"{"error":"UNAUTHORIZED","status":401}"#.utf8))
|
||||
}
|
||||
|
||||
_ = try? await mocked.auth.refreshAccessToken()
|
||||
#expect(mocked.auth.status == .guest(id: id))
|
||||
#expect(mocked.auth.currentGuestId() == id)
|
||||
}
|
||||
|
||||
// MARK: - AuthError.invalidatesSession
|
||||
|
||||
@Test("invalidatesSession unterscheidet Session-Tot vs. transient")
|
||||
func invalidatesSessionPartitioning() {
|
||||
// Tot — Session muss weg
|
||||
#expect(AuthError.invalidCredentials.invalidatesSession)
|
||||
#expect(AuthError.unauthorized.invalidatesSession)
|
||||
#expect(AuthError.tokenExpired.invalidatesSession)
|
||||
#expect(AuthError.tokenInvalid.invalidatesSession)
|
||||
|
||||
// Transient — Session bleibt
|
||||
#expect(!AuthError.serviceUnavailable.invalidatesSession)
|
||||
#expect(!AuthError.serverInternal.invalidatesSession)
|
||||
#expect(!AuthError.networkFailure("offline").invalidatesSession)
|
||||
#expect(!AuthError.rateLimited(retryAfter: 30).invalidatesSession)
|
||||
#expect(!AuthError.accountLocked(retryAfter: nil).invalidatesSession)
|
||||
}
|
||||
}
|
||||
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")
|
||||
}
|
||||
}
|
||||
167
Tests/ManaCoreTests/AuthErrorClassifyTests.swift
Normal file
167
Tests/ManaCoreTests/AuthErrorClassifyTests.swift
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
import Foundation
|
||||
import Testing
|
||||
@testable import ManaCore
|
||||
|
||||
@Suite("AuthError.classify")
|
||||
struct AuthErrorClassifyTests {
|
||||
private func body(_ json: String) -> Data {
|
||||
Data(json.utf8)
|
||||
}
|
||||
|
||||
@Test("Mapped INVALID_CREDENTIALS auf invalidCredentials")
|
||||
func mapsInvalidCredentials() {
|
||||
let err = AuthError.classify(
|
||||
status: 401,
|
||||
data: body(#"{"error":"INVALID_CREDENTIALS","message":"Email oder Passwort falsch","status":401}"#)
|
||||
)
|
||||
#expect(err == .invalidCredentials)
|
||||
}
|
||||
|
||||
@Test("Mapped EMAIL_NOT_VERIFIED auf emailNotVerified")
|
||||
func mapsEmailNotVerified() {
|
||||
let err = AuthError.classify(
|
||||
status: 403,
|
||||
data: body(#"{"error":"EMAIL_NOT_VERIFIED","message":"Bitte bestätige…","status":403}"#)
|
||||
)
|
||||
#expect(err == .emailNotVerified)
|
||||
}
|
||||
|
||||
@Test("Mapped EMAIL_ALREADY_REGISTERED auf emailAlreadyRegistered")
|
||||
func mapsEmailAlreadyRegistered() {
|
||||
let err = AuthError.classify(
|
||||
status: 409,
|
||||
data: body(#"{"error":"EMAIL_ALREADY_REGISTERED","status":409}"#)
|
||||
)
|
||||
#expect(err == .emailAlreadyRegistered)
|
||||
}
|
||||
|
||||
@Test("WEAK_PASSWORD trägt Server-Message")
|
||||
func weakPasswordCarriesMessage() {
|
||||
let err = AuthError.classify(
|
||||
status: 400,
|
||||
data: body(#"{"error":"WEAK_PASSWORD","message":"Mindestens 8 Zeichen","status":400}"#)
|
||||
)
|
||||
if case let .weakPassword(message) = err {
|
||||
#expect(message == "Mindestens 8 Zeichen")
|
||||
} else {
|
||||
Issue.record("Expected .weakPassword, got \(err)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("RATE_LIMITED nutzt retryAfterSec aus Body")
|
||||
func rateLimitedFromBody() {
|
||||
let err = AuthError.classify(
|
||||
status: 429,
|
||||
data: body(#"{"error":"RATE_LIMITED","retryAfterSec":30,"status":429}"#)
|
||||
)
|
||||
if case let .rateLimited(retryAfter) = err {
|
||||
#expect(retryAfter == 30)
|
||||
} else {
|
||||
Issue.record("Expected .rateLimited(30), got \(err)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("RATE_LIMITED fällt auf Retry-After-Header zurück")
|
||||
func rateLimitedFromHeader() {
|
||||
let err = AuthError.classify(
|
||||
status: 429,
|
||||
data: body(#"{"error":"RATE_LIMITED","status":429}"#),
|
||||
retryAfterHeader: 60
|
||||
)
|
||||
if case let .rateLimited(retryAfter) = err {
|
||||
#expect(retryAfter == 60)
|
||||
} else {
|
||||
Issue.record("Expected .rateLimited(60), got \(err)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("ACCOUNT_LOCKED erhält retryAfter")
|
||||
func accountLockedRetryAfter() {
|
||||
let err = AuthError.classify(
|
||||
status: 423,
|
||||
data: body(#"{"error":"ACCOUNT_LOCKED","retryAfterSec":120,"status":423}"#)
|
||||
)
|
||||
if case let .accountLocked(retryAfter) = err {
|
||||
#expect(retryAfter == 120)
|
||||
} else {
|
||||
Issue.record("Expected .accountLocked(120), got \(err)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("SIGNUP_LIMIT_REACHED")
|
||||
func signupLimitReached() {
|
||||
let err = AuthError.classify(
|
||||
status: 429,
|
||||
data: body(#"{"error":"SIGNUP_LIMIT_REACHED","status":429}"#)
|
||||
)
|
||||
#expect(err == .signupLimitReached)
|
||||
}
|
||||
|
||||
@Test("TOKEN_EXPIRED und TOKEN_INVALID werden unterschieden")
|
||||
func tokenStates() {
|
||||
#expect(
|
||||
AuthError.classify(status: 400, data: body(#"{"error":"TOKEN_EXPIRED"}"#))
|
||||
== .tokenExpired
|
||||
)
|
||||
#expect(
|
||||
AuthError.classify(status: 400, data: body(#"{"error":"TOKEN_INVALID"}"#))
|
||||
== .tokenInvalid
|
||||
)
|
||||
}
|
||||
|
||||
@Test("VALIDATION trägt Message")
|
||||
func validationCarriesMessage() {
|
||||
let err = AuthError.classify(
|
||||
status: 400,
|
||||
data: body(#"{"error":"VALIDATION","message":"email is required","status":400}"#)
|
||||
)
|
||||
if case let .validation(message) = err {
|
||||
#expect(message == "email is required")
|
||||
} else {
|
||||
Issue.record("Expected .validation, got \(err)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Unbekannter Code mit Status 401 fällt auf invalidCredentials")
|
||||
func unknownCodeStatusHeuristic401() {
|
||||
let err = AuthError.classify(
|
||||
status: 401,
|
||||
data: body(#"{}"#)
|
||||
)
|
||||
#expect(err == .invalidCredentials)
|
||||
}
|
||||
|
||||
@Test("Unbekannter Code mit Status 503 fällt auf serviceUnavailable")
|
||||
func unknownCodeStatusHeuristic503() {
|
||||
let err = AuthError.classify(
|
||||
status: 503,
|
||||
data: body(#"{}"#)
|
||||
)
|
||||
#expect(err == .serviceUnavailable)
|
||||
}
|
||||
|
||||
@Test("Komplett kaputter Body führt zu serverError mit Status")
|
||||
func brokenBodyFallback() {
|
||||
let err = AuthError.classify(
|
||||
status: 500,
|
||||
data: body("nicht-json")
|
||||
)
|
||||
if case let .serverError(status, code, _) = err {
|
||||
#expect(status == 500)
|
||||
#expect(code == nil)
|
||||
} else {
|
||||
Issue.record("Expected .serverError(500), got \(err)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("errorDescription liefert deutsche Strings")
|
||||
func germanErrorDescriptions() {
|
||||
#expect(AuthError.invalidCredentials.errorDescription == "Email oder Passwort falsch")
|
||||
#expect(AuthError.emailAlreadyRegistered.errorDescription == "Diese Email ist bereits registriert.")
|
||||
#expect(
|
||||
AuthError.rateLimited(retryAfter: 30).errorDescription
|
||||
== "Zu viele Versuche. Bitte warte 30s."
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
127
Tests/ManaCoreTests/MockURLProtocol.swift
Normal file
127
Tests/ManaCoreTests/MockURLProtocol.swift
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
import Foundation
|
||||
@testable import ManaCore
|
||||
|
||||
/// URLProtocol-Mock mit Pro-Test-Routing: jede Test-AuthClient-
|
||||
/// Instanz kriegt eine eigene Test-ID als HTTP-Header, der Mock
|
||||
/// routet nach ID zum richtigen Handler. Das löst die Cross-Suite-
|
||||
/// Pollution (mehrere `.serialized`-Suites laufen untereinander
|
||||
/// parallel, der globale Handler-Slot wäre sonst ein Race).
|
||||
///
|
||||
/// Identisches Pattern wie in mana-swift-ui — wenn weitere Test-
|
||||
/// Helper hier hinzukommen, beide Pakete parallel halten.
|
||||
final class MockURLProtocol: URLProtocol, @unchecked Sendable {
|
||||
typealias Handler = @Sendable (URLRequest) -> Any
|
||||
|
||||
nonisolated(unsafe) static var handlersStorage: [String: Handler] = [:]
|
||||
static let handlersLock = NSLock()
|
||||
|
||||
static func register(testID: String, handler: @escaping Handler) {
|
||||
handlersLock.lock(); defer { handlersLock.unlock() }
|
||||
handlersStorage[testID] = handler
|
||||
}
|
||||
|
||||
static func unregister(testID: String) {
|
||||
handlersLock.lock(); defer { handlersLock.unlock() }
|
||||
handlersStorage.removeValue(forKey: testID)
|
||||
}
|
||||
|
||||
private static func lookup(testID: String) -> Handler? {
|
||||
handlersLock.lock(); defer { handlersLock.unlock() }
|
||||
return handlersStorage[testID]
|
||||
}
|
||||
|
||||
final class Capture: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var stored: URLRequest?
|
||||
|
||||
func store(_ r: URLRequest) {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
stored = r
|
||||
}
|
||||
|
||||
var request: URLRequest? {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
return stored
|
||||
}
|
||||
}
|
||||
|
||||
override class func canInit(with request: URLRequest) -> Bool { true }
|
||||
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
|
||||
override func stopLoading() {}
|
||||
|
||||
override func startLoading() {
|
||||
let testID = request.value(forHTTPHeaderField: "X-Test-ID") ?? ""
|
||||
guard let handler = MockURLProtocol.lookup(testID: testID) else {
|
||||
client?.urlProtocol(self, didFailWithError: URLError(.unknown))
|
||||
return
|
||||
}
|
||||
|
||||
let result = handler(request)
|
||||
let status: Int
|
||||
let body: Data
|
||||
let headers: [String: String]
|
||||
if let tuple = result as? (Int, Data, [String: String]) {
|
||||
status = tuple.0; body = tuple.1; headers = tuple.2
|
||||
} else if let tuple = result as? (Int, Data) {
|
||||
status = tuple.0; body = tuple.1; headers = [:]
|
||||
} else {
|
||||
client?.urlProtocol(self, didFailWithError: URLError(.unknown))
|
||||
return
|
||||
}
|
||||
|
||||
let response = HTTPURLResponse(
|
||||
url: request.url!,
|
||||
statusCode: status,
|
||||
httpVersion: "HTTP/1.1",
|
||||
headerFields: headers
|
||||
)!
|
||||
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
|
||||
client?.urlProtocol(self, didLoad: body)
|
||||
client?.urlProtocolDidFinishLoading(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Bündelt einen `AuthClient` mit seiner Test-ID.
|
||||
@MainActor
|
||||
struct MockedAuth {
|
||||
let auth: AuthClient
|
||||
let testID: String
|
||||
|
||||
func setHandler(_ handler: @escaping MockURLProtocol.Handler) {
|
||||
MockURLProtocol.register(testID: testID, handler: handler)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func makeMockedAuth() -> MockedAuth {
|
||||
let testID = UUID().uuidString
|
||||
let configuration = URLSessionConfiguration.ephemeral
|
||||
configuration.protocolClasses = [MockURLProtocol.self]
|
||||
configuration.httpAdditionalHeaders = ["X-Test-ID": testID]
|
||||
let session = URLSession(configuration: configuration)
|
||||
let config = DefaultManaAppConfig(
|
||||
authBaseURL: URL(string: "https://auth.test")!,
|
||||
keychainService: "ev.mana.test.\(testID)",
|
||||
keychainAccessGroup: nil
|
||||
)
|
||||
return MockedAuth(auth: AuthClient(config: config, session: session), testID: testID)
|
||||
}
|
||||
|
||||
extension URLRequest {
|
||||
/// Liest httpBodyStream in einen Data. URLSession ephemeral-Session
|
||||
/// nutzt manchmal Streams statt httpBody.
|
||||
func bodyStreamData() -> Data? {
|
||||
guard let stream = httpBodyStream else { return nil }
|
||||
stream.open(); defer { stream.close() }
|
||||
var data = Data()
|
||||
let bufferSize = 1024
|
||||
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
|
||||
defer { buffer.deallocate() }
|
||||
while stream.hasBytesAvailable {
|
||||
let read = stream.read(buffer, maxLength: bufferSize)
|
||||
if read <= 0 { break }
|
||||
data.append(buffer, count: read)
|
||||
}
|
||||
return data
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue