v1.3.0 — 2FA-Login-Challenge
Mini-Sprint A des 2FA-Vollausbaus. Apps mit aktivem TOTP-2FA können
sich nativ einloggen. Komplett additiv.
AuthClient.Status um .twoFactorRequired(token, methods, email)
erweitert. signIn() erkennt automatisch den Server-Pfad
{twoFactorRequired: true, ...} und routet zum neuen Status.
Neue Methoden in AuthClient+Account:
- verifyTotp(code:trustDevice:) — 6-stellige Codes aus Authenticator-
App. Bei Erfolg .signedIn, bei Fehler bleibt Status im Challenge
(User kann retry mit anderem Code).
- verifyBackupCode(code:trustDevice:) — einmalige Codes als Fallback.
Wire-Format: Client schickt {code, twoFactorToken, trustDevice} an
/api/v1/auth/two-factor/verify-{totp,backup-code}. Server (mana-auth)
re-injectet den twoFactorToken als better-auth.two_factor-Cookie und
delegiert an Better Auths Plugin.
5 neue Tests, 59/59 grün.
Setzt mana-auth-Server mit den entsprechenden Custom-Endpoints
voraus — siehe gleichzeitiger Commit im mana-Repo.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
923b5d06b5
commit
7526b807da
4 changed files with 294 additions and 0 deletions
39
CHANGELOG.md
39
CHANGELOG.md
|
|
@ -4,6 +4,45 @@ Alle Änderungen werden hier dokumentiert. Format orientiert an
|
|||
[Keep a Changelog](https://keepachangelog.com), Versionierung nach
|
||||
[Semver](https://semver.org).
|
||||
|
||||
## [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-
|
||||
|
|
|
|||
|
|
@ -388,3 +388,96 @@ private struct ChangePasswordRequest: Encodable {
|
|||
private struct DeleteAccountRequest: Encodable {
|
||||
let password: String
|
||||
}
|
||||
|
||||
// MARK: - Two-Factor (Login-Challenge)
|
||||
|
||||
public extension AuthClient {
|
||||
/// Verifiziert einen TOTP-Code im 2FA-Login-Flow. Vorbedingung:
|
||||
/// Status ist ``Status/twoFactorRequired(token:methods:email:)``
|
||||
/// (typisch nach `signIn(...)`).
|
||||
///
|
||||
/// Bei Erfolg setzt der Server die Session, ManaCore persistiert
|
||||
/// Tokens und der Status wird `.signedIn(email:)`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - code: 6-stelliger TOTP-Code aus der Authenticator-App.
|
||||
/// - trustDevice: Wenn `true`, setzt der Server einen
|
||||
/// `trust_device`-Cookie. Bei Native heute ohne Effekt
|
||||
/// (Cookies werden nicht persistiert) — wir spiegeln das Flag
|
||||
/// trotzdem für künftige Erweiterungen.
|
||||
///
|
||||
/// - Throws: ``AuthError/twoFactorFailed`` bei falschem Code,
|
||||
/// ``AuthError/tokenExpired`` wenn der Challenge-Token alt ist,
|
||||
/// plus Standard-Netzwerk-Fehler.
|
||||
func verifyTotp(code: String, trustDevice: Bool = false) async throws {
|
||||
try await verifyTwoFactor(
|
||||
path: "/api/v1/auth/two-factor/verify-totp",
|
||||
code: code,
|
||||
trustDevice: trustDevice
|
||||
)
|
||||
}
|
||||
|
||||
/// Verifiziert einen Backup-Code im 2FA-Login-Flow. Same Pre-/
|
||||
/// Postconditions wie ``verifyTotp(code:trustDevice:)`` — der
|
||||
/// Server entscheidet anhand des Endpoints, welches Verfahren er
|
||||
/// nutzt. Backup-Codes werden vom Server beim Setup generiert
|
||||
/// und einmalig konsumiert.
|
||||
func verifyBackupCode(code: String, trustDevice: Bool = false) async throws {
|
||||
try await verifyTwoFactor(
|
||||
path: "/api/v1/auth/two-factor/verify-backup-code",
|
||||
code: code,
|
||||
trustDevice: trustDevice
|
||||
)
|
||||
}
|
||||
|
||||
private func verifyTwoFactor(
|
||||
path: String,
|
||||
code: String,
|
||||
trustDevice: Bool
|
||||
) async throws {
|
||||
guard case let .twoFactorRequired(token, _, email) = status else {
|
||||
throw AuthError.validation(
|
||||
message: "Kein 2FA-Challenge aktiv — verifyTotp setzt eine vorherige signIn-Antwort mit .twoFactorRequired voraus"
|
||||
)
|
||||
}
|
||||
guard !code.isEmpty else {
|
||||
throw AuthError.validation(message: "Code ist erforderlich")
|
||||
}
|
||||
|
||||
let body = TwoFactorVerifyRequest(
|
||||
code: code,
|
||||
twoFactorToken: token,
|
||||
trustDevice: trustDevice
|
||||
)
|
||||
let (data, http) = try await postJSON(path: path, body: body)
|
||||
guard http.statusCode == 200 else {
|
||||
throw AuthError.classify(
|
||||
status: http.statusCode,
|
||||
data: data,
|
||||
retryAfterHeader: http.retryAfterSeconds
|
||||
)
|
||||
}
|
||||
|
||||
let token2 = try JSONDecoder().decode(TwoFactorVerifyResponse.self, from: data)
|
||||
guard let access = token2.accessToken, let refresh = token2.refreshToken else {
|
||||
// Server hat 200 zurück, aber keine Tokens. Sollte nicht
|
||||
// passieren — UI bleibt im 2FA-Required-Zustand.
|
||||
throw AuthError.decoding("Tokens fehlen in 2FA-Verify-Antwort")
|
||||
}
|
||||
|
||||
try persistSession(email: email, accessToken: access, refreshToken: refresh)
|
||||
CoreLog.auth.info("2FA verify successful — signed in")
|
||||
}
|
||||
}
|
||||
|
||||
private struct TwoFactorVerifyRequest: Encodable {
|
||||
let code: String
|
||||
let twoFactorToken: String
|
||||
let trustDevice: Bool
|
||||
}
|
||||
|
||||
private struct TwoFactorVerifyResponse: Decodable {
|
||||
let success: Bool?
|
||||
let accessToken: String?
|
||||
let refreshToken: String?
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,6 +28,14 @@ public final class AuthClient {
|
|||
/// Status erreichbar; schreibende Endpoints nicht.
|
||||
case guest(id: String)
|
||||
case signingIn
|
||||
/// Sign-In war erfolgreich aber der Account hat 2FA aktiviert.
|
||||
/// UI fragt nun den TOTP-Code (oder einen Backup-Code) ab und
|
||||
/// ruft `verifyTotp(code:trustDevice:)` / `verifyBackupCode(...)`
|
||||
/// mit dem hier gespeicherten Token auf.
|
||||
///
|
||||
/// `token` ist der Better-Auth-`two_factor`-Cookie-Wert, vom
|
||||
/// Server in der Login-Response als `twoFactorToken` mitgeliefert.
|
||||
case twoFactorRequired(token: String, methods: [String], email: String)
|
||||
case signedIn(email: String)
|
||||
case error(String)
|
||||
}
|
||||
|
|
@ -160,6 +168,23 @@ public final class AuthClient {
|
|||
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)
|
||||
try keychain.setString(token.accessToken, for: .accessToken)
|
||||
try keychain.setString(token.refreshToken, for: .refreshToken)
|
||||
|
|
@ -339,6 +364,16 @@ struct TokenResponse: Decodable {
|
|||
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 {
|
||||
/// Liest `Retry-After` als Anzahl Sekunden. Server schickt Integer-
|
||||
/// Sekunden (siehe `lib/auth-errors.ts`). HTTP-Datum-Variante wird
|
||||
|
|
|
|||
127
Tests/ManaCoreTests/AuthClientTwoFactorTests.swift
Normal file
127
Tests/ManaCoreTests/AuthClientTwoFactorTests.swift
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
import Foundation
|
||||
import Testing
|
||||
@testable import ManaCore
|
||||
|
||||
@Suite("AuthClient 2FA-Login-Challenge")
|
||||
@MainActor
|
||||
struct AuthClientTwoFactorTests {
|
||||
@Test("signIn mit 2FA-Account → .twoFactorRequired statt .signedIn")
|
||||
func signInRedirectsToTwoFactor() async {
|
||||
let mocked = makeMockedAuth()
|
||||
mocked.setHandler { _ in
|
||||
(200, Data(#"""
|
||||
{"twoFactorRequired":true,"twoFactorMethods":["totp"],"twoFactorToken":"tf-abc123"}
|
||||
"""#.utf8))
|
||||
}
|
||||
|
||||
await mocked.auth.signIn(email: "u@x.de", password: "pw")
|
||||
if case let .twoFactorRequired(token, methods, email) = mocked.auth.status {
|
||||
#expect(token == "tf-abc123")
|
||||
#expect(methods == ["totp"])
|
||||
#expect(email == "u@x.de")
|
||||
} else {
|
||||
Issue.record("Expected .twoFactorRequired, got \(mocked.auth.status)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("verifyTotp erfolgreich → .signedIn")
|
||||
func verifyTotpSuccess() async throws {
|
||||
let mocked = makeMockedAuth()
|
||||
// Schritt 1: signIn liefert 2FA-Challenge.
|
||||
mocked.setHandler { _ in
|
||||
(200, Data(#"""
|
||||
{"twoFactorRequired":true,"twoFactorMethods":["totp"],"twoFactorToken":"tf-xyz"}
|
||||
"""#.utf8))
|
||||
}
|
||||
await mocked.auth.signIn(email: "u@x.de", password: "pw")
|
||||
|
||||
// Schritt 2: verifyTotp liefert Tokens.
|
||||
let access = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
|
||||
let captured = MockURLProtocol.Capture()
|
||||
mocked.setHandler { request in
|
||||
captured.store(request)
|
||||
return (200, Data(#"""
|
||||
{"success":true,"accessToken":"\#(access)","refreshToken":"r1"}
|
||||
"""#.utf8))
|
||||
}
|
||||
|
||||
try await mocked.auth.verifyTotp(code: "123456")
|
||||
#expect(mocked.auth.status == .signedIn(email: "u@x.de"))
|
||||
|
||||
let request = try #require(captured.request)
|
||||
#expect(request.url?.path == "/api/v1/auth/two-factor/verify-totp")
|
||||
// Body trägt code + twoFactorToken aus dem Challenge-Status
|
||||
let body = request.httpBody ?? request.bodyStreamData() ?? Data()
|
||||
let json = try JSONSerialization.jsonObject(with: body) as? [String: Any] ?? [:]
|
||||
#expect(json["code"] as? String == "123456")
|
||||
#expect(json["twoFactorToken"] as? String == "tf-xyz")
|
||||
}
|
||||
|
||||
@Test("verifyTotp ohne aktiven 2FA-Challenge wirft validation")
|
||||
func verifyTotpRequiresChallenge() async {
|
||||
let mocked = makeMockedAuth()
|
||||
// Status ist initial .unknown — kein 2FA-Challenge.
|
||||
do {
|
||||
try await mocked.auth.verifyTotp(code: "123456")
|
||||
Issue.record("Expected throw")
|
||||
} catch let AuthError.validation(message) {
|
||||
#expect(message?.contains("2FA-Challenge") == true)
|
||||
} catch {
|
||||
Issue.record("Unexpected error: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("verifyTotp mit falschem Code → twoFactorFailed, bleibt im Challenge")
|
||||
func verifyTotpWrongCode() async {
|
||||
let mocked = makeMockedAuth()
|
||||
mocked.setHandler { _ in
|
||||
(200, Data(#"""
|
||||
{"twoFactorRequired":true,"twoFactorMethods":["totp"],"twoFactorToken":"tf-xyz"}
|
||||
"""#.utf8))
|
||||
}
|
||||
await mocked.auth.signIn(email: "u@x.de", password: "pw")
|
||||
|
||||
mocked.setHandler { _ in
|
||||
(401, Data(#"{"error":"TWO_FACTOR_FAILED","status":401}"#.utf8))
|
||||
}
|
||||
|
||||
do {
|
||||
try await mocked.auth.verifyTotp(code: "000000")
|
||||
Issue.record("Expected throw")
|
||||
} catch AuthError.twoFactorFailed {
|
||||
// Status bleibt im Challenge — User kann erneut versuchen
|
||||
if case .twoFactorRequired = mocked.auth.status {
|
||||
#expect(Bool(true))
|
||||
} else {
|
||||
Issue.record("Status should remain .twoFactorRequired, got \(mocked.auth.status)")
|
||||
}
|
||||
} catch {
|
||||
Issue.record("Unexpected error: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("verifyBackupCode erfolgreich → .signedIn")
|
||||
func verifyBackupCodeSuccess() async throws {
|
||||
let mocked = makeMockedAuth()
|
||||
mocked.setHandler { _ in
|
||||
(200, Data(#"""
|
||||
{"twoFactorRequired":true,"twoFactorMethods":["totp"],"twoFactorToken":"tf-xyz"}
|
||||
"""#.utf8))
|
||||
}
|
||||
await mocked.auth.signIn(email: "u@x.de", password: "pw")
|
||||
|
||||
let access = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
|
||||
let captured = MockURLProtocol.Capture()
|
||||
mocked.setHandler { request in
|
||||
captured.store(request)
|
||||
return (200, Data(#"""
|
||||
{"success":true,"accessToken":"\#(access)","refreshToken":"r1"}
|
||||
"""#.utf8))
|
||||
}
|
||||
|
||||
try await mocked.auth.verifyBackupCode(code: "abc-def-ghi")
|
||||
#expect(mocked.auth.status == .signedIn(email: "u@x.de"))
|
||||
let request = try #require(captured.request)
|
||||
#expect(request.url?.path == "/api/v1/auth/two-factor/verify-backup-code")
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue