SPB Git

Repository Public

AuthService.swift 10.9 KB 180 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Core/Authentication/AuthService.swift3// Description: Passkey ceremonies against the backend (sign-in, re-authentication, enrolment), session lifecycle and account management calls.4import Foundation56// MARK: - Authenticator abstraction78public struct PasskeyAssertion: Sendable {9    public var credentialId: Data10    public var clientDataJSON: Data11    public var authenticatorData: Data12    public var signature: Data13    public var userHandle: Data?14    /// "platform" (this Mac / iCloud Keychain) or "cross-platform" (security key).15    public var attachment: String16    public init(credentialId: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userHandle: Data?, attachment: String = "platform") {17        self.credentialId = credentialId; self.clientDataJSON = clientDataJSON; self.authenticatorData = authenticatorData; self.signature = signature; self.userHandle = userHandle; self.attachment = attachment18    }19}2021public struct PasskeyRegistration: Sendable {22    public var credentialId: Data23    public var clientDataJSON: Data24    public var attestationObject: Data25    public var transports: [String]26    public var attachment: String27    public init(credentialId: Data, clientDataJSON: Data, attestationObject: Data, transports: [String] = ["internal", "hybrid"], attachment: String = "platform") {28        self.credentialId = credentialId; self.clientDataJSON = clientDataJSON; self.attestationObject = attestationObject; self.transports = transports; self.attachment = attachment29    }30}3132public struct AssertionRequest: Sendable, Equatable {33    public var rpId: String34    public var challenge: Data35    public var allowCredentials: [Data]36}3738public struct RegistrationRequest: Sendable, Equatable {39    public var rpId: String40    public var rpName: String41    public var challenge: Data42    public var userId: Data43    public var userName: String44    public var excludeCredentials: [Data]45}4647/// Performs the device side of a WebAuthn ceremony. The app implements it with AuthenticationServices (Touch ID /48/// iCloud Keychain / security keys); tests use a software authenticator. Biometric data never reaches this code.49public protocol PasskeyAuthenticator: Sendable {50    func assert(_ request: AssertionRequest) async throws -> PasskeyAssertion51    func register(_ request: RegistrationRequest) async throws -> PasskeyRegistration52}5354public struct PasskeyError: Error, Sendable, Equatable, LocalizedError {55    public enum Code: Sendable, Equatable { case cancelled, unsupported, refused, rateLimited, network, config, noSetupWindow }56    public let code: Code57    public let message: String58    public init(_ code: Code, _ message: String) { self.code = code; self.message = message }59    public var errorDescription: String? { message }60}6162// MARK: - Service6364public enum SessionState: Sendable, Equatable { case unknown, signedOut, signedIn }6566/// All authentication flows. The session itself is a server-side session whose opaque token is kept in the Keychain by67/// the `APIClient` cookie jar; this service never sees or stores key material.68public final class AuthService: Sendable {69    private let api: APIClient70    private let authenticator: PasskeyAuthenticator7172    public init(api: APIClient, authenticator: PasskeyAuthenticator) {73        self.api = api; self.authenticator = authenticator74        api.reauthenticator = { [weak self] in try await self?.reauthenticate() }75    }7677    public var hasStoredSession: Bool { api.hasSession }7879    /// Server-side view: is the stored token still a valid session? (Network errors are thrown, not treated as signed out.)80    public func state() async throws -> AuthState { try await api.decode(AuthState.self, .get, "/api/auth/state") }8182    public func signIn() async throws {83        try await ceremony(options: "/api/auth/login/options", verify: "/api/auth/login/verify", extra: [:])84        guard api.hasSession else { throw PasskeyError(.refused, "Le serveur n'a pas ouvert de session.") }85    }8687    /// Fresh verification for the current session: unlocks sensitive operations for 10 minutes and rotates the token.88    public func reauthenticate() async throws {89        try await ceremony(options: "/api/auth/reauth/options", verify: "/api/auth/reauth/verify", extra: [:])90    }9192    /// Opens a 10-minute enrolment window with a bootstrap or recovery code typed by the owner.93    public func redeemSetupCode(_ code: String) async throws {94        _ = try await post("/api/auth/setup", ["code": .string(code)])95    }9697    /// Registers a passkey: for a signed-in session (adding this Mac) or inside an enrolment window.98    public func registerPasskey(label: String?) async throws {99        let j = try await post("/api/auth/register/options", [:])100        guard let o = j["options"], let req = Self.registrationRequest(o) else { throw PasskeyError(.refused, "Options d'enrôlement illisibles.") }101        let reg: PasskeyRegistration102        do { reg = try await authenticator.register(req) } catch { throw Self.explain(error) }103        let id = reg.credentialId.base64URLEncodedString()104        var body: [String: JSONValue] = ["response": [105            "id": .string(id), "rawId": .string(id), "type": "public-key", "authenticatorAttachment": .string(reg.attachment), "clientExtensionResults": [:],106            "response": ["clientDataJSON": .string(reg.clientDataJSON.base64URLEncodedString()), "attestationObject": .string(reg.attestationObject.base64URLEncodedString()), "transports": .array(reg.transports.map(JSONValue.string))],107        ]]108        if let label, !label.trimmingCharacters(in: .whitespaces).isEmpty { body["label"] = .string(String(label.prefix(60))) }109        _ = try await post("/api/auth/register/verify", body)110    }111112    /// Revokes this device's session on the server, then forgets the token locally (even when the server is unreachable).113    public func signOut() async {114        _ = try? await api.raw(.post, "/api/auth/logout", allowReauth: false)115        api.cookies.clear()116    }117118    // MARK: Account management119120    public func passkeys() async throws -> PasskeyOverview { try await api.decode(PasskeyOverview.self, .get, "/api/auth/passkeys") }121    public func renamePasskey(_ id: String, label: String) async throws { _ = try await api.raw(.patch, "/api/auth/passkeys/\(Self.pathEscape(id))", json: ["label": .string(label)]) }122    public func revokePasskey(_ id: String) async throws -> Bool { try await api.json(.delete, "/api/auth/passkeys/\(Self.pathEscape(id))")["signedOut"]?.boolValue ?? false }123    public func sessions() async throws -> [DeviceSession] { try await api.decode([DeviceSession].self, .get, "/api/auth/sessions", key: "sessions") }124    public func revokeSession(_ id: String) async throws -> Bool { try await api.json(.delete, "/api/auth/sessions/\(id)")["signedOut"]?.boolValue ?? false }125    public func revokeAllSessions(includeCurrent: Bool) async throws { _ = try await api.raw(.delete, "/api/auth/sessions", json: ["includeCurrent": .bool(includeCurrent)]); if includeCurrent { api.cookies.clear() } }126    public func generateRecoveryCodes() async throws -> [String] { try await api.json(.post, "/api/auth/recovery-codes")["codes"]?.arrayValue?.compactMap(\.stringValue) ?? [] }127    public func events() async throws -> [AuthEvent] { try await api.decode([AuthEvent].self, .get, "/api/auth/events", key: "events") }128129    // MARK: Internals130131    private static func pathEscape(_ s: String) -> String { s.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed.subtracting(CharacterSet(charactersIn: "/"))) ?? s }132133    private func post(_ path: String, _ body: [String: JSONValue]) async throws -> JSONValue {134        do { return try await api.json(.post, path, body: .object(body), allowReauth: false) }135        catch let e as APIError {136            switch e.kind {137            case .network: throw PasskeyError(.network, "Réseau indisponible. Vérifie ta connexion et réessaie.")138            case .rateLimited: throw PasskeyError(.rateLimited, "Trop de tentatives. Réessaie dans quelques minutes.")139            case .reauthRequired: throw e140            default:141                if e.code == "bad_origin" { throw PasskeyError(.config, "Cette application n'est pas une origine autorisée par le serveur (AUTH_ORIGINS).") }142                if path.hasSuffix("register/options"), e.status == 401 { throw PasskeyError(.noSetupWindow, e.message) }143                throw PasskeyError(.refused, e.message)144            }145        }146    }147148    private func ceremony(options: String, verify: String, extra: [String: JSONValue]) async throws {149        let j = try await post(options, [:])150        guard let o = j["options"], let req = Self.assertionRequest(o) else { throw PasskeyError(.refused, "Options de connexion illisibles.") }151        let a: PasskeyAssertion152        do { a = try await authenticator.assert(req) } catch { throw Self.explain(error) }153        let id = a.credentialId.base64URLEncodedString()154        var response: [String: JSONValue] = ["clientDataJSON": .string(a.clientDataJSON.base64URLEncodedString()), "authenticatorData": .string(a.authenticatorData.base64URLEncodedString()), "signature": .string(a.signature.base64URLEncodedString())]155        if let h = a.userHandle, !h.isEmpty { response["userHandle"] = .string(h.base64URLEncodedString()) }156        var body = extra157        body["response"] = ["id": .string(id), "rawId": .string(id), "type": "public-key", "authenticatorAttachment": .string(a.attachment), "clientExtensionResults": [:], "response": .object(response)]158        _ = try await post(verify, body)159    }160161    static func explain(_ error: Error) -> Error {162        if error is PasskeyError { return error }163        if error is CancellationError { return PasskeyError(.cancelled, "Vérification annulée.") }164        return PasskeyError(.refused, "La vérification n'a pas abouti.")165    }166167    /// `PublicKeyCredentialRequestOptionsJSON` → request. The challenge is base64url.168    public static func assertionRequest(_ o: JSONValue) -> AssertionRequest? {169        guard let rp = o["rpId"]?.stringValue, let ch = o["challenge"]?.stringValue.flatMap(Data.init(base64URLEncoded:)) else { return nil }170        let allow = (o["allowCredentials"]?.arrayValue ?? []).compactMap { $0["id"]?.stringValue.flatMap(Data.init(base64URLEncoded:)) }171        return AssertionRequest(rpId: rp, challenge: ch, allowCredentials: allow)172    }173    public static func registrationRequest(_ o: JSONValue) -> RegistrationRequest? {174        guard let rp = o["rp"]?["id"]?.stringValue, let ch = o["challenge"]?.stringValue.flatMap(Data.init(base64URLEncoded:)),175              let uid = o["user"]?["id"]?.stringValue.flatMap(Data.init(base64URLEncoded:)) else { return nil }176        let exclude = (o["excludeCredentials"]?.arrayValue ?? []).compactMap { $0["id"]?.stringValue.flatMap(Data.init(base64URLEncoded:)) }177        return RegistrationRequest(rpId: rp, rpName: o["rp"]?["name"]?.stringValue ?? rp, challenge: ch, userId: uid, userName: o["user"]?["name"]?.stringValue ?? "proprietaire", excludeCredentials: exclude)178    }179}180
Files main
Menu

Theme