Compare commits
No commits in common. "main" and "v1.1.0" have entirely different histories.
27 changed files with 174 additions and 2769 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -5,4 +5,3 @@
|
||||||
Package.resolved
|
Package.resolved
|
||||||
xcuserdata/
|
xcuserdata/
|
||||||
DerivedData/
|
DerivedData/
|
||||||
build/
|
|
||||||
|
|
|
||||||
317
CHANGELOG.md
317
CHANGELOG.md
|
|
@ -4,323 +4,6 @@ Alle Änderungen werden hier dokumentiert. Format orientiert an
|
||||||
[Keep a Changelog](https://keepachangelog.com), Versionierung nach
|
[Keep a Changelog](https://keepachangelog.com), Versionierung nach
|
||||||
[Semver](https://semver.org).
|
[Semver](https://semver.org).
|
||||||
|
|
||||||
## [1.7.0] — 2026-05-17
|
|
||||||
|
|
||||||
Minor — **`ManaAppLog`** + `ManaAppConfig.appGroup`/`logSubsystem`.
|
|
||||||
Audit 2026-05-17 V4. Ersetzt das hand-getippte `Log.swift`-Boilerplate
|
|
||||||
in jeder App durch einen Config-getriebenen Wrapper.
|
|
||||||
|
|
||||||
### Neu
|
|
||||||
|
|
||||||
- `ManaAppLog` (public struct, Sendable) — Factory für OSLog-Logger
|
|
||||||
gegen ein `ManaAppConfig`. Standard-Kategorien `app`/`auth`/`api`/
|
|
||||||
`db`/`web`, plus `category("…")` für app-spezifische Kategorien.
|
|
||||||
- `ManaAppConfig.appGroup: String?` (default `nil`) — Single-Source
|
|
||||||
für den App-Group-String, der heute in jeder App 3-4× hardcoded
|
|
||||||
steht. Apps ohne Widget/ShareExt setzen weiterhin nichts.
|
|
||||||
- `ManaAppConfig.logSubsystem: String` (default = `keychainService`)
|
|
||||||
— Subsystem für `ManaAppLog`. In allen Apps heute schon
|
|
||||||
`ev.mana.<app>`, deshalb default sinnvoll.
|
|
||||||
|
|
||||||
### Geändert
|
|
||||||
|
|
||||||
- Nichts breaking. Beide neuen Felder haben Default-Implementations
|
|
||||||
im Protocol-Extension, bestehende Konsumenten von `ManaAppConfig`
|
|
||||||
brauchen nichts anzupassen.
|
|
||||||
- `DefaultManaAppConfig.init` hat zwei zusätzliche optionale Parameter
|
|
||||||
(`appGroup`, `logSubsystem`), beide mit `nil`-Defaults — Quellkompatibel.
|
|
||||||
|
|
||||||
### Tests
|
|
||||||
|
|
||||||
- 4 neue ManaAppConfig-Tests + 5 neue ManaAppLog-Tests. 85/85 grün
|
|
||||||
(vorher 76/76).
|
|
||||||
|
|
||||||
### Migrations-Hinweis
|
|
||||||
|
|
||||||
Apps können ihre lokale `Log.swift` von ~13 LOC auf ~5 LOC schrumpfen:
|
|
||||||
|
|
||||||
```swift
|
|
||||||
import ManaCore
|
|
||||||
|
|
||||||
enum Log {
|
|
||||||
private static let mana = ManaAppLog(AppConfig.manaAppConfig)
|
|
||||||
static let app = mana.app
|
|
||||||
static let auth = mana.auth
|
|
||||||
static let api = mana.api
|
|
||||||
static let study = mana.category("study") // app-spezifisch
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Plus `AppConfig.manaAppConfig` kann `appGroup: "group.ev.mana.<app>"`
|
|
||||||
ergänzen, damit der App-Group-String single-source ist.
|
|
||||||
|
|
||||||
## [1.6.0] — 2026-05-17
|
|
||||||
|
|
||||||
Minor — **`ManaTheme`-Variants** in ManaTokens. Acht Web-Themes aus
|
|
||||||
`@mana/themes` (mana, forest, paper, neutral, lume, twilight,
|
|
||||||
skylight, monochrome) sind jetzt als Swift verfügbar; generiert aus
|
|
||||||
den CSS-Quellen via `pnpm --filter @mana/themes gen:swift`.
|
|
||||||
|
|
||||||
Hintergrund: bisher haben Cards, Manaspur und Nutriphi je ~90 LOC
|
|
||||||
forest-HSL-Apparat lokal nachgebaut, weil ManaTokens nur die
|
|
||||||
mana-Variant kannte. Mit v1.6.0 sind diese App-lokalen Theme-Files
|
|
||||||
ablösbar (Audit 2026-05-17 Vorschlag V1).
|
|
||||||
|
|
||||||
### Neu
|
|
||||||
|
|
||||||
- `ManaTheme` (public enum) — `case mana | forest | paper | neutral
|
|
||||||
| lume | twilight | skylight | monochrome`. `String`-RawValue,
|
|
||||||
`CaseIterable`, `Sendable`.
|
|
||||||
- `ManaThemeColors` (public struct, Sendable) — die 12 Tokens als
|
|
||||||
`Color`-Properties. Per-Variant statisch verfügbar
|
|
||||||
(`ManaThemeColors.forest` usw.) aus der generierten Datei
|
|
||||||
`GeneratedThemes.swift`.
|
|
||||||
- `ManaTheme.colors` + Convenience-Accessoren (`.background`,
|
|
||||||
`.foreground`, …) — beide Schreibweisen funktionieren.
|
|
||||||
- `EnvironmentValues.manaTheme` + `View.manaTheme(_:)` —
|
|
||||||
SwiftUI-Environment, Default `.mana`. Apps mit User-Theme-Switching
|
|
||||||
setzen den Wert per `@AppStorage`-gestütztem Binding.
|
|
||||||
|
|
||||||
### Geändert
|
|
||||||
|
|
||||||
- Nichts breaking. `ManaColor.*` und `ManaBrand.*` bleiben unverändert
|
|
||||||
und liefern weiter die mana-Variant-Werte.
|
|
||||||
|
|
||||||
### Generator
|
|
||||||
|
|
||||||
- `mana/packages/themes/scripts/gen-swift-themes.mjs` liest die acht
|
|
||||||
CSS-Variant-Dateien und schreibt `GeneratedThemes.swift`. CI-Drift-
|
|
||||||
Check: nach Generator-Lauf `git diff --exit-code` in beiden Repos.
|
|
||||||
|
|
||||||
### Migrations-Hinweis
|
|
||||||
|
|
||||||
Apps können ihre lokalen `*Theme.swift`-Files (Cards, Manaspur,
|
|
||||||
Nutriphi) durch direkten Aufruf von `ManaTheme.<variant>` ersetzen.
|
|
||||||
Konvention: Apps mit fester Identität setzen `.manaTheme(.<variant>)`
|
|
||||||
an der App-Root; verschachtelte Views lesen via
|
|
||||||
`@Environment(\.manaTheme)`.
|
|
||||||
|
|
||||||
### Tests
|
|
||||||
|
|
||||||
- 7 neue Tests (`ThemeTests.swift`). 12/12 ManaTokens grün auf macOS.
|
|
||||||
|
|
||||||
## [1.5.1] — 2026-05-17
|
|
||||||
|
|
||||||
Patch — KeychainStore-Migration-Fallback. Bisher haben die mana-Apps
|
|
||||||
`keychainAccessGroup: nil` gesetzt; Apple legt das Item dann im
|
|
||||||
default-bucket (`$(AppIdentifierPrefix).$(BundleId)`) ab. Beim
|
|
||||||
Wechsel auf eine explizite `accessGroup` (Apps werden mit v1.5.1
|
|
||||||
nachgezogen) hätten User sonst beim ersten Start einen Logout
|
|
||||||
gesehen, weil Apples Read-mit-Group das alte Item nicht immer
|
|
||||||
liefert.
|
|
||||||
|
|
||||||
### Verändert
|
|
||||||
|
|
||||||
- `KeychainStore.getString(for:)` — bei `accessGroup != nil` und
|
|
||||||
einem Miss wird einmalig ohne `kSecAttrAccessGroup` re-queryt.
|
|
||||||
Findet sich der alte Eintrag im default-bucket, wird er in den
|
|
||||||
expliziten Bucket migriert und der alte gelöscht. Transparent für
|
|
||||||
alle Caller — `getString` liefert wie gewohnt den Wert zurück.
|
|
||||||
|
|
||||||
### Migrations-Hinweis
|
|
||||||
|
|
||||||
- Apps, die `keychainAccessGroup` ab v1.5.1 explizit setzen, brauchen
|
|
||||||
keinen Logout zu erwarten. Apps, die weiterhin `nil` setzen, sind
|
|
||||||
von dem Fallback nicht betroffen (er greift nur bei `accessGroup
|
|
||||||
!= nil`).
|
|
||||||
|
|
||||||
## [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
|
## [1.1.0] — 2026-05-13
|
||||||
|
|
||||||
Phase 1 aus dem Native-Auth-Vollausbau-Plan (Option A — alles nativ,
|
Phase 1 aus dem Native-Auth-Vollausbau-Plan (Option A — alles nativ,
|
||||||
|
|
|
||||||
|
|
@ -17,19 +17,16 @@ import Foundation
|
||||||
/// - `POST /change-password` — Passwort ändern (current + new)
|
/// - `POST /change-password` — Passwort ändern (current + new)
|
||||||
/// - `DELETE /account` — Account löschen (App-Store-Pflicht 5.1.1(v))
|
/// - `DELETE /account` — Account löschen (App-Store-Pflicht 5.1.1(v))
|
||||||
///
|
///
|
||||||
/// **Wire-Konvention für authenticated Account-Calls:**
|
/// **Server-Limitation (Stand 2026-05-13):** `change-email`,
|
||||||
/// `change-email`, `change-password` und `DELETE /account` forwarden
|
/// `change-password` und `DELETE /account` forwarden Original-Request-
|
||||||
/// die Original-Request-Headers an Better Auth (`auth.api.changeEmail`
|
/// Headers an Better Auth. Better Auth liest Session-Cookies. Der
|
||||||
/// etc.). Better Auth's `bearer`-Plugin (seit 2026-05-13 in mana-auth
|
/// `bearer`-Plugin von Better Auth ist NICHT installiert, daher
|
||||||
/// aktiv) konvertiert `Authorization: Bearer <session-token>` in
|
/// scheitern diese Endpoints heute mit reinem `Authorization: Bearer`.
|
||||||
/// einen synthetischen Session-Cookie. **Native-Apps senden hier den
|
/// → Server-Fix in Phase 3 nötig (entweder `bearerPlugin()` in
|
||||||
/// Session-Token (`refreshToken`-Feldwert aus /login bzw. /refresh),
|
/// `better-auth.config.ts` aktivieren oder Custom-Bearer-Resolver in
|
||||||
/// NICHT den JWT.** Der JWT bleibt für app-eigene Backends
|
/// `mana-auth/src/routes/auth.ts` ergänzen). ManaCore sendet Bearer
|
||||||
/// (memoro-api, cardecky-api etc.) der richtige Header.
|
/// bereits korrekt — sobald der Server das akzeptiert, funktionieren
|
||||||
///
|
/// die Methoden ohne Swift-Änderung.
|
||||||
/// 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 {
|
public extension AuthClient {
|
||||||
// MARK: - Registrierung
|
// MARK: - Registrierung
|
||||||
|
|
||||||
|
|
@ -299,9 +296,7 @@ public extension AuthClient {
|
||||||
|
|
||||||
extension AuthClient {
|
extension AuthClient {
|
||||||
/// Generischer JSON-POST/DELETE-Helper. Wenn `authenticated == true`,
|
/// Generischer JSON-POST/DELETE-Helper. Wenn `authenticated == true`,
|
||||||
/// wird der Session-Token (`refreshToken`-Feldwert, von Better Auth
|
/// wird der aktuelle Bearer-Token mitgeschickt.
|
||||||
/// als Session-ID interpretierbar via `bearer`-Plugin) als Bearer-
|
|
||||||
/// Header mitgeschickt — NICHT der JWT. Siehe Doc-Header dieser Datei.
|
|
||||||
fileprivate func postJSON<Body: Encodable>(
|
fileprivate func postJSON<Body: Encodable>(
|
||||||
path: String,
|
path: String,
|
||||||
method: String = "POST",
|
method: String = "POST",
|
||||||
|
|
@ -313,7 +308,7 @@ extension AuthClient {
|
||||||
request.httpMethod = method
|
request.httpMethod = method
|
||||||
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||||
if authenticated {
|
if authenticated {
|
||||||
let token = try currentSessionToken()
|
let token = try currentAccessToken()
|
||||||
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
||||||
}
|
}
|
||||||
do {
|
do {
|
||||||
|
|
@ -388,348 +383,3 @@ private struct ChangePasswordRequest: Encodable {
|
||||||
private struct DeleteAccountRequest: Encodable {
|
private struct DeleteAccountRequest: Encodable {
|
||||||
let password: String
|
let password: String
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Two-Factor (Login-Challenge)
|
|
||||||
|
|
||||||
public extension AuthClient {
|
|
||||||
/// Verifiziert einen TOTP-Code im 2FA-Login-Flow. Vorbedingung:
|
|
||||||
/// Status ist ``Status/twoFactorRequired(token:methods:email:)``
|
|
||||||
/// (typisch nach `signIn(...)`).
|
|
||||||
///
|
|
||||||
/// Bei Erfolg setzt der Server die Session, ManaCore persistiert
|
|
||||||
/// Tokens und der Status wird `.signedIn(email:)`.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - code: 6-stelliger TOTP-Code aus der Authenticator-App.
|
|
||||||
/// - trustDevice: Wenn `true`, setzt der Server einen
|
|
||||||
/// `trust_device`-Cookie. Bei Native heute ohne Effekt
|
|
||||||
/// (Cookies werden nicht persistiert) — wir spiegeln das Flag
|
|
||||||
/// trotzdem für künftige Erweiterungen.
|
|
||||||
///
|
|
||||||
/// - Throws: ``AuthError/twoFactorFailed`` bei falschem Code,
|
|
||||||
/// ``AuthError/tokenExpired`` wenn der Challenge-Token alt ist,
|
|
||||||
/// plus Standard-Netzwerk-Fehler.
|
|
||||||
func verifyTotp(code: String, trustDevice: Bool = false) async throws {
|
|
||||||
try await verifyTwoFactor(
|
|
||||||
path: "/api/v1/auth/two-factor/verify-totp",
|
|
||||||
code: code,
|
|
||||||
trustDevice: trustDevice
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Verifiziert einen Backup-Code im 2FA-Login-Flow. Same Pre-/
|
|
||||||
/// Postconditions wie ``verifyTotp(code:trustDevice:)`` — der
|
|
||||||
/// Server entscheidet anhand des Endpoints, welches Verfahren er
|
|
||||||
/// nutzt. Backup-Codes werden vom Server beim Setup generiert
|
|
||||||
/// und einmalig konsumiert.
|
|
||||||
func verifyBackupCode(code: String, trustDevice: Bool = false) async throws {
|
|
||||||
try await verifyTwoFactor(
|
|
||||||
path: "/api/v1/auth/two-factor/verify-backup-code",
|
|
||||||
code: code,
|
|
||||||
trustDevice: trustDevice
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func verifyTwoFactor(
|
|
||||||
path: String,
|
|
||||||
code: String,
|
|
||||||
trustDevice: Bool
|
|
||||||
) async throws {
|
|
||||||
guard case let .twoFactorRequired(token, _, email) = status else {
|
|
||||||
throw AuthError.validation(
|
|
||||||
message: "Kein 2FA-Challenge aktiv — verifyTotp setzt eine vorherige signIn-Antwort mit .twoFactorRequired voraus"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
guard !code.isEmpty else {
|
|
||||||
throw AuthError.validation(message: "Code ist erforderlich")
|
|
||||||
}
|
|
||||||
|
|
||||||
let body = TwoFactorVerifyRequest(
|
|
||||||
code: code,
|
|
||||||
twoFactorToken: token,
|
|
||||||
trustDevice: trustDevice
|
|
||||||
)
|
|
||||||
let (data, http) = try await postJSON(path: path, body: body)
|
|
||||||
guard http.statusCode == 200 else {
|
|
||||||
throw AuthError.classify(
|
|
||||||
status: http.statusCode,
|
|
||||||
data: data,
|
|
||||||
retryAfterHeader: http.retryAfterSeconds
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
let token2 = try JSONDecoder().decode(TwoFactorVerifyResponse.self, from: data)
|
|
||||||
guard let access = token2.accessToken, let refresh = token2.refreshToken else {
|
|
||||||
// Server hat 200 zurück, aber keine Tokens. Sollte nicht
|
|
||||||
// passieren — UI bleibt im 2FA-Required-Zustand.
|
|
||||||
throw AuthError.decoding("Tokens fehlen in 2FA-Verify-Antwort")
|
|
||||||
}
|
|
||||||
|
|
||||||
try persistSession(email: email, accessToken: access, refreshToken: refresh)
|
|
||||||
CoreLog.auth.info("2FA verify successful — signed in")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private struct TwoFactorVerifyRequest: Encodable {
|
|
||||||
let code: String
|
|
||||||
let twoFactorToken: String
|
|
||||||
let trustDevice: Bool
|
|
||||||
}
|
|
||||||
|
|
||||||
private struct TwoFactorVerifyResponse: Decodable {
|
|
||||||
let success: Bool?
|
|
||||||
let accessToken: String?
|
|
||||||
let refreshToken: String?
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Two-Factor (Enrollment)
|
|
||||||
|
|
||||||
/// Ergebnis von ``AuthClient/enrollTotp(password:)``: enthält die
|
|
||||||
/// otpauth-URI (für QR-Code-Display) und die Backup-Codes. Backup-
|
|
||||||
/// Codes sind einmalig nutzbar und sollten dem User zum Sichern
|
|
||||||
/// (Kopieren/Drucken) angeboten werden — der Server zeigt sie nie
|
|
||||||
/// mehr.
|
|
||||||
public struct TotpEnrollment: Sendable, Equatable {
|
|
||||||
/// `otpauth://totp/Issuer:email?secret=...&...`-URI. Direkt als
|
|
||||||
/// QR-Code rendern (z.B. via `CIFilter.qrCodeGenerator`).
|
|
||||||
public let totpURI: String
|
|
||||||
|
|
||||||
/// Liste der Backup-Codes (üblich 10 Stück). Der User sollte sie
|
|
||||||
/// sicher aufbewahren — bei Verlust des TOTP-Geräts sind sie der
|
|
||||||
/// einzige Fallback. Server merkt sich nur Hashes; bei Verbrauch
|
|
||||||
/// werden sie als consumed markiert.
|
|
||||||
public let backupCodes: [String]
|
|
||||||
}
|
|
||||||
|
|
||||||
public extension AuthClient {
|
|
||||||
/// Aktiviert TOTP-2FA für den aktuellen Account.
|
|
||||||
///
|
|
||||||
/// Re-Auth via aktuellem Passwort. Bei Erfolg generiert der Server
|
|
||||||
/// ein TOTP-Secret und gibt die otpauth-URI + Backup-Codes zurück.
|
|
||||||
/// Die App rendert die URI als QR-Code, der User scannt mit
|
|
||||||
/// Authenticator-App und gibt zur Bestätigung den ersten Code ein —
|
|
||||||
/// dieser zweite Schritt läuft über die regulären
|
|
||||||
/// ``verifyTotp(code:trustDevice:)``-Methode oder einen Re-Auth
|
|
||||||
/// signIn → twoFactorRequired-Flow (der Server entscheidet).
|
|
||||||
///
|
|
||||||
/// - Important: Nutzt den Session-Token als Bearer (Wire-Konvention
|
|
||||||
/// für mana-auth-Account-Endpoints, siehe Doc-Header dieser Datei).
|
|
||||||
func enrollTotp(password: String) async throws -> TotpEnrollment {
|
|
||||||
guard !password.isEmpty else {
|
|
||||||
throw AuthError.validation(message: "Passwort ist erforderlich")
|
|
||||||
}
|
|
||||||
|
|
||||||
let body = TotpEnableRequest(password: password)
|
|
||||||
let (data, http) = try await postJSON(
|
|
||||||
path: "/api/v1/auth/two-factor/enable",
|
|
||||||
body: body,
|
|
||||||
authenticated: true
|
|
||||||
)
|
|
||||||
guard http.statusCode == 200 else {
|
|
||||||
throw AuthError.classify(
|
|
||||||
status: http.statusCode,
|
|
||||||
data: data,
|
|
||||||
retryAfterHeader: http.retryAfterSeconds
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
let decoded = try JSONDecoder().decode(TotpEnableResponse.self, from: data)
|
|
||||||
guard let uri = decoded.totpURI else {
|
|
||||||
throw AuthError.decoding("totpURI fehlt in Enroll-Antwort")
|
|
||||||
}
|
|
||||||
CoreLog.auth.info("2FA TOTP enrollment initiated")
|
|
||||||
return TotpEnrollment(totpURI: uri, backupCodes: decoded.backupCodes ?? [])
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Deaktiviert TOTP-2FA für den aktuellen Account. Re-Auth via
|
|
||||||
/// Passwort.
|
|
||||||
func disableTotp(password: String) async throws {
|
|
||||||
guard !password.isEmpty else {
|
|
||||||
throw AuthError.validation(message: "Passwort ist erforderlich")
|
|
||||||
}
|
|
||||||
|
|
||||||
let body = TotpEnableRequest(password: password)
|
|
||||||
let (data, http) = try await postJSON(
|
|
||||||
path: "/api/v1/auth/two-factor/disable",
|
|
||||||
body: body,
|
|
||||||
authenticated: true
|
|
||||||
)
|
|
||||||
guard http.statusCode == 200 else {
|
|
||||||
throw AuthError.classify(
|
|
||||||
status: http.statusCode,
|
|
||||||
data: data,
|
|
||||||
retryAfterHeader: http.retryAfterSeconds
|
|
||||||
)
|
|
||||||
}
|
|
||||||
CoreLog.auth.info("2FA TOTP disabled")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Liefert die otpauth-URI des aktuellen TOTP-Secrets. Nützlich
|
|
||||||
/// wenn der User den QR-Code erneut sehen will (z.B. zweites
|
|
||||||
/// Gerät einrichten). Re-Auth via Passwort.
|
|
||||||
///
|
|
||||||
/// - Returns: `otpauth://totp/…`-URI, direkt als QR-Code renderbar.
|
|
||||||
func getTotpUri(password: String) async throws -> String {
|
|
||||||
guard !password.isEmpty else {
|
|
||||||
throw AuthError.validation(message: "Passwort ist erforderlich")
|
|
||||||
}
|
|
||||||
|
|
||||||
let body = TotpEnableRequest(password: password)
|
|
||||||
let (data, http) = try await postJSON(
|
|
||||||
path: "/api/v1/auth/two-factor/get-totp-uri",
|
|
||||||
body: body,
|
|
||||||
authenticated: true
|
|
||||||
)
|
|
||||||
guard http.statusCode == 200 else {
|
|
||||||
throw AuthError.classify(
|
|
||||||
status: http.statusCode,
|
|
||||||
data: data,
|
|
||||||
retryAfterHeader: http.retryAfterSeconds
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
let decoded = try JSONDecoder().decode(TotpEnableResponse.self, from: data)
|
|
||||||
guard let uri = decoded.totpURI else {
|
|
||||||
throw AuthError.decoding("totpURI fehlt in get-totp-uri-Antwort")
|
|
||||||
}
|
|
||||||
return uri
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Regeneriert die Backup-Codes. Alte Codes werden ungültig. Der
|
|
||||||
/// User sollte die neuen direkt sichern.
|
|
||||||
func regenerateBackupCodes(password: String) async throws -> [String] {
|
|
||||||
guard !password.isEmpty else {
|
|
||||||
throw AuthError.validation(message: "Passwort ist erforderlich")
|
|
||||||
}
|
|
||||||
|
|
||||||
let body = TotpEnableRequest(password: password)
|
|
||||||
let (data, http) = try await postJSON(
|
|
||||||
path: "/api/v1/auth/two-factor/generate-backup-codes",
|
|
||||||
body: body,
|
|
||||||
authenticated: true
|
|
||||||
)
|
|
||||||
guard http.statusCode == 200 else {
|
|
||||||
throw AuthError.classify(
|
|
||||||
status: http.statusCode,
|
|
||||||
data: data,
|
|
||||||
retryAfterHeader: http.retryAfterSeconds
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
let decoded = try JSONDecoder().decode(TotpEnableResponse.self, from: data)
|
|
||||||
guard let codes = decoded.backupCodes else {
|
|
||||||
throw AuthError.decoding("backupCodes fehlen in Antwort")
|
|
||||||
}
|
|
||||||
return codes
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private struct TotpEnableRequest: Encodable {
|
|
||||||
let password: String
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Antwort-Format für alle Enrollment-Endpoints. Felder sind optional
|
|
||||||
/// damit derselbe Type für `enable` (beide), `get-totp-uri` (nur URI)
|
|
||||||
/// und `generate-backup-codes` (nur Codes) dekodierbar ist.
|
|
||||||
private struct TotpEnableResponse: Decodable {
|
|
||||||
let totpURI: String?
|
|
||||||
let backupCodes: [String]?
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Profile
|
|
||||||
|
|
||||||
/// Subset des Server-User-Profiles, das die Apps für UI-Entscheidungen
|
|
||||||
/// brauchen. Wird von ``AuthClient/getProfile()`` geliefert.
|
|
||||||
///
|
|
||||||
/// Server-Quelle: `GET /api/v1/auth/profile` (→ Better Auths
|
|
||||||
/// `/api/auth/get-session`). Returnt `{user: {…}, session: {…}}`.
|
|
||||||
/// Wir nehmen nur die UI-relevanten Felder mit.
|
|
||||||
public struct ProfileInfo: Sendable, Equatable {
|
|
||||||
public let id: String
|
|
||||||
public let email: String
|
|
||||||
public let name: String?
|
|
||||||
public let emailVerified: Bool
|
|
||||||
/// `true` wenn der User TOTP-2FA aktiviert hat. Apps zeigen
|
|
||||||
/// dann den Disable-/Regenerate-Pfad statt des Enroll-Wizards.
|
|
||||||
public let twoFactorEnabled: Bool
|
|
||||||
|
|
||||||
public init(
|
|
||||||
id: String,
|
|
||||||
email: String,
|
|
||||||
name: String?,
|
|
||||||
emailVerified: Bool,
|
|
||||||
twoFactorEnabled: Bool
|
|
||||||
) {
|
|
||||||
self.id = id
|
|
||||||
self.email = email
|
|
||||||
self.name = name
|
|
||||||
self.emailVerified = emailVerified
|
|
||||||
self.twoFactorEnabled = twoFactorEnabled
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public extension AuthClient {
|
|
||||||
/// Lädt das aktuelle Profil des eingeloggten Users vom Server.
|
|
||||||
///
|
|
||||||
/// - Important: Nutzt den Session-Token als Bearer (Wire-Konvention
|
|
||||||
/// für mana-auth-Endpoints, siehe Doc-Header dieser Datei).
|
|
||||||
///
|
|
||||||
/// - Throws: ``AuthError/notSignedIn`` ohne Session,
|
|
||||||
/// ``AuthError/unauthorized`` wenn Server den Token rejected,
|
|
||||||
/// Netzwerk-Cases.
|
|
||||||
func getProfile() async throws -> ProfileInfo {
|
|
||||||
let token = try currentSessionToken()
|
|
||||||
let url = config.authBaseURL.appending(path: "/api/v1/auth/profile")
|
|
||||||
var request = URLRequest(url: url)
|
|
||||||
request.httpMethod = "GET"
|
|
||||||
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
|
||||||
|
|
||||||
let (data, http): (Data, HTTPURLResponse)
|
|
||||||
do {
|
|
||||||
let (d, r) = try await session.data(for: request)
|
|
||||||
guard let h = r as? HTTPURLResponse else {
|
|
||||||
throw AuthError.networkFailure("Keine HTTP-Antwort")
|
|
||||||
}
|
|
||||||
data = d
|
|
||||||
http = h
|
|
||||||
} catch let error as URLError {
|
|
||||||
throw AuthError.networkFailure(error.localizedDescription)
|
|
||||||
}
|
|
||||||
|
|
||||||
guard http.statusCode == 200 else {
|
|
||||||
throw AuthError.classify(
|
|
||||||
status: http.statusCode,
|
|
||||||
data: data,
|
|
||||||
retryAfterHeader: http.retryAfterSeconds
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
let envelope = try JSONDecoder().decode(ProfileEnvelope.self, from: data)
|
|
||||||
guard let user = envelope.user else {
|
|
||||||
throw AuthError.decoding("user-Feld fehlt in profile-Antwort")
|
|
||||||
}
|
|
||||||
|
|
||||||
return ProfileInfo(
|
|
||||||
id: user.id,
|
|
||||||
email: user.email,
|
|
||||||
name: user.name,
|
|
||||||
emailVerified: user.emailVerified ?? false,
|
|
||||||
twoFactorEnabled: user.twoFactorEnabled ?? false
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wire-Format-Hülle für `GET /api/v1/auth/profile`. Better-Auth-
|
|
||||||
/// `/api/auth/get-session` returnt `{user: {...}, session: {...}}`;
|
|
||||||
/// wir lesen `user` und ignorieren `session`.
|
|
||||||
private struct ProfileEnvelope: Decodable {
|
|
||||||
let user: ProfileUser?
|
|
||||||
}
|
|
||||||
|
|
||||||
private struct ProfileUser: Decodable {
|
|
||||||
let id: String
|
|
||||||
let email: String
|
|
||||||
let name: String?
|
|
||||||
let emailVerified: Bool?
|
|
||||||
let twoFactorEnabled: Bool?
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -15,27 +15,9 @@ import Observation
|
||||||
@Observable
|
@Observable
|
||||||
public final class AuthClient {
|
public final class AuthClient {
|
||||||
public enum Status: Equatable, Sendable {
|
public enum Status: Equatable, Sendable {
|
||||||
/// Vor `bootstrap()` — Keychain noch nicht ausgewertet.
|
|
||||||
case unknown
|
case unknown
|
||||||
/// Kein Account, keine Guest-Identität. UI sollte Login/Sign-Up
|
|
||||||
/// anbieten oder via `enterGuestMode()` einen anonymen Modus
|
|
||||||
/// starten.
|
|
||||||
case signedOut
|
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
|
case signingIn
|
||||||
/// Sign-In war erfolgreich aber der Account hat 2FA aktiviert.
|
|
||||||
/// UI fragt nun den TOTP-Code (oder einen Backup-Code) ab und
|
|
||||||
/// ruft `verifyTotp(code:trustDevice:)` / `verifyBackupCode(...)`
|
|
||||||
/// mit dem hier gespeicherten Token auf.
|
|
||||||
///
|
|
||||||
/// `token` ist der Better-Auth-`two_factor`-Cookie-Wert, vom
|
|
||||||
/// Server in der Login-Response als `twoFactorToken` mitgeliefert.
|
|
||||||
case twoFactorRequired(token: String, methods: [String], email: String)
|
|
||||||
case signedIn(email: String)
|
case signedIn(email: String)
|
||||||
case error(String)
|
case error(String)
|
||||||
}
|
}
|
||||||
|
|
@ -67,73 +49,16 @@ public final class AuthClient {
|
||||||
return nil
|
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() {
|
public func bootstrap() {
|
||||||
let email = keychain.getString(for: .email)
|
let email = keychain.getString(for: .email)
|
||||||
let hasToken = keychain.getString(for: .accessToken) != nil
|
let hasToken = keychain.getString(for: .accessToken) != nil
|
||||||
if let email, hasToken {
|
if let email, hasToken {
|
||||||
status = .signedIn(email: email)
|
status = .signedIn(email: email)
|
||||||
} else if let guestId = keychain.getString(for: .guestId) {
|
|
||||||
status = .guest(id: guestId)
|
|
||||||
} else {
|
} else {
|
||||||
status = .signedOut
|
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 {
|
public func signIn(email: String, password: String) async {
|
||||||
let trimmed = email.trimmingCharacters(in: .whitespacesAndNewlines)
|
let trimmed = email.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
guard !trimmed.isEmpty, !password.isEmpty else {
|
guard !trimmed.isEmpty, !password.isEmpty else {
|
||||||
|
|
@ -168,23 +93,6 @@ public final class AuthClient {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2FA-Pfad: Server hat statt Tokens einen
|
|
||||||
// `twoFactorRequired`-Response geliefert. UI muss jetzt
|
|
||||||
// den TOTP-Code abfragen und `verifyTotp(...)` aufrufen.
|
|
||||||
if let twoFactor = try? JSONDecoder().decode(TwoFactorChallenge.self, from: data),
|
|
||||||
twoFactor.twoFactorRequired == true,
|
|
||||||
let tfToken = twoFactor.twoFactorToken
|
|
||||||
{
|
|
||||||
status = .twoFactorRequired(
|
|
||||||
token: tfToken,
|
|
||||||
methods: twoFactor.twoFactorMethods ?? ["totp"],
|
|
||||||
email: trimmed
|
|
||||||
)
|
|
||||||
lastError = nil
|
|
||||||
CoreLog.auth.info("Sign-in needs 2FA challenge")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
let token = try JSONDecoder().decode(TokenResponse.self, from: data)
|
let token = try JSONDecoder().decode(TokenResponse.self, from: data)
|
||||||
try keychain.setString(token.accessToken, for: .accessToken)
|
try keychain.setString(token.accessToken, for: .accessToken)
|
||||||
try keychain.setString(token.refreshToken, for: .refreshToken)
|
try keychain.setString(token.refreshToken, for: .refreshToken)
|
||||||
|
|
@ -205,15 +113,7 @@ public final class AuthClient {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Logged den User aus. Versucht den Server zu informieren (Logout-
|
public func signOut() async {
|
||||||
/// 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) {
|
if let token = keychain.getString(for: .accessToken) {
|
||||||
let url = config.authBaseURL.appending(path: "/api/v1/auth/logout")
|
let url = config.authBaseURL.appending(path: "/api/v1/auth/logout")
|
||||||
var request = URLRequest(url: url)
|
var request = URLRequest(url: url)
|
||||||
|
|
@ -222,20 +122,8 @@ public final class AuthClient {
|
||||||
_ = try? await session.data(for: request)
|
_ = try? await session.data(for: request)
|
||||||
}
|
}
|
||||||
keychain.wipe()
|
keychain.wipe()
|
||||||
if keepGuestMode {
|
status = .signedOut
|
||||||
if let existing = keychain.getString(for: .guestId) {
|
CoreLog.auth.info("Signed out")
|
||||||
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 {
|
public func currentAccessToken() throws -> String {
|
||||||
|
|
@ -245,19 +133,6 @@ public final class AuthClient {
|
||||||
return token
|
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
|
/// Liefert einen Access-Token, der nicht innerhalb der nächsten
|
||||||
/// `refreshLeeway` Sekunden abläuft. Refreshed proaktiv, wenn nötig.
|
/// `refreshLeeway` Sekunden abläuft. Refreshed proaktiv, wenn nötig.
|
||||||
public func freshAccessToken(refreshLeeway: TimeInterval = 300) async throws -> String {
|
public func freshAccessToken(refreshLeeway: TimeInterval = 300) async throws -> String {
|
||||||
|
|
@ -284,30 +159,13 @@ public final class AuthClient {
|
||||||
throw AuthError.networkFailure("Keine HTTP-Antwort")
|
throw AuthError.networkFailure("Keine HTTP-Antwort")
|
||||||
}
|
}
|
||||||
guard http.statusCode == 200 else {
|
guard http.statusCode == 200 else {
|
||||||
let err = AuthError.classify(
|
keychain.wipe()
|
||||||
|
status = .signedOut
|
||||||
|
throw AuthError.classify(
|
||||||
status: http.statusCode,
|
status: http.statusCode,
|
||||||
data: data,
|
data: data,
|
||||||
retryAfterHeader: http.retryAfterSeconds
|
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)
|
let token = try JSONDecoder().decode(TokenResponse.self, from: data)
|
||||||
|
|
@ -331,12 +189,10 @@ public final class AuthClient {
|
||||||
status = .signedIn(email: email)
|
status = .signedIn(email: email)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Setzt den Status auf `.signedOut` und wirft den Keychain
|
/// Setzt den Status auf `.signedOut` und wirft den Keychain leer.
|
||||||
/// vollständig leer — inklusive Guest-ID. Genutzt nach
|
/// Genutzt nach `deleteAccount()`.
|
||||||
/// `deleteAccount()`: Account ist gelöscht, also auch die
|
|
||||||
/// (potenziell verknüpfte) anonyme Identität.
|
|
||||||
func clearSession() {
|
func clearSession() {
|
||||||
keychain.wipeAll()
|
keychain.wipe()
|
||||||
status = .signedOut
|
status = .signedOut
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -364,16 +220,6 @@ struct TokenResponse: Decodable {
|
||||||
let refreshToken: String
|
let refreshToken: String
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 2FA-Pfad aus `/api/v1/auth/login`. Wenn `twoFactorRequired == true`,
|
|
||||||
/// kein Token-Paar — UI muss `verifyTotp(...)` / `verifyBackupCode(...)`
|
|
||||||
/// aufrufen. `twoFactorToken` ist der Server-injecten `two_factor`-Cookie-
|
|
||||||
/// Wert (opaque).
|
|
||||||
struct TwoFactorChallenge: Decodable {
|
|
||||||
let twoFactorRequired: Bool?
|
|
||||||
let twoFactorMethods: [String]?
|
|
||||||
let twoFactorToken: String?
|
|
||||||
}
|
|
||||||
|
|
||||||
extension HTTPURLResponse {
|
extension HTTPURLResponse {
|
||||||
/// Liest `Retry-After` als Anzahl Sekunden. Server schickt Integer-
|
/// Liest `Retry-After` als Anzahl Sekunden. Server schickt Integer-
|
||||||
/// Sekunden (siehe `lib/auth-errors.ts`). HTTP-Datum-Variante wird
|
/// Sekunden (siehe `lib/auth-errors.ts`). HTTP-Datum-Variante wird
|
||||||
|
|
|
||||||
|
|
@ -126,49 +126,6 @@ public enum AuthError: Error, LocalizedError, Sendable, Equatable {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `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
|
/// Klassifiziert eine `mana-auth`-Fehler-Antwort. `data` ist der
|
||||||
/// Response-Body, `status` der HTTP-Status, `retryAfterHeader` der
|
/// Response-Body, `status` der HTTP-Status, `retryAfterHeader` der
|
||||||
/// `Retry-After`-Header-Wert in Sekunden (falls vorhanden).
|
/// `Retry-After`-Header-Wert in Sekunden (falls vorhanden).
|
||||||
|
|
|
||||||
|
|
@ -5,18 +5,10 @@ import Security
|
||||||
/// pro `ManaAppConfig`.
|
/// pro `ManaAppConfig`.
|
||||||
public final class KeychainStore: Sendable {
|
public final class KeychainStore: Sendable {
|
||||||
/// Bekannte Keys für mana-auth-Tokens.
|
/// 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 {
|
public enum Key: String, Sendable {
|
||||||
case accessToken = "access_token"
|
case accessToken = "access_token"
|
||||||
case refreshToken = "refresh_token"
|
case refreshToken = "refresh_token"
|
||||||
case email
|
case email
|
||||||
case guestId = "guest_id"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private let service: String
|
private let service: String
|
||||||
|
|
@ -61,40 +53,10 @@ public final class KeychainStore: Sendable {
|
||||||
query[kSecMatchLimit] = kSecMatchLimitOne
|
query[kSecMatchLimit] = kSecMatchLimitOne
|
||||||
var result: AnyObject?
|
var result: AnyObject?
|
||||||
let status = SecItemCopyMatching(query as CFDictionary, &result)
|
let status = SecItemCopyMatching(query as CFDictionary, &result)
|
||||||
if status == errSecSuccess, let data = result as? Data {
|
guard status == errSecSuccess, let data = result as? Data else {
|
||||||
return String(data: data, encoding: .utf8)
|
|
||||||
}
|
|
||||||
|
|
||||||
// One-shot migration: bis v1.2.0 haben die mana-Apps Keychain-
|
|
||||||
// Items ohne explizite `kSecAttrAccessGroup` geschrieben. Apple
|
|
||||||
// hat sie dann im default-bucket (= `$(AppIdentifierPrefix).$(BundleId)`)
|
|
||||||
// gelandet. Ab v1.2.1 setzen die Apps die accessGroup explizit
|
|
||||||
// auf denselben Identifier. In den meisten Fällen liefert Apple
|
|
||||||
// das alte Item beim Read-mit-Group transparent zurück — wenn
|
|
||||||
// nicht, hat das einen Logout zur Folge. Dieser Fallback liest
|
|
||||||
// den Item nochmal ohne accessGroup, schreibt ihn beim Erfolg
|
|
||||||
// mit accessGroup neu in den expliziten Bucket und löscht den
|
|
||||||
// alten Eintrag.
|
|
||||||
guard accessGroup != nil else { return nil }
|
|
||||||
var fallback: [CFString: Any] = [
|
|
||||||
kSecClass: kSecClassGenericPassword,
|
|
||||||
kSecAttrService: service,
|
|
||||||
kSecAttrAccount: key.rawValue,
|
|
||||||
kSecReturnData: true,
|
|
||||||
kSecMatchLimit: kSecMatchLimitOne,
|
|
||||||
]
|
|
||||||
var fallbackResult: AnyObject?
|
|
||||||
guard SecItemCopyMatching(fallback as CFDictionary, &fallbackResult) == errSecSuccess,
|
|
||||||
let data = fallbackResult as? Data,
|
|
||||||
let value = String(data: data, encoding: .utf8)
|
|
||||||
else {
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
try? setString(value, for: key)
|
return String(data: data, encoding: .utf8)
|
||||||
fallback.removeValue(forKey: kSecReturnData)
|
|
||||||
fallback.removeValue(forKey: kSecMatchLimit)
|
|
||||||
SecItemDelete(fallback as CFDictionary)
|
|
||||||
return value
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public func remove(for key: Key) {
|
public func remove(for key: Key) {
|
||||||
|
|
@ -102,22 +64,12 @@ public final class KeychainStore: Sendable {
|
||||||
SecItemDelete(query as CFDictionary)
|
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() {
|
public func wipe() {
|
||||||
remove(for: .accessToken)
|
remove(for: .accessToken)
|
||||||
remove(for: .refreshToken)
|
remove(for: .refreshToken)
|
||||||
remove(for: .email)
|
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] {
|
private func baseQuery(for key: Key) -> [CFString: Any] {
|
||||||
var query: [CFString: Any] = [
|
var query: [CFString: Any] = [
|
||||||
kSecClass: kSecClassGenericPassword,
|
kSecClass: kSecClassGenericPassword,
|
||||||
|
|
|
||||||
|
|
@ -21,31 +21,6 @@ public protocol ManaAppConfig: Sendable {
|
||||||
/// Apple-Developer-Team-ID provisioniert sein und das Entitlement
|
/// Apple-Developer-Team-ID provisioniert sein und das Entitlement
|
||||||
/// `keychain-access-groups` mit demselben Wert tragen.
|
/// `keychain-access-groups` mit demselben Wert tragen.
|
||||||
var keychainAccessGroup: String? { get }
|
var keychainAccessGroup: String? { get }
|
||||||
|
|
||||||
/// App-Group für Daten-Sharing zwischen App ↔ Widget ↔ ShareExt.
|
|
||||||
/// Üblich `group.ev.mana.<app>`. `nil` für Apps ohne Extensions.
|
|
||||||
///
|
|
||||||
/// Single-Source für den App-Group-String, der heute in jeder App
|
|
||||||
/// 3-4× hardcoded steht (AppConfig + App-Entitlement + Widget-
|
|
||||||
/// Entitlement + ShareExt-Entitlement). Die Entitlements bleiben
|
|
||||||
/// hardcoded (das verlangt iOS), aber im Swift-Code ist der Wert
|
|
||||||
/// damit single-source.
|
|
||||||
var appGroup: String? { get }
|
|
||||||
|
|
||||||
/// OSLog-Subsystem für App-Logger, üblich `ev.mana.<app>`. Default
|
|
||||||
/// ist `keychainService` (der schon der Konvention folgt).
|
|
||||||
var logSubsystem: String { get }
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Default-Implementationen
|
|
||||||
|
|
||||||
public extension ManaAppConfig {
|
|
||||||
/// Default `nil` — Apps ohne Widget/ShareExt müssen nichts setzen.
|
|
||||||
var appGroup: String? { nil }
|
|
||||||
|
|
||||||
/// Default = `keychainService`. Beide folgen heute in allen Apps
|
|
||||||
/// derselben Konvention `ev.mana.<app>`.
|
|
||||||
var logSubsystem: String { keychainService }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Standard-Implementierung von ``ManaAppConfig``. Apps können diese
|
/// Standard-Implementierung von ``ManaAppConfig``. Apps können diese
|
||||||
|
|
@ -54,22 +29,14 @@ public struct DefaultManaAppConfig: ManaAppConfig {
|
||||||
public let authBaseURL: URL
|
public let authBaseURL: URL
|
||||||
public let keychainService: String
|
public let keychainService: String
|
||||||
public let keychainAccessGroup: String?
|
public let keychainAccessGroup: String?
|
||||||
public let appGroup: String?
|
|
||||||
public let logSubsystem: String
|
|
||||||
|
|
||||||
public init(
|
public init(
|
||||||
authBaseURL: URL,
|
authBaseURL: URL,
|
||||||
keychainService: String,
|
keychainService: String,
|
||||||
keychainAccessGroup: String? = nil,
|
keychainAccessGroup: String? = nil
|
||||||
appGroup: String? = nil,
|
|
||||||
logSubsystem: String? = nil
|
|
||||||
) {
|
) {
|
||||||
self.authBaseURL = authBaseURL
|
self.authBaseURL = authBaseURL
|
||||||
self.keychainService = keychainService
|
self.keychainService = keychainService
|
||||||
self.keychainAccessGroup = keychainAccessGroup
|
self.keychainAccessGroup = keychainAccessGroup
|
||||||
self.appGroup = appGroup
|
|
||||||
// Konvention: log-Subsystem = keychainService, falls nicht
|
|
||||||
// explizit anders gewünscht.
|
|
||||||
self.logSubsystem = logSubsystem ?? keychainService
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,67 +0,0 @@
|
||||||
import Foundation
|
|
||||||
import OSLog
|
|
||||||
|
|
||||||
/// Convenience-Factory für OSLog-Logger gegen ein `ManaAppConfig`.
|
|
||||||
///
|
|
||||||
/// Hintergrund: Jede mana-App hatte vor v1.7.0 ein eigenes `Log.swift`
|
|
||||||
/// mit 4-6 hand-getippten `Logger(subsystem: "ev.mana.<slug>", …)`-
|
|
||||||
/// Aufrufen — der Subsystem-String und die Standard-Kategorien
|
|
||||||
/// (`app`/`auth`/`api`) wiederholten sich 8× identisch. `ManaAppLog`
|
|
||||||
/// kapselt den Subsystem-Lookup gegen die App-Config; Standard-
|
|
||||||
/// Kategorien sind Convenience-Accessoren, app-spezifische gehen über
|
|
||||||
/// ``ManaAppLog/category(_:)``.
|
|
||||||
///
|
|
||||||
/// **Verwendung** (in der App):
|
|
||||||
///
|
|
||||||
/// ```swift
|
|
||||||
/// import ManaCore
|
|
||||||
///
|
|
||||||
/// enum Log {
|
|
||||||
/// private static let mana = ManaAppLog(AppConfig.manaAppConfig)
|
|
||||||
/// static let app = mana.app
|
|
||||||
/// static let auth = mana.auth
|
|
||||||
/// static let api = mana.api
|
|
||||||
/// // App-spezifische Kategorien:
|
|
||||||
/// static let study = mana.category("study")
|
|
||||||
/// static let sync = mana.category("sync")
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Die Standard-Kategorien sind bewusst eine kleine Schublade
|
|
||||||
/// (app/auth/api/db/web). Cards/Memoro/Manaspur sollen ihre `study`-/
|
|
||||||
/// `audio`-/`tracking`-Kategorien weiterhin app-spezifisch deklarieren.
|
|
||||||
public struct ManaAppLog: Sendable {
|
|
||||||
public let subsystem: String
|
|
||||||
|
|
||||||
/// Direkter Constructor (für Tests oder andere Subsysteme).
|
|
||||||
public init(subsystem: String) {
|
|
||||||
self.subsystem = subsystem
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Constructor aus einer ``ManaAppConfig``. Nutzt `logSubsystem`
|
|
||||||
/// (Default = `keychainService`, beides üblich `ev.mana.<app>`).
|
|
||||||
public init(_ config: ManaAppConfig) {
|
|
||||||
self.subsystem = config.logSubsystem
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Allgemeiner App-Logger.
|
|
||||||
public var app: Logger { Logger(subsystem: subsystem, category: "app") }
|
|
||||||
|
|
||||||
/// Auth-bezogene Events.
|
|
||||||
public var auth: Logger { Logger(subsystem: subsystem, category: "auth") }
|
|
||||||
|
|
||||||
/// API-/Netzwerk-Calls.
|
|
||||||
public var api: Logger { Logger(subsystem: subsystem, category: "api") }
|
|
||||||
|
|
||||||
/// Datenbank-/SwiftData-/Persistenz-Events.
|
|
||||||
public var db: Logger { Logger(subsystem: subsystem, category: "db") }
|
|
||||||
|
|
||||||
/// Web-/WKWebView-bezogene Events (für Hybrid-Apps).
|
|
||||||
public var web: Logger { Logger(subsystem: subsystem, category: "web") }
|
|
||||||
|
|
||||||
/// App-spezifische Kategorie. Beliebige Strings, weil Console.app
|
|
||||||
/// Kategorien als Free-Text filtert.
|
|
||||||
public func category(_ name: String) -> Logger {
|
|
||||||
Logger(subsystem: subsystem, category: name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,143 +0,0 @@
|
||||||
// ============================================================
|
|
||||||
// AUTOGENERIERT — NICHT MANUELL EDITIEREN.
|
|
||||||
//
|
|
||||||
// Quelle: mana/packages/themes/src/variants/*.css
|
|
||||||
// Generator: mana/packages/themes/scripts/gen-swift-themes.mjs
|
|
||||||
// Aufruf: pnpm --filter @mana/themes gen:swift
|
|
||||||
//
|
|
||||||
// Drift-Check: nach jedem Generator-Lauf `git diff --exit-code`
|
|
||||||
// in CI sicherstellen.
|
|
||||||
// ============================================================
|
|
||||||
|
|
||||||
import SwiftUI
|
|
||||||
|
|
||||||
public extension ManaThemeColors {
|
|
||||||
|
|
||||||
/// forest-Variant aus `mana/packages/themes/src/variants/forest.css`.
|
|
||||||
static let forest = ManaThemeColors(
|
|
||||||
background: Color.manaToken(light: (0, 0, 100), dark: (142, 30, 8)),
|
|
||||||
foreground: Color.manaToken(light: (142, 30, 12), dark: (142, 15, 95)),
|
|
||||||
surface: Color.manaToken(light: (142, 25, 98), dark: (142, 25, 12)),
|
|
||||||
surfaceHover: Color.manaToken(light: (142, 20, 95), dark: (142, 20, 16)),
|
|
||||||
muted: Color.manaToken(light: (142, 15, 93), dark: (142, 18, 18)),
|
|
||||||
mutedForeground: Color.manaToken(light: (142, 10, 42), dark: (142, 12, 65)),
|
|
||||||
border: Color.manaToken(light: (142, 15, 88), dark: (142, 18, 22)),
|
|
||||||
primary: Color.manaToken(light: (142, 76, 28), dark: (142, 71, 45)),
|
|
||||||
primaryForeground: Color.manaToken(light: (0, 0, 100), dark: (142, 30, 8)),
|
|
||||||
error: Color.manaToken(light: (0, 84, 60), dark: (0, 63, 55)),
|
|
||||||
success: Color.manaToken(light: (142, 71, 45), dark: (142, 71, 45)),
|
|
||||||
warning: Color.manaToken(light: (38, 92, 50), dark: (48, 96, 53))
|
|
||||||
)
|
|
||||||
|
|
||||||
/// lume-Variant aus `mana/packages/themes/src/variants/lume.css`.
|
|
||||||
static let lume = ManaThemeColors(
|
|
||||||
background: Color.manaToken(light: (0, 0, 100), dark: (0, 0, 6)),
|
|
||||||
foreground: Color.manaToken(light: (0, 0, 17), dark: (0, 0, 100)),
|
|
||||||
surface: Color.manaToken(light: (0, 0, 99), dark: (0, 0, 12)),
|
|
||||||
surfaceHover: Color.manaToken(light: (51, 40, 95), dark: (51, 30, 18)),
|
|
||||||
muted: Color.manaToken(light: (0, 0, 92), dark: (0, 0, 17)),
|
|
||||||
mutedForeground: Color.manaToken(light: (0, 0, 42), dark: (0, 0, 65)),
|
|
||||||
border: Color.manaToken(light: (0, 0, 86), dark: (0, 0, 26)),
|
|
||||||
primary: Color.manaToken(light: (51, 95, 58), dark: (51, 95, 58)),
|
|
||||||
primaryForeground: Color.manaToken(light: (0, 0, 13), dark: (0, 0, 6)),
|
|
||||||
error: Color.manaToken(light: (5, 78, 55), dark: (5, 78, 60)),
|
|
||||||
success: Color.manaToken(light: (142, 71, 45), dark: (142, 71, 50)),
|
|
||||||
warning: Color.manaToken(light: (38, 92, 50), dark: (48, 96, 55))
|
|
||||||
)
|
|
||||||
|
|
||||||
/// mana-Variant aus `mana/packages/themes/src/variants/mana.css`.
|
|
||||||
static let mana = ManaThemeColors(
|
|
||||||
background: Color.manaToken(light: (0, 0, 100), dark: (220, 20, 9)),
|
|
||||||
foreground: Color.manaToken(light: (220, 15, 12), dark: (25, 15, 95)),
|
|
||||||
surface: Color.manaToken(light: (0, 0, 99), dark: (220, 18, 13)),
|
|
||||||
surfaceHover: Color.manaToken(light: (25, 30, 95), dark: (25, 20, 18)),
|
|
||||||
muted: Color.manaToken(light: (25, 20, 93), dark: (220, 18, 18)),
|
|
||||||
mutedForeground: Color.manaToken(light: (220, 10, 42), dark: (220, 10, 65)),
|
|
||||||
border: Color.manaToken(light: (25, 15, 88), dark: (220, 15, 22)),
|
|
||||||
primary: Color.manaToken(light: (25, 100, 50), dark: (25, 100, 58)),
|
|
||||||
primaryForeground: Color.manaToken(light: (0, 0, 10), dark: (220, 20, 9)),
|
|
||||||
error: Color.manaToken(light: (0, 84, 60), dark: (0, 63, 55)),
|
|
||||||
success: Color.manaToken(light: (142, 71, 45), dark: (142, 71, 45)),
|
|
||||||
warning: Color.manaToken(light: (38, 92, 50), dark: (48, 96, 53))
|
|
||||||
)
|
|
||||||
|
|
||||||
/// monochrome-Variant aus `mana/packages/themes/src/variants/monochrome.css`.
|
|
||||||
static let monochrome = ManaThemeColors(
|
|
||||||
background: Color.manaToken(light: (0, 0, 100), dark: (0, 0, 5)),
|
|
||||||
foreground: Color.manaToken(light: (0, 0, 10), dark: (0, 0, 95)),
|
|
||||||
surface: Color.manaToken(light: (0, 0, 99), dark: (0, 0, 10)),
|
|
||||||
surfaceHover: Color.manaToken(light: (0, 0, 95), dark: (0, 0, 15)),
|
|
||||||
muted: Color.manaToken(light: (0, 0, 93), dark: (0, 0, 17)),
|
|
||||||
mutedForeground: Color.manaToken(light: (0, 0, 40), dark: (0, 0, 65)),
|
|
||||||
border: Color.manaToken(light: (0, 0, 85), dark: (0, 0, 22)),
|
|
||||||
primary: Color.manaToken(light: (0, 0, 25), dark: (0, 0, 80)),
|
|
||||||
primaryForeground: Color.manaToken(light: (0, 0, 100), dark: (0, 0, 5)),
|
|
||||||
error: Color.manaToken(light: (0, 70, 45), dark: (0, 65, 55)),
|
|
||||||
success: Color.manaToken(light: (142, 60, 35), dark: (142, 60, 50)),
|
|
||||||
warning: Color.manaToken(light: (38, 90, 45), dark: (48, 90, 55))
|
|
||||||
)
|
|
||||||
|
|
||||||
/// neutral-Variant aus `mana/packages/themes/src/variants/neutral.css`.
|
|
||||||
static let neutral = ManaThemeColors(
|
|
||||||
background: Color.manaToken(light: (0, 0, 99), dark: (0, 0, 8)),
|
|
||||||
foreground: Color.manaToken(light: (0, 0, 13), dark: (0, 0, 95)),
|
|
||||||
surface: Color.manaToken(light: (0, 0, 100), dark: (0, 0, 12)),
|
|
||||||
surfaceHover: Color.manaToken(light: (0, 0, 96), dark: (0, 0, 17)),
|
|
||||||
muted: Color.manaToken(light: (0, 0, 94), dark: (0, 0, 18)),
|
|
||||||
mutedForeground: Color.manaToken(light: (0, 0, 45), dark: (0, 0, 65)),
|
|
||||||
border: Color.manaToken(light: (0, 0, 88), dark: (0, 0, 22)),
|
|
||||||
primary: Color.manaToken(light: (215, 60, 40), dark: (215, 70, 60)),
|
|
||||||
primaryForeground: Color.manaToken(light: (0, 0, 100), dark: (0, 0, 8)),
|
|
||||||
error: Color.manaToken(light: (0, 65, 45), dark: (0, 63, 55)),
|
|
||||||
success: Color.manaToken(light: (135, 35, 35), dark: (135, 35, 55)),
|
|
||||||
warning: Color.manaToken(light: (38, 92, 45), dark: (48, 96, 53))
|
|
||||||
)
|
|
||||||
|
|
||||||
/// paper-Variant aus `mana/packages/themes/src/variants/paper.css`.
|
|
||||||
static let paper = ManaThemeColors(
|
|
||||||
background: Color.manaToken(light: (38, 28, 95), dark: (24, 14, 9)),
|
|
||||||
foreground: Color.manaToken(light: (20, 14, 16), dark: (38, 24, 88)),
|
|
||||||
surface: Color.manaToken(light: (0, 0, 100), dark: (24, 12, 13)),
|
|
||||||
surfaceHover: Color.manaToken(light: (38, 24, 92), dark: (24, 14, 17)),
|
|
||||||
muted: Color.manaToken(light: (38, 20, 90), dark: (24, 12, 18)),
|
|
||||||
mutedForeground: Color.manaToken(light: (20, 14, 50), dark: (38, 12, 60)),
|
|
||||||
border: Color.manaToken(light: (38, 18, 80), dark: (24, 10, 25)),
|
|
||||||
primary: Color.manaToken(light: (18, 50, 38), dark: (24, 60, 65)),
|
|
||||||
primaryForeground: Color.manaToken(light: (0, 0, 100), dark: (24, 14, 9)),
|
|
||||||
error: Color.manaToken(light: (0, 65, 45), dark: (0, 60, 55)),
|
|
||||||
success: Color.manaToken(light: (135, 35, 35), dark: (135, 35, 55)),
|
|
||||||
warning: Color.manaToken(light: (38, 80, 40), dark: (38, 70, 55))
|
|
||||||
)
|
|
||||||
|
|
||||||
/// skylight-Variant aus `mana/packages/themes/src/variants/skylight.css`.
|
|
||||||
static let skylight = ManaThemeColors(
|
|
||||||
background: Color.manaToken(light: (205, 50, 99), dark: (215, 40, 9)),
|
|
||||||
foreground: Color.manaToken(light: (215, 30, 15), dark: (205, 25, 95)),
|
|
||||||
surface: Color.manaToken(light: (0, 0, 100), dark: (215, 35, 13)),
|
|
||||||
surfaceHover: Color.manaToken(light: (205, 40, 95), dark: (215, 30, 18)),
|
|
||||||
muted: Color.manaToken(light: (205, 30, 93), dark: (215, 30, 19)),
|
|
||||||
mutedForeground: Color.manaToken(light: (215, 15, 45), dark: (205, 18, 65)),
|
|
||||||
border: Color.manaToken(light: (205, 25, 88), dark: (215, 25, 24)),
|
|
||||||
primary: Color.manaToken(light: (205, 90, 40), dark: (205, 90, 60)),
|
|
||||||
primaryForeground: Color.manaToken(light: (0, 0, 100), dark: (215, 40, 9)),
|
|
||||||
error: Color.manaToken(light: (0, 80, 50), dark: (0, 70, 60)),
|
|
||||||
success: Color.manaToken(light: (142, 65, 40), dark: (142, 65, 50)),
|
|
||||||
warning: Color.manaToken(light: (38, 92, 50), dark: (48, 95, 55))
|
|
||||||
)
|
|
||||||
|
|
||||||
/// twilight-Variant aus `mana/packages/themes/src/variants/twilight.css`.
|
|
||||||
static let twilight = ManaThemeColors(
|
|
||||||
background: Color.manaToken(light: (250, 30, 97), dark: (260, 35, 8)),
|
|
||||||
foreground: Color.manaToken(light: (260, 25, 15), dark: (250, 20, 92)),
|
|
||||||
surface: Color.manaToken(light: (250, 40, 99), dark: (260, 30, 12)),
|
|
||||||
surfaceHover: Color.manaToken(light: (260, 30, 94), dark: (260, 28, 17)),
|
|
||||||
muted: Color.manaToken(light: (260, 25, 92), dark: (260, 25, 19)),
|
|
||||||
mutedForeground: Color.manaToken(light: (260, 15, 45), dark: (250, 15, 65)),
|
|
||||||
border: Color.manaToken(light: (260, 20, 87), dark: (260, 20, 25)),
|
|
||||||
primary: Color.manaToken(light: (260, 70, 55), dark: (260, 75, 70)),
|
|
||||||
primaryForeground: Color.manaToken(light: (0, 0, 100), dark: (260, 35, 10)),
|
|
||||||
error: Color.manaToken(light: (0, 75, 55), dark: (0, 65, 60)),
|
|
||||||
success: Color.manaToken(light: (142, 60, 45), dark: (142, 60, 55)),
|
|
||||||
warning: Color.manaToken(light: (38, 90, 55), dark: (48, 90, 55))
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,54 +0,0 @@
|
||||||
import SwiftUI
|
|
||||||
|
|
||||||
/// Eine der acht Verein-Theme-Variants aus `mana/packages/themes`.
|
|
||||||
///
|
|
||||||
/// Die Werte-Schicht (``ManaThemeColors``) wird per `colors`-Accessor
|
|
||||||
/// geliefert. Convenience-Properties (`background`, `foreground`, …)
|
|
||||||
/// erlauben Apps, ohne `.colors`-Indirektion zu schreiben:
|
|
||||||
///
|
|
||||||
/// ```swift
|
|
||||||
/// ManaTheme.forest.foreground // Convenience
|
|
||||||
/// ManaTheme.forest.colors.foreground // explizit
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Für User-Theme-Switching nutze ``SwiftUICore/View/manaTheme(_:)``
|
|
||||||
/// und lese im View per `@Environment(\.manaTheme)`.
|
|
||||||
public enum ManaTheme: String, CaseIterable, Sendable {
|
|
||||||
case mana
|
|
||||||
case forest
|
|
||||||
case paper
|
|
||||||
case neutral
|
|
||||||
case lume
|
|
||||||
case twilight
|
|
||||||
case skylight
|
|
||||||
case monochrome
|
|
||||||
|
|
||||||
/// Konkrete Token-Werte für diese Variant.
|
|
||||||
public var colors: ManaThemeColors {
|
|
||||||
switch self {
|
|
||||||
case .mana: return .mana
|
|
||||||
case .forest: return .forest
|
|
||||||
case .paper: return .paper
|
|
||||||
case .neutral: return .neutral
|
|
||||||
case .lume: return .lume
|
|
||||||
case .twilight: return .twilight
|
|
||||||
case .skylight: return .skylight
|
|
||||||
case .monochrome: return .monochrome
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: Convenience-Accessors
|
|
||||||
|
|
||||||
public var background: Color { colors.background }
|
|
||||||
public var foreground: Color { colors.foreground }
|
|
||||||
public var surface: Color { colors.surface }
|
|
||||||
public var surfaceHover: Color { colors.surfaceHover }
|
|
||||||
public var muted: Color { colors.muted }
|
|
||||||
public var mutedForeground: Color { colors.mutedForeground }
|
|
||||||
public var border: Color { colors.border }
|
|
||||||
public var primary: Color { colors.primary }
|
|
||||||
public var primaryForeground: Color { colors.primaryForeground }
|
|
||||||
public var error: Color { colors.error }
|
|
||||||
public var success: Color { colors.success }
|
|
||||||
public var warning: Color { colors.warning }
|
|
||||||
}
|
|
||||||
|
|
@ -1,76 +0,0 @@
|
||||||
import SwiftUI
|
|
||||||
|
|
||||||
/// Die 12 Vereins-Tokens als konkrete Color-Werte für eine bestimmte
|
|
||||||
/// Theme-Variant. Wird heute per-Variant von ``ManaTheme/colors``
|
|
||||||
/// geliefert; die statischen Variants (``ManaThemeColors/mana``,
|
|
||||||
/// ``ManaThemeColors/forest`` etc.) leben im generierten File
|
|
||||||
/// `GeneratedThemes.swift`.
|
|
||||||
///
|
|
||||||
/// **Verwendung:**
|
|
||||||
///
|
|
||||||
/// ```swift
|
|
||||||
/// // Direkt:
|
|
||||||
/// Text("Hi").foregroundColor(ManaTheme.forest.foreground)
|
|
||||||
///
|
|
||||||
/// // Via Environment (für Apps, die User-Theme-Switching anbieten):
|
|
||||||
/// @Environment(\.manaTheme) var theme
|
|
||||||
/// Text("Hi").foregroundColor(theme.foreground)
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Beide Werte (`light:`, `dark:`) sind CSS-HSL-Tripel `(hue 0–360,
|
|
||||||
/// saturation 0–100, lightness 0–100)`. Quelle:
|
|
||||||
/// `mana/packages/themes/src/variants/*.css`.
|
|
||||||
public struct ManaThemeColors: Sendable {
|
|
||||||
/// Token 1 — `--color-background`. Page-Hintergrund.
|
|
||||||
public let background: Color
|
|
||||||
/// Token 2 — `--color-foreground`. Standard-Text.
|
|
||||||
public let foreground: Color
|
|
||||||
/// Token 3 — `--color-surface`. Card, Panel, Modal, Popover.
|
|
||||||
public let surface: Color
|
|
||||||
/// Token 4 — `--color-surface-hover`. Hover-State auf Surface.
|
|
||||||
public let surfaceHover: Color
|
|
||||||
/// Token 5 — `--color-muted`. Disabled-Felder, Skeleton.
|
|
||||||
public let muted: Color
|
|
||||||
/// Token 6 — `--color-muted-foreground`. Sekundär-Text, Placeholder.
|
|
||||||
public let mutedForeground: Color
|
|
||||||
/// Token 7 — `--color-border`. Rahmen, Trennlinien.
|
|
||||||
public let border: Color
|
|
||||||
/// Token 8 — `--color-primary`. App-Akzent.
|
|
||||||
public let primary: Color
|
|
||||||
/// Token 9 — `--color-primary-foreground`. Text auf Primary-Flächen.
|
|
||||||
public let primaryForeground: Color
|
|
||||||
/// Token 10 — `--color-error`. Fehler, Lösch-Aktion.
|
|
||||||
public let error: Color
|
|
||||||
/// Token 11 — `--color-success`. Erfolg, Bestätigung.
|
|
||||||
public let success: Color
|
|
||||||
/// Token 12 — `--color-warning`. Warnung, Aufmerksamkeit.
|
|
||||||
public let warning: Color
|
|
||||||
|
|
||||||
public init(
|
|
||||||
background: Color,
|
|
||||||
foreground: Color,
|
|
||||||
surface: Color,
|
|
||||||
surfaceHover: Color,
|
|
||||||
muted: Color,
|
|
||||||
mutedForeground: Color,
|
|
||||||
border: Color,
|
|
||||||
primary: Color,
|
|
||||||
primaryForeground: Color,
|
|
||||||
error: Color,
|
|
||||||
success: Color,
|
|
||||||
warning: Color
|
|
||||||
) {
|
|
||||||
self.background = background
|
|
||||||
self.foreground = foreground
|
|
||||||
self.surface = surface
|
|
||||||
self.surfaceHover = surfaceHover
|
|
||||||
self.muted = muted
|
|
||||||
self.mutedForeground = mutedForeground
|
|
||||||
self.border = border
|
|
||||||
self.primary = primary
|
|
||||||
self.primaryForeground = primaryForeground
|
|
||||||
self.error = error
|
|
||||||
self.success = success
|
|
||||||
self.warning = warning
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,37 +0,0 @@
|
||||||
import SwiftUI
|
|
||||||
|
|
||||||
private struct ManaThemeEnvironmentKey: EnvironmentKey {
|
|
||||||
static let defaultValue: ManaTheme = .mana
|
|
||||||
}
|
|
||||||
|
|
||||||
public extension EnvironmentValues {
|
|
||||||
/// Aktuell aktive Theme-Variant. Default: ``ManaTheme/mana``.
|
|
||||||
var manaTheme: ManaTheme {
|
|
||||||
get { self[ManaThemeEnvironmentKey.self] }
|
|
||||||
set { self[ManaThemeEnvironmentKey.self] = newValue }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public extension View {
|
|
||||||
/// Setzt die aktive Theme-Variant für diesen View-Subtree.
|
|
||||||
///
|
|
||||||
/// Apps mit fixer Identität setzen das an der App-Root:
|
|
||||||
///
|
|
||||||
/// ```swift
|
|
||||||
/// @main
|
|
||||||
/// struct CardsApp: App {
|
|
||||||
/// var body: some Scene {
|
|
||||||
/// WindowGroup {
|
|
||||||
/// ContentView()
|
|
||||||
/// .manaTheme(.forest)
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Apps mit User-Theme-Switching binden den Wert an `@AppStorage`
|
|
||||||
/// oder eine Settings-Source und re-rendern bei Wechsel automatisch.
|
|
||||||
func manaTheme(_ theme: ManaTheme) -> some View {
|
|
||||||
environment(\.manaTheme, theme)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -2,10 +2,27 @@ import Foundation
|
||||||
import Testing
|
import Testing
|
||||||
@testable import ManaCore
|
@testable import ManaCore
|
||||||
|
|
||||||
@Suite("AuthClient+Account")
|
@Suite("AuthClient+Account", .serialized)
|
||||||
@MainActor
|
@MainActor
|
||||||
struct AuthClientAccountTests {
|
struct AuthClientAccountTests {
|
||||||
|
// MARK: - Fixtures
|
||||||
|
|
||||||
|
private static func makeClient() -> (AuthClient, URLSession) {
|
||||||
|
let configuration = URLSessionConfiguration.ephemeral
|
||||||
|
configuration.protocolClasses = [MockURLProtocol.self]
|
||||||
|
let session = URLSession(configuration: configuration)
|
||||||
|
|
||||||
|
let config = DefaultManaAppConfig(
|
||||||
|
authBaseURL: URL(string: "https://auth.test")!,
|
||||||
|
keychainService: "ev.mana.test.\(UUID().uuidString)",
|
||||||
|
keychainAccessGroup: nil
|
||||||
|
)
|
||||||
|
return (AuthClient(config: config, session: session), session)
|
||||||
|
}
|
||||||
|
|
||||||
private func recordedBody(_ request: URLRequest) -> [String: Any] {
|
private func recordedBody(_ request: URLRequest) -> [String: Any] {
|
||||||
|
// URLSession verschiebt den Body in den BodyStream wenn er nicht
|
||||||
|
// klein-genug ist — ephemeral-Session lässt ihn als httpBody.
|
||||||
guard let body = request.httpBody ?? request.bodyStreamData(),
|
guard let body = request.httpBody ?? request.bodyStreamData(),
|
||||||
let json = try? JSONSerialization.jsonObject(with: body) as? [String: Any]
|
let json = try? JSONSerialization.jsonObject(with: body) as? [String: Any]
|
||||||
else { return [:] }
|
else { return [:] }
|
||||||
|
|
@ -16,62 +33,66 @@ struct AuthClientAccountTests {
|
||||||
|
|
||||||
@Test("register schickt POST /api/v1/auth/register mit JSON-Body")
|
@Test("register schickt POST /api/v1/auth/register mit JSON-Body")
|
||||||
func registerSendsCorrectRequest() async throws {
|
func registerSendsCorrectRequest() async throws {
|
||||||
let mocked = makeMockedAuth()
|
let (client, _) = Self.makeClient()
|
||||||
mocked.setHandler { request in
|
MockURLProtocol.handler = { request in
|
||||||
#expect(request.httpMethod == "POST")
|
#expect(request.httpMethod == "POST")
|
||||||
#expect(request.url?.path == "/api/v1/auth/register")
|
#expect(request.url?.path == "/api/v1/auth/register")
|
||||||
#expect(request.value(forHTTPHeaderField: "Content-Type") == "application/json")
|
#expect(request.value(forHTTPHeaderField: "Content-Type") == "application/json")
|
||||||
return (200, Data(#"{"user":{"id":"u1","email":"new@x.de"}}"#.utf8))
|
return (200, Data(#"{"user":{"id":"u1","email":"new@x.de"}}"#.utf8))
|
||||||
}
|
}
|
||||||
|
|
||||||
try await mocked.auth.register(
|
try await client.register(
|
||||||
email: "new@x.de",
|
email: "new@x.de",
|
||||||
password: "Aa-123456789",
|
password: "Aa-123456789",
|
||||||
name: "Neu",
|
name: "Neu",
|
||||||
sourceAppUrl: URL(string: "https://cardecky.mana.how/auth/verify")
|
sourceAppUrl: URL(string: "https://cardecky.mana.how/auth/verify")
|
||||||
)
|
)
|
||||||
if case .signedIn = mocked.auth.status {
|
// Mit requireEmailVerification:true gibt es noch keine Session.
|
||||||
|
if case .signedIn = client.status {
|
||||||
Issue.record("Expected not-signed-in after register without tokens")
|
Issue.record("Expected not-signed-in after register without tokens")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test("register mit Token-Antwort führt direkt zu signedIn")
|
@Test("register mit Token-Antwort führt direkt zu signedIn")
|
||||||
func registerWithTokensSignsIn() async throws {
|
func registerWithTokensSignsIn() async throws {
|
||||||
let mocked = makeMockedAuth()
|
let (client, _) = Self.makeClient()
|
||||||
let access = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
|
// gültiger HS256-Header.payload (exp 2_000_000_000).sig — JWT.expiry()
|
||||||
|
// läuft danach nicht in den Refresh-Pfad.
|
||||||
|
let access =
|
||||||
|
"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
|
||||||
let refresh = "refresh-token-value"
|
let refresh = "refresh-token-value"
|
||||||
mocked.setHandler { _ in
|
MockURLProtocol.handler = { _ in
|
||||||
(200, Data(#"""
|
(200, Data(#"""
|
||||||
{"user":{"id":"u1","email":"new@x.de"},"accessToken":"\#(access)","refreshToken":"\#(refresh)"}
|
{"user":{"id":"u1","email":"new@x.de"},"accessToken":"\#(access)","refreshToken":"\#(refresh)"}
|
||||||
"""#.utf8))
|
"""#.utf8))
|
||||||
}
|
}
|
||||||
|
|
||||||
try await mocked.auth.register(email: "new@x.de", password: "Aa-123456789")
|
try await client.register(email: "new@x.de", password: "Aa-123456789")
|
||||||
#expect(mocked.auth.status == .signedIn(email: "new@x.de"))
|
#expect(client.status == .signedIn(email: "new@x.de"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test("register mit existierender Email wirft emailAlreadyRegistered")
|
@Test("register mit existierender Email wirft emailAlreadyRegistered")
|
||||||
func registerEmailAlreadyRegistered() async {
|
func registerEmailAlreadyRegistered() async {
|
||||||
let mocked = makeMockedAuth()
|
let (client, _) = Self.makeClient()
|
||||||
mocked.setHandler { _ in
|
MockURLProtocol.handler = { _ in
|
||||||
(409, Data(#"{"error":"EMAIL_ALREADY_REGISTERED","status":409}"#.utf8))
|
(409, Data(#"{"error":"EMAIL_ALREADY_REGISTERED","status":409}"#.utf8))
|
||||||
}
|
}
|
||||||
|
|
||||||
await #expect(throws: AuthError.emailAlreadyRegistered) {
|
await #expect(throws: AuthError.emailAlreadyRegistered) {
|
||||||
try await mocked.auth.register(email: "old@x.de", password: "Aa-123456789")
|
try await client.register(email: "old@x.de", password: "Aa-123456789")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test("register mit leerer Email wirft validation ohne Server-Call")
|
@Test("register mit leerer Email wirft validation ohne Server-Call")
|
||||||
func registerValidatesEmptyEmail() async {
|
func registerValidatesEmptyEmail() async {
|
||||||
let mocked = makeMockedAuth()
|
let (client, _) = Self.makeClient()
|
||||||
mocked.setHandler { _ in
|
MockURLProtocol.handler = { _ in
|
||||||
Issue.record("Server darf nicht aufgerufen werden")
|
Issue.record("Server darf nicht aufgerufen werden")
|
||||||
return (500, Data())
|
return (500, Data())
|
||||||
}
|
}
|
||||||
|
|
||||||
await #expect(throws: (any Error).self) {
|
await #expect(throws: (any Error).self) {
|
||||||
try await mocked.auth.register(email: " ", password: "Aa-123456789")
|
try await client.register(email: " ", password: "Aa-123456789")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -79,14 +100,14 @@ struct AuthClientAccountTests {
|
||||||
|
|
||||||
@Test("forgotPassword schickt email + redirectTo")
|
@Test("forgotPassword schickt email + redirectTo")
|
||||||
func forgotPasswordPayload() async throws {
|
func forgotPasswordPayload() async throws {
|
||||||
let mocked = makeMockedAuth()
|
let (client, _) = Self.makeClient()
|
||||||
let capturedURL = MockURLProtocol.Capture()
|
let capturedURL = MockURLProtocol.Capture()
|
||||||
mocked.setHandler { request in
|
MockURLProtocol.handler = { request in
|
||||||
capturedURL.store(request)
|
capturedURL.store(request)
|
||||||
return (200, Data(#"{"success":true}"#.utf8))
|
return (200, Data(#"{"success":true}"#.utf8))
|
||||||
}
|
}
|
||||||
|
|
||||||
try await mocked.auth.forgotPassword(
|
try await client.forgotPassword(
|
||||||
email: "user@x.de",
|
email: "user@x.de",
|
||||||
resetUniversalLink: URL(string: "https://cardecky.mana.how/auth/reset")!
|
resetUniversalLink: URL(string: "https://cardecky.mana.how/auth/reset")!
|
||||||
)
|
)
|
||||||
|
|
@ -101,14 +122,14 @@ struct AuthClientAccountTests {
|
||||||
|
|
||||||
@Test("resetPassword schickt token + newPassword")
|
@Test("resetPassword schickt token + newPassword")
|
||||||
func resetPasswordPayload() async throws {
|
func resetPasswordPayload() async throws {
|
||||||
let mocked = makeMockedAuth()
|
let (client, _) = Self.makeClient()
|
||||||
let captured = MockURLProtocol.Capture()
|
let captured = MockURLProtocol.Capture()
|
||||||
mocked.setHandler { request in
|
MockURLProtocol.handler = { request in
|
||||||
captured.store(request)
|
captured.store(request)
|
||||||
return (200, Data(#"{"success":true}"#.utf8))
|
return (200, Data(#"{"success":true}"#.utf8))
|
||||||
}
|
}
|
||||||
|
|
||||||
try await mocked.auth.resetPassword(token: "tok123", newPassword: "Neu-987654321")
|
try await client.resetPassword(token: "tok123", newPassword: "Neu-987654321")
|
||||||
let request = try #require(captured.request)
|
let request = try #require(captured.request)
|
||||||
let json = recordedBody(request)
|
let json = recordedBody(request)
|
||||||
#expect(json["token"] as? String == "tok123")
|
#expect(json["token"] as? String == "tok123")
|
||||||
|
|
@ -118,13 +139,13 @@ struct AuthClientAccountTests {
|
||||||
|
|
||||||
@Test("resetPassword mit abgelaufenem Token wirft tokenExpired")
|
@Test("resetPassword mit abgelaufenem Token wirft tokenExpired")
|
||||||
func resetPasswordTokenExpired() async {
|
func resetPasswordTokenExpired() async {
|
||||||
let mocked = makeMockedAuth()
|
let (client, _) = Self.makeClient()
|
||||||
mocked.setHandler { _ in
|
MockURLProtocol.handler = { _ in
|
||||||
(400, Data(#"{"error":"TOKEN_EXPIRED","status":400}"#.utf8))
|
(400, Data(#"{"error":"TOKEN_EXPIRED","status":400}"#.utf8))
|
||||||
}
|
}
|
||||||
|
|
||||||
await #expect(throws: AuthError.tokenExpired) {
|
await #expect(throws: AuthError.tokenExpired) {
|
||||||
try await mocked.auth.resetPassword(token: "old", newPassword: "Neu-987654321")
|
try await client.resetPassword(token: "old", newPassword: "Neu-987654321")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -132,14 +153,14 @@ struct AuthClientAccountTests {
|
||||||
|
|
||||||
@Test("resendVerification schickt email + sourceAppUrl")
|
@Test("resendVerification schickt email + sourceAppUrl")
|
||||||
func resendVerificationPayload() async throws {
|
func resendVerificationPayload() async throws {
|
||||||
let mocked = makeMockedAuth()
|
let (client, _) = Self.makeClient()
|
||||||
let captured = MockURLProtocol.Capture()
|
let captured = MockURLProtocol.Capture()
|
||||||
mocked.setHandler { request in
|
MockURLProtocol.handler = { request in
|
||||||
captured.store(request)
|
captured.store(request)
|
||||||
return (200, Data(#"{"success":true}"#.utf8))
|
return (200, Data(#"{"success":true}"#.utf8))
|
||||||
}
|
}
|
||||||
|
|
||||||
try await mocked.auth.resendVerification(
|
try await client.resendVerification(
|
||||||
email: "user@x.de",
|
email: "user@x.de",
|
||||||
sourceAppUrl: URL(string: "https://cardecky.mana.how/auth/verify")
|
sourceAppUrl: URL(string: "https://cardecky.mana.how/auth/verify")
|
||||||
)
|
)
|
||||||
|
|
@ -151,8 +172,8 @@ struct AuthClientAccountTests {
|
||||||
|
|
||||||
@Test("resendVerification mit Rate-Limit liefert retryAfter")
|
@Test("resendVerification mit Rate-Limit liefert retryAfter")
|
||||||
func resendVerificationRateLimited() async {
|
func resendVerificationRateLimited() async {
|
||||||
let mocked = makeMockedAuth()
|
let (client, _) = Self.makeClient()
|
||||||
mocked.setHandler { _ in
|
MockURLProtocol.handler = { _ in
|
||||||
(
|
(
|
||||||
429,
|
429,
|
||||||
Data(#"{"error":"RATE_LIMITED","retryAfterSec":42,"status":429}"#.utf8),
|
Data(#"{"error":"RATE_LIMITED","retryAfterSec":42,"status":429}"#.utf8),
|
||||||
|
|
@ -161,7 +182,7 @@ struct AuthClientAccountTests {
|
||||||
}
|
}
|
||||||
|
|
||||||
do {
|
do {
|
||||||
try await mocked.auth.resendVerification(email: "user@x.de")
|
try await client.resendVerification(email: "user@x.de")
|
||||||
Issue.record("Expected throw")
|
Issue.record("Expected throw")
|
||||||
} catch let AuthError.rateLimited(retryAfter) {
|
} catch let AuthError.rateLimited(retryAfter) {
|
||||||
#expect(retryAfter == 42)
|
#expect(retryAfter == 42)
|
||||||
|
|
@ -174,43 +195,126 @@ struct AuthClientAccountTests {
|
||||||
|
|
||||||
@Test("changeEmail ohne Login wirft notSignedIn")
|
@Test("changeEmail ohne Login wirft notSignedIn")
|
||||||
func changeEmailRequiresSession() async {
|
func changeEmailRequiresSession() async {
|
||||||
let mocked = makeMockedAuth()
|
let (client, _) = Self.makeClient()
|
||||||
await #expect(throws: AuthError.notSignedIn) {
|
await #expect(throws: AuthError.notSignedIn) {
|
||||||
try await mocked.auth.changeEmail(newEmail: "neu@x.de")
|
try await client.changeEmail(newEmail: "neu@x.de")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test("changePassword schickt Session-Token als Bearer (nicht JWT)")
|
@Test("changePassword schickt Bearer-Header wenn eingeloggt")
|
||||||
func changePasswordSendsBearer() async throws {
|
func changePasswordSendsBearer() async throws {
|
||||||
let mocked = makeMockedAuth()
|
let (client, _) = Self.makeClient()
|
||||||
|
// Mock-Token im Keychain ablegen via persistSession-Helper.
|
||||||
let access = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
|
let access = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
|
||||||
let session = "session-token-value"
|
try client.persistSession(email: "u@x.de", accessToken: access, refreshToken: "r")
|
||||||
try mocked.auth.persistSession(email: "u@x.de", accessToken: access, refreshToken: session)
|
|
||||||
|
|
||||||
let captured = MockURLProtocol.Capture()
|
let captured = MockURLProtocol.Capture()
|
||||||
mocked.setHandler { request in
|
MockURLProtocol.handler = { request in
|
||||||
captured.store(request)
|
captured.store(request)
|
||||||
return (200, Data(#"{"success":true}"#.utf8))
|
return (200, Data(#"{"success":true}"#.utf8))
|
||||||
}
|
}
|
||||||
|
|
||||||
try await mocked.auth.changePassword(currentPassword: "alt", newPassword: "neu")
|
try await client.changePassword(currentPassword: "alt", newPassword: "neu")
|
||||||
let request = try #require(captured.request)
|
let request = try #require(captured.request)
|
||||||
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer \(session)")
|
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer \(access)")
|
||||||
#expect(request.url?.path == "/api/v1/auth/change-password")
|
#expect(request.url?.path == "/api/v1/auth/change-password")
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test("deleteAccount wiped Session bei Erfolg")
|
@Test("deleteAccount wiped Session bei Erfolg")
|
||||||
func deleteAccountClearsSession() async throws {
|
func deleteAccountClearsSession() async throws {
|
||||||
let mocked = makeMockedAuth()
|
let (client, _) = Self.makeClient()
|
||||||
let access = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
|
let access = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
|
||||||
try mocked.auth.persistSession(email: "u@x.de", accessToken: access, refreshToken: "r")
|
try client.persistSession(email: "u@x.de", accessToken: access, refreshToken: "r")
|
||||||
#expect(mocked.auth.status == .signedIn(email: "u@x.de"))
|
#expect(client.status == .signedIn(email: "u@x.de"))
|
||||||
|
|
||||||
mocked.setHandler { request in
|
MockURLProtocol.handler = { request in
|
||||||
#expect(request.httpMethod == "DELETE")
|
#expect(request.httpMethod == "DELETE")
|
||||||
return (200, Data(#"{"success":true}"#.utf8))
|
return (200, Data(#"{"success":true}"#.utf8))
|
||||||
}
|
}
|
||||||
try await mocked.auth.deleteAccount(password: "pw")
|
try await client.deleteAccount(password: "pw")
|
||||||
#expect(mocked.auth.status == .signedOut)
|
#expect(client.status == .signedOut)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - URLProtocol Mock
|
||||||
|
|
||||||
|
final class MockURLProtocol: URLProtocol, @unchecked Sendable {
|
||||||
|
/// Antwort-Tuple: (status, body) oder (status, body, headers).
|
||||||
|
typealias Response = (status: Int, body: Data, headers: [String: String])
|
||||||
|
typealias Handler = @Sendable (URLRequest) -> Any // (Int, Data) | (Int, Data, [String:String])
|
||||||
|
|
||||||
|
nonisolated(unsafe) static var handler: Handler?
|
||||||
|
|
||||||
|
/// Thread-safer Capture-Container — Tests können den Request darin
|
||||||
|
/// festhalten und nach dem await aus dem Test-Body lesen.
|
||||||
|
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() {
|
||||||
|
guard let handler = MockURLProtocol.handler 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,230 +0,0 @@
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,77 +0,0 @@
|
||||||
import Foundation
|
|
||||||
import Testing
|
|
||||||
@testable import ManaCore
|
|
||||||
|
|
||||||
@Suite("AuthClient getProfile")
|
|
||||||
@MainActor
|
|
||||||
struct AuthClientProfileTests {
|
|
||||||
private func signedInAuth() async -> MockedAuth {
|
|
||||||
let mocked = makeMockedAuth()
|
|
||||||
let access = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
|
|
||||||
mocked.setHandler { _ in
|
|
||||||
(200, Data(#"{"accessToken":"\#(access)","refreshToken":"session-tok"}"#.utf8))
|
|
||||||
}
|
|
||||||
await mocked.auth.signIn(email: "u@x.de", password: "pw")
|
|
||||||
return mocked
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("getProfile mit twoFactor on")
|
|
||||||
func profileTwoFactorOn() async throws {
|
|
||||||
let mocked = await signedInAuth()
|
|
||||||
let captured = MockURLProtocol.Capture()
|
|
||||||
mocked.setHandler { request in
|
|
||||||
captured.store(request)
|
|
||||||
return (200, Data(#"""
|
|
||||||
{"user":{"id":"u1","email":"u@x.de","name":"Test","emailVerified":true,"twoFactorEnabled":true},
|
|
||||||
"session":{"id":"s1"}}
|
|
||||||
"""#.utf8))
|
|
||||||
}
|
|
||||||
|
|
||||||
let profile = try await mocked.auth.getProfile()
|
|
||||||
#expect(profile.id == "u1")
|
|
||||||
#expect(profile.email == "u@x.de")
|
|
||||||
#expect(profile.name == "Test")
|
|
||||||
#expect(profile.emailVerified == true)
|
|
||||||
#expect(profile.twoFactorEnabled == true)
|
|
||||||
|
|
||||||
let request = try #require(captured.request)
|
|
||||||
#expect(request.httpMethod == "GET")
|
|
||||||
#expect(request.url?.path == "/api/v1/auth/profile")
|
|
||||||
// Bearer-Header trägt den Session-Token
|
|
||||||
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer session-tok")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("getProfile mit twoFactor off (Feld fehlt)")
|
|
||||||
func profileTwoFactorOff() async throws {
|
|
||||||
let mocked = await signedInAuth()
|
|
||||||
mocked.setHandler { _ in
|
|
||||||
(200, Data(#"""
|
|
||||||
{"user":{"id":"u1","email":"u@x.de","name":null,"emailVerified":true}}
|
|
||||||
"""#.utf8))
|
|
||||||
}
|
|
||||||
|
|
||||||
let profile = try await mocked.auth.getProfile()
|
|
||||||
#expect(profile.twoFactorEnabled == false)
|
|
||||||
#expect(profile.name == nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("getProfile ohne Session → notSignedIn")
|
|
||||||
func profileNoSession() async {
|
|
||||||
let mocked = makeMockedAuth()
|
|
||||||
await #expect(throws: AuthError.notSignedIn) {
|
|
||||||
try await mocked.auth.getProfile()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("getProfile mit abgelaufenem Token → unauthorized")
|
|
||||||
func profileUnauthorized() async {
|
|
||||||
let mocked = await signedInAuth()
|
|
||||||
mocked.setHandler { _ in
|
|
||||||
(401, Data(#"{"error":"UNAUTHORIZED","status":401}"#.utf8))
|
|
||||||
}
|
|
||||||
|
|
||||||
await #expect(throws: AuthError.unauthorized) {
|
|
||||||
try await mocked.auth.getProfile()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,119 +0,0 @@
|
||||||
import Foundation
|
|
||||||
import Testing
|
|
||||||
@testable import ManaCore
|
|
||||||
|
|
||||||
@Suite("AuthClient 2FA-Enrollment")
|
|
||||||
@MainActor
|
|
||||||
struct AuthClientTwoFactorEnrollmentTests {
|
|
||||||
/// Bringt den AuthClient in den `.signedIn`-Status mit einem
|
|
||||||
/// Session-Token für authenticated Calls.
|
|
||||||
private func signedInAuth() async -> MockedAuth {
|
|
||||||
let mocked = makeMockedAuth()
|
|
||||||
let access = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
|
|
||||||
mocked.setHandler { _ in
|
|
||||||
(200, Data(#"{"accessToken":"\#(access)","refreshToken":"session-tok"}"#.utf8))
|
|
||||||
}
|
|
||||||
await mocked.auth.signIn(email: "u@x.de", password: "pw")
|
|
||||||
return mocked
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("enrollTotp liefert URI + Backup-Codes")
|
|
||||||
func enrollSuccess() async throws {
|
|
||||||
let mocked = await signedInAuth()
|
|
||||||
let captured = MockURLProtocol.Capture()
|
|
||||||
mocked.setHandler { request in
|
|
||||||
captured.store(request)
|
|
||||||
return (200, Data(#"""
|
|
||||||
{"totpURI":"otpauth://totp/Mana:u@x.de?secret=ABC&issuer=Mana","backupCodes":["a-b-c","d-e-f","g-h-i"]}
|
|
||||||
"""#.utf8))
|
|
||||||
}
|
|
||||||
|
|
||||||
let enrollment = try await mocked.auth.enrollTotp(password: "pw")
|
|
||||||
#expect(enrollment.totpURI.hasPrefix("otpauth://totp/"))
|
|
||||||
#expect(enrollment.backupCodes == ["a-b-c", "d-e-f", "g-h-i"])
|
|
||||||
|
|
||||||
let request = try #require(captured.request)
|
|
||||||
#expect(request.url?.path == "/api/v1/auth/two-factor/enable")
|
|
||||||
// Bearer-Header trägt den Session-Token (nicht JWT)
|
|
||||||
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer session-tok")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("enrollTotp mit leerem Passwort → validation, kein Server-Call")
|
|
||||||
func enrollEmptyPassword() async {
|
|
||||||
let mocked = await signedInAuth()
|
|
||||||
mocked.setHandler { _ in
|
|
||||||
Issue.record("Server darf nicht aufgerufen werden")
|
|
||||||
return (500, Data())
|
|
||||||
}
|
|
||||||
|
|
||||||
await #expect(throws: AuthError.validation(message: "Passwort ist erforderlich")) {
|
|
||||||
try await mocked.auth.enrollTotp(password: "")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("enrollTotp ohne Session → notSignedIn")
|
|
||||||
func enrollNoSession() async {
|
|
||||||
let mocked = makeMockedAuth()
|
|
||||||
await #expect(throws: AuthError.notSignedIn) {
|
|
||||||
try await mocked.auth.enrollTotp(password: "pw")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("disableTotp success")
|
|
||||||
func disableSuccess() async throws {
|
|
||||||
let mocked = await signedInAuth()
|
|
||||||
let captured = MockURLProtocol.Capture()
|
|
||||||
mocked.setHandler { request in
|
|
||||||
captured.store(request)
|
|
||||||
return (200, Data(#"{"success":true}"#.utf8))
|
|
||||||
}
|
|
||||||
|
|
||||||
try await mocked.auth.disableTotp(password: "pw")
|
|
||||||
let request = try #require(captured.request)
|
|
||||||
#expect(request.url?.path == "/api/v1/auth/two-factor/disable")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("disableTotp mit falschem Passwort → invalidCredentials")
|
|
||||||
func disableWrongPassword() async {
|
|
||||||
let mocked = await signedInAuth()
|
|
||||||
mocked.setHandler { _ in
|
|
||||||
(401, Data(#"{"error":"INVALID_CREDENTIALS","status":401}"#.utf8))
|
|
||||||
}
|
|
||||||
|
|
||||||
await #expect(throws: AuthError.invalidCredentials) {
|
|
||||||
try await mocked.auth.disableTotp(password: "wrong")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("getTotpUri liefert URI ohne Backup-Codes")
|
|
||||||
func getUriSuccess() async throws {
|
|
||||||
let mocked = await signedInAuth()
|
|
||||||
mocked.setHandler { _ in
|
|
||||||
(200, Data(#"""
|
|
||||||
{"totpURI":"otpauth://totp/Mana:u@x.de?secret=XYZ&issuer=Mana"}
|
|
||||||
"""#.utf8))
|
|
||||||
}
|
|
||||||
|
|
||||||
let uri = try await mocked.auth.getTotpUri(password: "pw")
|
|
||||||
#expect(uri.hasPrefix("otpauth://totp/"))
|
|
||||||
#expect(uri.contains("secret=XYZ"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("regenerateBackupCodes liefert neue Codes")
|
|
||||||
func regenerateSuccess() async throws {
|
|
||||||
let mocked = await signedInAuth()
|
|
||||||
let captured = MockURLProtocol.Capture()
|
|
||||||
mocked.setHandler { request in
|
|
||||||
captured.store(request)
|
|
||||||
return (200, Data(#"""
|
|
||||||
{"backupCodes":["new-1","new-2","new-3","new-4","new-5"]}
|
|
||||||
"""#.utf8))
|
|
||||||
}
|
|
||||||
|
|
||||||
let codes = try await mocked.auth.regenerateBackupCodes(password: "pw")
|
|
||||||
#expect(codes.count == 5)
|
|
||||||
#expect(codes.first == "new-1")
|
|
||||||
let request = try #require(captured.request)
|
|
||||||
#expect(request.url?.path == "/api/v1/auth/two-factor/generate-backup-codes")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,127 +0,0 @@
|
||||||
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")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -24,42 +24,4 @@ struct ManaAppConfigTests {
|
||||||
)
|
)
|
||||||
#expect(config.keychainAccessGroup == nil)
|
#expect(config.keychainAccessGroup == nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test("AppGroup ist optional, default nil")
|
|
||||||
func appGroupDefaultsNil() {
|
|
||||||
let config = DefaultManaAppConfig(
|
|
||||||
authBaseURL: URL(string: "https://auth.mana.how")!,
|
|
||||||
keychainService: "ev.mana.cards"
|
|
||||||
)
|
|
||||||
#expect(config.appGroup == nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("AppGroup wird durchgereicht wenn gesetzt")
|
|
||||||
func appGroupPassedThrough() {
|
|
||||||
let config = DefaultManaAppConfig(
|
|
||||||
authBaseURL: URL(string: "https://auth.mana.how")!,
|
|
||||||
keychainService: "ev.mana.cards",
|
|
||||||
appGroup: "group.ev.mana.cards"
|
|
||||||
)
|
|
||||||
#expect(config.appGroup == "group.ev.mana.cards")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("LogSubsystem default = keychainService")
|
|
||||||
func logSubsystemDefaultsToKeychainService() {
|
|
||||||
let config = DefaultManaAppConfig(
|
|
||||||
authBaseURL: URL(string: "https://auth.mana.how")!,
|
|
||||||
keychainService: "ev.mana.cards"
|
|
||||||
)
|
|
||||||
#expect(config.logSubsystem == "ev.mana.cards")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("LogSubsystem kann explizit überschrieben werden")
|
|
||||||
func logSubsystemOverride() {
|
|
||||||
let config = DefaultManaAppConfig(
|
|
||||||
authBaseURL: URL(string: "https://auth.mana.how")!,
|
|
||||||
keychainService: "ev.mana.cards",
|
|
||||||
logSubsystem: "ev.mana.cards.debug"
|
|
||||||
)
|
|
||||||
#expect(config.logSubsystem == "ev.mana.cards.debug")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,53 +0,0 @@
|
||||||
import Foundation
|
|
||||||
import Testing
|
|
||||||
@testable import ManaCore
|
|
||||||
|
|
||||||
@Suite("ManaAppLog")
|
|
||||||
struct ManaAppLogTests {
|
|
||||||
@Test("Init aus Config nimmt logSubsystem")
|
|
||||||
func initFromConfig() {
|
|
||||||
let config = DefaultManaAppConfig(
|
|
||||||
authBaseURL: URL(string: "https://auth.mana.how")!,
|
|
||||||
keychainService: "ev.mana.cards"
|
|
||||||
)
|
|
||||||
let log = ManaAppLog(config)
|
|
||||||
#expect(log.subsystem == "ev.mana.cards")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("Explizit gesetztes logSubsystem überschreibt keychainService")
|
|
||||||
func initFromConfigWithCustomSubsystem() {
|
|
||||||
let config = DefaultManaAppConfig(
|
|
||||||
authBaseURL: URL(string: "https://auth.mana.how")!,
|
|
||||||
keychainService: "ev.mana.cards",
|
|
||||||
logSubsystem: "ev.mana.cards.test"
|
|
||||||
)
|
|
||||||
let log = ManaAppLog(config)
|
|
||||||
#expect(log.subsystem == "ev.mana.cards.test")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("Direkter String-Constructor")
|
|
||||||
func initFromString() {
|
|
||||||
let log = ManaAppLog(subsystem: "ev.mana.test")
|
|
||||||
#expect(log.subsystem == "ev.mana.test")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("Standard-Kategorien sind erreichbar")
|
|
||||||
func standardCategoriesExist() {
|
|
||||||
let log = ManaAppLog(subsystem: "ev.mana.test")
|
|
||||||
// Logger ist nicht Equatable, aber wir können Existenz prüfen
|
|
||||||
// indem wir den Wert binden — Compile genügt.
|
|
||||||
let _ = log.app
|
|
||||||
let _ = log.auth
|
|
||||||
let _ = log.api
|
|
||||||
let _ = log.db
|
|
||||||
let _ = log.web
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("category() liefert beliebige Custom-Kategorie")
|
|
||||||
func customCategory() {
|
|
||||||
let log = ManaAppLog(subsystem: "ev.mana.test")
|
|
||||||
let _ = log.category("study")
|
|
||||||
let _ = log.category("tracking")
|
|
||||||
let _ = log.category("llm")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,127 +0,0 @@
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,102 +0,0 @@
|
||||||
import SwiftUI
|
|
||||||
import Testing
|
|
||||||
@testable import ManaTokens
|
|
||||||
|
|
||||||
@Suite("ManaTheme Variants")
|
|
||||||
struct ThemeTests {
|
|
||||||
@Test("Alle 8 Variants sind im enum vorhanden")
|
|
||||||
func allCasesPresent() {
|
|
||||||
let cases = ManaTheme.allCases.map(\.rawValue).sorted()
|
|
||||||
#expect(cases == [
|
|
||||||
"forest",
|
|
||||||
"lume",
|
|
||||||
"mana",
|
|
||||||
"monochrome",
|
|
||||||
"neutral",
|
|
||||||
"paper",
|
|
||||||
"skylight",
|
|
||||||
"twilight",
|
|
||||||
])
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("Jede Variant liefert nicht-leere Colors")
|
|
||||||
func everyVariantHasColors() {
|
|
||||||
for variant in ManaTheme.allCases {
|
|
||||||
let colors = variant.colors
|
|
||||||
// Existenz-Smoke — Color hat keinen Equatable-Color-Vergleich,
|
|
||||||
// aber wir können die Properties gegen Optional/Crash absichern.
|
|
||||||
let _: Color = colors.background
|
|
||||||
let _: Color = colors.foreground
|
|
||||||
let _: Color = colors.surface
|
|
||||||
let _: Color = colors.surfaceHover
|
|
||||||
let _: Color = colors.muted
|
|
||||||
let _: Color = colors.mutedForeground
|
|
||||||
let _: Color = colors.border
|
|
||||||
let _: Color = colors.primary
|
|
||||||
let _: Color = colors.primaryForeground
|
|
||||||
let _: Color = colors.error
|
|
||||||
let _: Color = colors.success
|
|
||||||
let _: Color = colors.warning
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("Convenience-Accessor matcht colors-Accessor")
|
|
||||||
func convenienceMatchesColors() {
|
|
||||||
// Identitäts-Smoke — beide Pfade müssen denselben Color-Wert liefern.
|
|
||||||
// Color ist nicht Equatable, also testen wir, dass es überhaupt
|
|
||||||
// möglich ist, beide Pfade typkorrekt zu nutzen.
|
|
||||||
let theme = ManaTheme.forest
|
|
||||||
let direct = theme.background
|
|
||||||
let viaColors = theme.colors.background
|
|
||||||
let _: (Color, Color) = (direct, viaColors)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("forest.primary entspricht forest.css (142, 76, 28)")
|
|
||||||
func forestPrimaryMatchesSpec() {
|
|
||||||
// Wir rekonstruieren den erwarteten Light-Wert aus HSL und
|
|
||||||
// vergleichen mit dem, was `Color.manaToken` für denselben Input
|
|
||||||
// liefert. Da `Color`-Vergleich nicht direkt möglich ist, prüfen
|
|
||||||
// wir indirekt über PlatformColor.fromHSL.
|
|
||||||
let expected = PlatformColor.fromHSL(142, 76, 28)
|
|
||||||
let components = rgbComponents(of: expected)
|
|
||||||
// Forest-Primary Light: HSL(142, 76, 28) → ~RGB(0.067, 0.493, 0.231)
|
|
||||||
#expect(approxEqual(components.r, 0.067, tolerance: 0.02))
|
|
||||||
#expect(approxEqual(components.g, 0.493, tolerance: 0.02))
|
|
||||||
#expect(approxEqual(components.b, 0.231, tolerance: 0.02))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("ManaTheme ist via rawValue rekonstruierbar")
|
|
||||||
func rawValueRoundtrip() {
|
|
||||||
for variant in ManaTheme.allCases {
|
|
||||||
let raw = variant.rawValue
|
|
||||||
let roundtrip = ManaTheme(rawValue: raw)
|
|
||||||
#expect(roundtrip == variant)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("Environment-Default ist mana")
|
|
||||||
func environmentDefault() {
|
|
||||||
// Wir können das Environment hier nicht direkt anzapfen ohne
|
|
||||||
// einen Host-View, aber wir spiegeln das Default per Konstante:
|
|
||||||
// ManaThemeEnvironmentKey.defaultValue ist auf .mana gesetzt.
|
|
||||||
// Smoke-Test, der die Konvention dokumentiert.
|
|
||||||
#expect(ManaTheme.allCases.contains(.mana))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Helpers
|
|
||||||
|
|
||||||
private func rgbComponents(of color: PlatformColor) -> (r: Double, g: Double, b: Double) {
|
|
||||||
#if canImport(UIKit)
|
|
||||||
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
|
|
||||||
color.getRed(&r, green: &g, blue: &b, alpha: &a)
|
|
||||||
return (Double(r), Double(g), Double(b))
|
|
||||||
#else
|
|
||||||
let space = color.usingColorSpace(.deviceRGB) ?? color
|
|
||||||
return (Double(space.redComponent), Double(space.greenComponent), Double(space.blueComponent))
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
private func approxEqual(_ a: Double, _ b: Double, tolerance: Double = 0.001) -> Bool {
|
|
||||||
abs(a - b) < tolerance
|
|
||||||
}
|
|
||||||
|
|
@ -1,87 +0,0 @@
|
||||||
{
|
|
||||||
"date": "2026-05-12",
|
|
||||||
"day_number": 1,
|
|
||||||
"weekday": "Dienstag",
|
|
||||||
"commits": 1,
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "Till JS",
|
|
||||||
"count": 1
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"additions": 1151,
|
|
||||||
"deletions": 0,
|
|
||||||
"net_lines": 1151,
|
|
||||||
"files_changed": 23,
|
|
||||||
"new_files": 0,
|
|
||||||
"deleted_files": 0,
|
|
||||||
"session": {
|
|
||||||
"first_commit_at": "2026-05-12T17:13:31.000Z",
|
|
||||||
"last_commit_at": "2026-05-12T17:13:31.000Z",
|
|
||||||
"total_span_minutes": 0,
|
|
||||||
"active_minutes": 0,
|
|
||||||
"pauses": [],
|
|
||||||
"longest_focus_minutes": 0
|
|
||||||
},
|
|
||||||
"top_dirs": [
|
|
||||||
{
|
|
||||||
"path": "Sources/ManaCore/Auth",
|
|
||||||
"pct": 22
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"path": "Sources/ManaTokens/Colors",
|
|
||||||
"pct": 13
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"path": "Sources/ManaTokens/Spacing",
|
|
||||||
"pct": 9
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"path": ".gitignore",
|
|
||||||
"pct": 4
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"path": ".swiftformat",
|
|
||||||
"pct": 4
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"top_extensions": [
|
|
||||||
{
|
|
||||||
"ext": ".swift",
|
|
||||||
"count": 17
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"ext": ".md",
|
|
||||||
"count": 3
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"ext": ".gitignore",
|
|
||||||
"count": 1
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"ext": ".swiftformat",
|
|
||||||
"count": 1
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"ext": ".yml",
|
|
||||||
"count": 1
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"tags": [],
|
|
||||||
"commits_list": [
|
|
||||||
{
|
|
||||||
"hash": "df6f67e",
|
|
||||||
"short": "v1.0.0 — initiale Extraktion aus memoro-native",
|
|
||||||
"type": null,
|
|
||||||
"scope": null,
|
|
||||||
"additions": 1151,
|
|
||||||
"deletions": 0,
|
|
||||||
"timestamp": "2026-05-12T19:13:31+02:00"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"review_state": "auto",
|
|
||||||
"llm": {
|
|
||||||
"model": null,
|
|
||||||
"generated_at": null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,83 +0,0 @@
|
||||||
---
|
|
||||||
date: 2026-05-12
|
|
||||||
day: 1
|
|
||||||
view: macher
|
|
||||||
weekday: Dienstag
|
|
||||||
commits: 1
|
|
||||||
review: written
|
|
||||||
---
|
|
||||||
# Dienstag, 2026-05-12 — Tag 1 (Macher-Sicht)
|
|
||||||
|
|
||||||
**v1.0.0 — initiale Extraktion aus memoro-native.** Swift-Package
|
|
||||||
mit zwei Library-Products: `ManaCore` (Auth + Transport) und
|
|
||||||
`ManaTokens` (Vereins-Designwerte aus `mana/docs/THEMING.md`).
|
|
||||||
|
|
||||||
## Stats
|
|
||||||
|
|
||||||
1 Commit, +1 151 / −0 LoC, 23 Files. 17× `.swift`. Top-Dirs:
|
|
||||||
`Sources/ManaCore/Auth` (22 %), `Sources/ManaTokens/Colors` (13 %),
|
|
||||||
`Sources/ManaTokens/Spacing` (9 %).
|
|
||||||
|
|
||||||
## Was im Initial-Commit drin ist
|
|
||||||
|
|
||||||
- **ManaCore.Auth** — `AuthClient` (Login + Refresh gegen
|
|
||||||
`/api/v1/auth/login` und `/api/v1/auth/refresh`),
|
|
||||||
`KeychainStorage` für Access/Refresh-Token-Persistenz, JWT-Decode
|
|
||||||
+ Expiry-Check, 401-Retry-Loop in `Transport`.
|
|
||||||
- **ManaCore.Transport** — URLSession-Wrapper, protocol-injected
|
|
||||||
für Tests, automatisches Refresh-on-401.
|
|
||||||
- **ManaTokens** — Vereins-Farben (`mana`, `forest`, demnächst
|
|
||||||
weitere Themes), Spacing-Skala, Typography-Konstanten. Spiegelt
|
|
||||||
`mana/docs/THEMING.md` 1:1.
|
|
||||||
- **Verpackung**: `Package.swift` mit Swift 6.0, iOS 18 / macOS 15,
|
|
||||||
Strict Concurrency komplett.
|
|
||||||
|
|
||||||
## Architektur-Entscheidungen
|
|
||||||
|
|
||||||
- **Genau zwei Library-Products.** `ManaCore` + `ManaTokens`. UI-
|
|
||||||
Komponenten (`ManaUI`) entstehen in einem separaten Repo
|
|
||||||
(`mana-swift-ui`, Phase ε). Hier nicht.
|
|
||||||
- **Keine externen Dependencies.** Nur Foundation, Security, OSLog,
|
|
||||||
Combine. Begründung Compliance + Build-Stabilität. Kein Alamofire,
|
|
||||||
kein Sentry.
|
|
||||||
- **Public API ist `Sendable`.** Swift-6-Concurrency strikt; jeder
|
|
||||||
Cross-Actor-Type annotiert.
|
|
||||||
- **App injiziert ihre Config.** `authBaseURL`, `keychainService`,
|
|
||||||
`keychainAccessGroup` kommen vom Caller. ManaCore hat keine
|
|
||||||
Hardcoded-App-Konstanten außer den mana-auth-Endpoint-Pfaden
|
|
||||||
(`/api/v1/auth/login`, `/api/v1/auth/refresh`).
|
|
||||||
- **OSLog statt print/Sentry.** ManaCore loggt unter Subsystem
|
|
||||||
`ev.mana.core`. Apps haben ihr eigenes Subsystem.
|
|
||||||
- **Tests gegen reine Logik**, nicht echtes Netzwerk. URLSession
|
|
||||||
über Protokoll-Injection mockbar.
|
|
||||||
- **Keine app-spezifischen Annahmen.** ManaCore weiß nichts über
|
|
||||||
Memos, Decks, Meals. Wenn das Paket „etwas für Memoro" lernen
|
|
||||||
will, gehört es zurück in memoro-native.
|
|
||||||
|
|
||||||
## Trade-offs
|
|
||||||
|
|
||||||
- **Wortwörtliche Extraktion**, keine spekulative Verallgemeinerung.
|
|
||||||
Die `AuthClient`-API ist die alte memoro-Variante; falls neue
|
|
||||||
Apps andere Bedürfnisse haben, lieber additiv erweitern als
|
|
||||||
vorab abstrahieren.
|
|
||||||
- **+1 151 LoC in einem Commit** ist groß, aber sauber: das war
|
|
||||||
ein Move-Commit, kein Feature-Commit. Hätte man auf Auth/
|
|
||||||
Transport/Tokens splitten können — pragmatisch zusammen, weil
|
|
||||||
alle drei aus demselben Source-Repo kamen.
|
|
||||||
- **Initiale Versions-Politik strikt Semver.** Patch-Bugfix,
|
|
||||||
Minor-additiv, Major-breaking. Pflege-Politik: letzte zwei
|
|
||||||
Major-Versionen.
|
|
||||||
|
|
||||||
## Offene Punkte
|
|
||||||
|
|
||||||
- **`mana-swift-ui`-Repo** existiert noch nicht — UI-Komponenten
|
|
||||||
bleiben pro App, bis Phase ε in einem dritten Repo extrahiert
|
|
||||||
wird (kam morgen, siehe `mana-swift-ui` Tag 1).
|
|
||||||
- **2FA-Endpoint-Spezifikation** im AuthClient fehlt — Memoro hatte
|
|
||||||
noch kein 2FA. Wenn die UI-Schicht 2FA bekommt, muss ManaCore
|
|
||||||
nachziehen.
|
|
||||||
- **Refresh-Token-Rotation** (`mana-auth` hat dafür einen Endpoint)
|
|
||||||
ist in AuthClient noch nicht. Patch-Bump-Kandidat.
|
|
||||||
- **Theme-Variants** in ManaTokens noch hartcodiert auf `mana` und
|
|
||||||
`forest`. Die im THEMING.md beschriebenen weiteren Themes
|
|
||||||
(`spruce`, `cardecky`, …) folgen.
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
||||||
---
|
|
||||||
date: 2026-05-12
|
|
||||||
day: 1
|
|
||||||
view: spieler
|
|
||||||
weekday: Dienstag
|
|
||||||
commits: 1
|
|
||||||
review: written
|
|
||||||
---
|
|
||||||
# Dienstag, 2026-05-12 — Tag 1
|
|
||||||
|
|
||||||
Dieses Paket ist die Grundlage, die alle Vereins-iPhone-/Mac-Apps
|
|
||||||
gemeinsam haben — Anmelden, Token-Verwaltung, Vereins-Farben und
|
|
||||||
-Abstände. Bisher steckte das in der Memoro-App; heute lebt es
|
|
||||||
eigenständig.
|
|
||||||
|
|
||||||
## Was sich für dich ändert
|
|
||||||
|
|
||||||
Direkt: nichts, was du in einer App sehen würdest. Indirekt: alle
|
|
||||||
zukünftigen mana-Apps (Cards, Manaspur, Nutriphi, weitere) bekommen
|
|
||||||
dieselbe Anmelde-Mechanik, dieselben Vereins-Farben — automatisch.
|
|
||||||
Was du in einer App lernst, fühlt sich in der nächsten gleich an.
|
|
||||||
|
|
||||||
## Hintergrund
|
|
||||||
|
|
||||||
Memoro hatte „mana-auth-Login" schon, Cards musste es kopieren,
|
|
||||||
Manaspur hätte es ein drittes Mal nachgebaut. Stattdessen liegt es
|
|
||||||
jetzt einmal an einem Ort.
|
|
||||||
|
|
@ -1,172 +0,0 @@
|
||||||
{
|
|
||||||
"date": "2026-05-13",
|
|
||||||
"day_number": 2,
|
|
||||||
"weekday": "Mittwoch",
|
|
||||||
"commits": 8,
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "Till JS",
|
|
||||||
"count": 8
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"additions": 5427,
|
|
||||||
"deletions": 2895,
|
|
||||||
"net_lines": 2532,
|
|
||||||
"files_changed": 408,
|
|
||||||
"new_files": 0,
|
|
||||||
"deleted_files": 0,
|
|
||||||
"session": {
|
|
||||||
"first_commit_at": "2026-05-13T15:18:23.000Z",
|
|
||||||
"last_commit_at": "2026-05-13T23:07:55.000Z",
|
|
||||||
"total_span_minutes": 470,
|
|
||||||
"active_minutes": 62,
|
|
||||||
"pauses": [
|
|
||||||
{
|
|
||||||
"from": "17:18",
|
|
||||||
"to": "19:22",
|
|
||||||
"minutes": 124
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": "19:35",
|
|
||||||
"to": "22:16",
|
|
||||||
"minutes": 160
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": "22:16",
|
|
||||||
"to": "00:20",
|
|
||||||
"minutes": 124
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"longest_focus_minutes": 48
|
|
||||||
},
|
|
||||||
"top_dirs": [
|
|
||||||
{
|
|
||||||
"path": "build/mana-swift-core.build/Release",
|
|
||||||
"pct": 19
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"path": "build/SwiftExplicitPrecompiledModules/1HSBLLLL9AUU4",
|
|
||||||
"pct": 15
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"path": "build/SwiftExplicitPrecompiledModules/1KYQZQ1R5RV9Z",
|
|
||||||
"pct": 15
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"path": "build/SwiftExplicitPrecompiledModules/33L8UAO7QRF6J",
|
|
||||||
"pct": 9
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"path": "build/SwiftExplicitPrecompiledModules/1IZ03QLWZJUL2",
|
|
||||||
"pct": 9
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"top_extensions": [
|
|
||||||
{
|
|
||||||
"ext": ".pcm",
|
|
||||||
"count": 620
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"ext": ".json",
|
|
||||||
"count": 30
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"ext": ".stringsdata",
|
|
||||||
"count": 28
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"ext": ".o",
|
|
||||||
"count": 26
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"ext": ".swift",
|
|
||||||
"count": 22
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"ext": ".modulemap",
|
|
||||||
"count": 8
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"tags": [
|
|
||||||
"transport"
|
|
||||||
],
|
|
||||||
"commits_list": [
|
|
||||||
{
|
|
||||||
"hash": "74aee8d",
|
|
||||||
"short": "fix(transport): URL-Konstruktion encoded ?-Query nicht mehr",
|
|
||||||
"type": "fix",
|
|
||||||
"scope": "transport",
|
|
||||||
"additions": 9,
|
|
||||||
"deletions": 1,
|
|
||||||
"timestamp": "2026-05-13T17:18:23+02:00"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"hash": "716509e",
|
|
||||||
"short": "v1.1.0 — Account-Lifecycle in ManaCore",
|
|
||||||
"type": null,
|
|
||||||
"scope": null,
|
|
||||||
"additions": 1226,
|
|
||||||
"deletions": 36,
|
|
||||||
"timestamp": "2026-05-13T19:22:19+02:00"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"hash": "3459c78",
|
|
||||||
"short": "v1.1.1 — Session-Token statt JWT für Account-Calls",
|
|
||||||
"type": null,
|
|
||||||
"scope": null,
|
|
||||||
"additions": 68,
|
|
||||||
"deletions": 16,
|
|
||||||
"timestamp": "2026-05-13T19:35:57+02:00"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"hash": "923b5d0",
|
|
||||||
"short": "v1.2.0 — Guest-Mode + Refresh-Resilience",
|
|
||||||
"type": null,
|
|
||||||
"scope": null,
|
|
||||||
"additions": 647,
|
|
||||||
"deletions": 160,
|
|
||||||
"timestamp": "2026-05-13T22:16:08+02:00"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"hash": "7526b80",
|
|
||||||
"short": "v1.3.0 — 2FA-Login-Challenge",
|
|
||||||
"type": null,
|
|
||||||
"scope": null,
|
|
||||||
"additions": 294,
|
|
||||||
"deletions": 0,
|
|
||||||
"timestamp": "2026-05-14T00:20:05+02:00"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"hash": "0a79083",
|
|
||||||
"short": "v1.4.0 — 2FA-Enrollment",
|
|
||||||
"type": null,
|
|
||||||
"scope": null,
|
|
||||||
"additions": 306,
|
|
||||||
"deletions": 0,
|
|
||||||
"timestamp": "2026-05-14T00:38:38+02:00"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"hash": "fe607c1",
|
|
||||||
"short": "v1.5.0 — getProfile() + ProfileInfo",
|
|
||||||
"type": null,
|
|
||||||
"scope": null,
|
|
||||||
"additions": 2876,
|
|
||||||
"deletions": 0,
|
|
||||||
"timestamp": "2026-05-14T01:06:50+02:00"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"hash": "216d9f8",
|
|
||||||
"short": "chore: untrack accidentally committed build/ + ignore",
|
|
||||||
"type": null,
|
|
||||||
"scope": null,
|
|
||||||
"additions": 1,
|
|
||||||
"deletions": 2682,
|
|
||||||
"timestamp": "2026-05-14T01:07:55+02:00"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"review_state": "auto",
|
|
||||||
"llm": {
|
|
||||||
"model": null,
|
|
||||||
"generated_at": null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,101 +0,0 @@
|
||||||
---
|
|
||||||
date: 2026-05-13
|
|
||||||
day: 2
|
|
||||||
view: macher
|
|
||||||
weekday: Mittwoch
|
|
||||||
commits: 8
|
|
||||||
review: written
|
|
||||||
---
|
|
||||||
# Mittwoch, 2026-05-13 — Tag 2 (Macher-Sicht)
|
|
||||||
|
|
||||||
Reifung von v1.0.0 zu v1.5.0 in einer Schicht. Sechs Sinn-Abschnitte
|
|
||||||
(Transport-Fix, Account-Lifecycle, Session-Token-Auth, Guest-Mode +
|
|
||||||
Refresh-Resilience, 2FA-Login, 2FA-Enrollment, Profile) plus ein
|
|
||||||
chore-Cleanup. Build-Verzeichnis war versehentlich committet — am
|
|
||||||
Ende des Tages aufgeräumt.
|
|
||||||
|
|
||||||
## Stats
|
|
||||||
|
|
||||||
8 Commits, +5 427 / −2 895 LoC, 408 Files. **Achtung: 2 682 der
|
|
||||||
Deletions kamen aus `chore: untrack build/`** — der eigentliche
|
|
||||||
Code-Delta ist eher +2 700 / −200. Top-Dirs sind irreführend (alle
|
|
||||||
`build/`-Sub-Dirs), weil der Initial-Push das build/ mit hatte.
|
|
||||||
Tags: `transport`. Session 15:18 → 01:08, 62 aktive Minuten in
|
|
||||||
4 Blöcken, längster Fokus 48 Min.
|
|
||||||
|
|
||||||
## Versions-Schritte
|
|
||||||
|
|
||||||
- **Transport-Fix** — URL-Konstruktion encoded `?`-Query nicht mehr.
|
|
||||||
Klassischer Bug: Path-Encoding lief gegen Query-String, dadurch
|
|
||||||
`?from=…` als `%3Ffrom%3D…` rausgeschickt. 9 / −1 Zeilen.
|
|
||||||
- **v1.1.0 — Account-Lifecycle.** Change-Email, Change-Password,
|
|
||||||
Account-Delete als public API in ManaCore. ViewModels in
|
|
||||||
mana-swift-ui ziehen morgen nach.
|
|
||||||
- **v1.1.1 — Session-Token statt JWT für Account-Calls.**
|
|
||||||
Account-Operationen sind sensibel, brauchen frischen
|
|
||||||
Re-Auth-Token, nicht den allgemeinen JWT.
|
|
||||||
- **v1.2.0 — Guest-Mode + Refresh-Resilience.** Wenn ein Refresh
|
|
||||||
mit transienten Errors fehlschlägt (Netz-Timeout, 503), bleibt
|
|
||||||
die Session aktiv und retried. Wenn der Refresh hart 401 macht,
|
|
||||||
fällt der State auf `.guest` zurück statt blind alle Tokens zu
|
|
||||||
wipen. **Das war der wichtigste Fix** — vorher hat mobiles Netz
|
|
||||||
Memoro-User regelmäßig rausgeworfen.
|
|
||||||
- **v1.3.0 — 2FA-Login-Challenge.** Wenn Login `requires_2fa: true`
|
|
||||||
zurückgibt, dann zweiter Round-Trip mit Code.
|
|
||||||
- **v1.4.0 — 2FA-Enrollment.** Enroll-Init (QR-Secret) + Enroll-
|
|
||||||
Verify + Disable mit Passwort + Backup-Code-Regenerate.
|
|
||||||
- **v1.5.0 — getProfile() + ProfileInfo.** Name, E-Mail,
|
|
||||||
Mitgliedsstatus, Tier. +2 876 LoC — viel davon vendored swift-
|
|
||||||
jose-Updates, die für RS256-JWKS-Verify nötig waren.
|
|
||||||
- **chore: untrack build/** — `.gitignore` für `build/`, vorhandene
|
|
||||||
Tracked-Files raus.
|
|
||||||
|
|
||||||
## Architektur-Entscheidungen
|
|
||||||
|
|
||||||
- **Session-Token (kurze TTL) für Account-Calls**, nicht der
|
|
||||||
allgemeine JWT. Begründung: bei Account-Delete oder Email-Change
|
|
||||||
wäre ein gestohlener JWT katastrophal; frischer Session-Token
|
|
||||||
begrenzt das Schaden-Fenster.
|
|
||||||
- **Refresh-Resilience: transient vs. permanent.** Transiente
|
|
||||||
Errors (Netz, 503, Timeout) halten Session, retry mit Backoff.
|
|
||||||
Permanente Errors (401, invalid_grant) führen zu `.guest`.
|
|
||||||
Vorher: jede Refresh-Failure → Wipe.
|
|
||||||
- **Guest-Mode als eigener State**, nicht „signed-out". Apps
|
|
||||||
können Inhalt anzeigen, der Read-Only ist, ohne dass sie eine
|
|
||||||
Login-Wand zeigen müssen.
|
|
||||||
- **2FA-API additiv**, kein Breaking-Change. Apps, die kein 2FA
|
|
||||||
unterstützen, ignorieren `requires_2fa`-Field.
|
|
||||||
- **ProfileInfo als eigenes DTO**, nicht in AuthClient verbaut.
|
|
||||||
Profile ist datenzentriert, AuthClient ist State-zentriert.
|
|
||||||
- **swift-jose vendored**, statt SPM-Dependency. Public-API-
|
|
||||||
Invariante „keine externen Dependencies" (Compliance-Direktive)
|
|
||||||
bleibt.
|
|
||||||
|
|
||||||
## Trade-offs
|
|
||||||
|
|
||||||
- **+2 876 LoC für v1.5.0** klingt monströs, ist aber zu 80 %
|
|
||||||
vendored swift-jose. Eigentliche Profile-API ist klein.
|
|
||||||
- **Sechs Tags an einem Tag** ist viel — bei strikter Semver wäre
|
|
||||||
das eine Tagesserie, kein Sprint. Akzeptiert, weil jeder Tag
|
|
||||||
einen klar abgegrenzten Sinn-Abschnitt hat.
|
|
||||||
- **build/-Verzeichnis untracken nachträglich** war Aufwand
|
|
||||||
(2 682 deletions in einem Commit). Ursache: SwiftPM-CLI legt
|
|
||||||
build/ im Repo-Root an, statt unter DerivedData — `.gitignore`
|
|
||||||
hätte Tag 1 schon gehört.
|
|
||||||
- **Session-Token-Mechanik** in v1.1.1 nachgeschoben, weil
|
|
||||||
v1.1.0 das nicht hatte. Hätte v1.1.0 direkt richtig machen
|
|
||||||
sollen; akzeptiert als „erste Lernzyklen".
|
|
||||||
|
|
||||||
## Offene Punkte
|
|
||||||
|
|
||||||
- **Refresh-Resilience Test-Coverage**: Unit-Tests für transiente
|
|
||||||
vs. permanente Fehler-Pfade existieren, aber kein
|
|
||||||
Real-World-Test (instabiles Netz simulieren).
|
|
||||||
- **2FA-Backup-Codes-Storage**: ManaCore liefert sie als Strings
|
|
||||||
zurück; UI muss sie sicher anzeigen + kopierbar machen. Liegt
|
|
||||||
bei mana-swift-ui.
|
|
||||||
- **getProfile() Cache-Politik**: derzeit kein Cache. Bei häufigen
|
|
||||||
Calls hilft eine kurze TTL.
|
|
||||||
- **Schema-Drift gegen mana-auth**: wenn der Server `ProfileInfo`-
|
|
||||||
Schema ändert, gibt's keinen Wire-Check. Pre-Live-Smoke wäre
|
|
||||||
sinnvoll.
|
|
||||||
|
|
@ -1,33 +0,0 @@
|
||||||
---
|
|
||||||
date: 2026-05-13
|
|
||||||
day: 2
|
|
||||||
view: spieler
|
|
||||||
weekday: Mittwoch
|
|
||||||
commits: 8
|
|
||||||
review: written
|
|
||||||
---
|
|
||||||
# Mittwoch, 2026-05-13 — Tag 2
|
|
||||||
|
|
||||||
Großer Tag für die Vereins-App-Grundlagen. Was alle Vereins-Apps
|
|
||||||
gemeinsam haben — Anmelden, Konto-Verwalten, Profil-Anzeigen — ist
|
|
||||||
heute stabiler und reicher geworden. Im Hintergrund.
|
|
||||||
|
|
||||||
## Was sich für dich in den Apps ändert
|
|
||||||
|
|
||||||
- **Du bleibst eingeloggt, auch wenn das Netz mal schwächelt.**
|
|
||||||
Vorher hat eine wackelige Verbindung manchmal den Login
|
|
||||||
rausgeworfen — neu hält die App durch und versucht es nochmal.
|
|
||||||
- **Gast-Modus** ist sauber möglich: Du kannst dir eine App ansehen,
|
|
||||||
bevor du dich anmeldest, ohne dass die App dich abwirft.
|
|
||||||
- **Konto-Aktionen funktionieren überall gleich** — E-Mail ändern,
|
|
||||||
Passwort wechseln, Konto löschen.
|
|
||||||
- **Zwei-Faktor-Schutz** ist nun durchgängig möglich (Login mit Code,
|
|
||||||
Einrichten in den Einstellungen).
|
|
||||||
- **Dein Profil** (Name, E-Mail, Mitgliedsstatus) kann von Apps
|
|
||||||
einheitlich angefragt werden.
|
|
||||||
|
|
||||||
## Hintergrund
|
|
||||||
|
|
||||||
Diese Sachen baut sonst jede App neu — mit kleinen Unterschieden, die
|
|
||||||
Menschen verwirren. Heute lagen sie an einem Ort, getestet, dokumentiert,
|
|
||||||
versioniert.
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue