SPB Git

Repository Public

AuthService.swift 13.1 KB 243 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Auth/AuthService.swift3// Description: Passkey ceremonies against the VQuant backend (sign-in, setup-link enrolment, re-verification) and the device session lifecycle.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    public init(credentialId: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userHandle: Data?) {15        self.credentialId = credentialId; self.clientDataJSON = clientDataJSON; self.authenticatorData = authenticatorData; self.signature = signature; self.userHandle = userHandle16    }17}1819public struct PasskeyRegistration: Sendable {20    public var credentialId: Data21    public var clientDataJSON: Data22    public var attestationObject: Data23    public var transports: [String]24    public init(credentialId: Data, clientDataJSON: Data, attestationObject: Data, transports: [String] = ["internal", "hybrid"]) {25        self.credentialId = credentialId; self.clientDataJSON = clientDataJSON; self.attestationObject = attestationObject; self.transports = transports26    }27}2829public struct AssertionRequest: Sendable, Equatable {30    public var rpId: String31    public var challenge: Data32    public var allowCredentials: [Data]33}3435public struct RegistrationRequest: Sendable, Equatable {36    public var rpId: String37    public var challenge: Data38    public var userId: Data39    public var userName: String40    public var excludeCredentials: [Data]41}4243/// The device side of a WebAuthn ceremony. The app implements it with AuthenticationServices (Touch ID, iCloud44/// Keychain, a nearby iPhone); tests use a software authenticator.45public protocol PasskeyAuthenticator: Sendable {46    func assert(_ request: AssertionRequest) async throws -> PasskeyAssertion47    func register(_ request: RegistrationRequest) async throws -> PasskeyRegistration48}4950public struct AuthError: Error, Sendable, Equatable, LocalizedError {51    public enum Code: Sendable, Equatable { case cancelled, refused, expiredLink, invalidLink, rateLimited, network, notAssociated, server }52    public let code: Code53    public let message: String54    public init(_ code: Code, _ message: String) { self.code = code; self.message = message }55    public var errorDescription: String? { message }56}5758// MARK: - Models5960public struct Account: Codable, Sendable, Equatable, Identifiable {61    public var id: String62    public var name: String63    public init(id: String, name: String) { self.id = id; self.name = name }64}6566public struct DeviceInfo: Codable, Sendable, Equatable, Identifiable {67    public var id: String68    public var label: String69    public var platform: String70    public var createdAt: Double71    public var lastUsedAt: Double?72    public var current: Bool?73    public var created: Date { Date(timeIntervalSince1970: createdAt / 1000) }74    public var lastUsed: Date? { lastUsedAt.map { Date(timeIntervalSince1970: $0 / 1000) } }75}7677public struct PasskeyInfo: Codable, Sendable, Equatable, Identifiable {78    public var ref: String79    public var label: String80    public var deviceType: String?81    public var backedUp: Bool82    public var createdAt: Double83    public var lastUsedAt: Double?84    public var id: String { ref }85    public var created: Date { Date(timeIntervalSince1970: createdAt / 1000) }86    public var lastUsed: Date? { lastUsedAt.map { Date(timeIntervalSince1970: $0 / 1000) } }87}8889public struct SessionInfo: Codable, Sendable, Equatable {90    public var user: Account91    public var device: DeviceInfo92    public var reauthFresh: Bool93    public var idleDays: Int94}9596public struct DeviceOverview: Codable, Sendable, Equatable {97    public var sessions: [DeviceInfo]98    public var passkeys: [PasskeyInfo]99    public var reauthFresh: Bool100}101102struct OpenedSession: Codable, Sendable {103    var token: String104    var user: Account105    var device: DeviceInfo106}107108// MARK: - Service109110/// Authentication against the same identities as the web app. A passkey (same relying party as vquant.spboucher.ai)111/// proves who the person is; the server answers with a device token that this Mac keeps in the Keychain and that the112/// owner can revoke from any other device. This service never sees key material or biometric data.113public final class AuthService: Sendable {114    private let api: APIClient115    private let authenticator: PasskeyAuthenticator116117    public init(api: APIClient, authenticator: PasskeyAuthenticator) { self.api = api; self.authenticator = authenticator }118119    public var hasStoredSession: Bool { api.hasToken }120121    /// Signs in with a passkey of an existing VQuant account. Returns the account.122    @discardableResult123    public func signIn() async throws -> Account {124        let options = try await post("/api/native/login/options", [:], authenticated: false)125        guard let req = Self.assertionRequest(options) else { throw AuthError(.server, "The server sent sign-in options this version cannot read.") }126        let a: PasskeyAssertion127        do { a = try await authenticator.assert(req) } catch { throw Self.explain(error) }128        let answer = try await post("/api/native/login/verify", ["response": Self.assertionJSON(a), "device": ["name": .string(api.identity.deviceName)]], authenticated: false)129        return try open(answer)130    }131132    /// Enrols this Mac with a single-use setup link (`https://…/setup/<token>`) or its bare token: creates a passkey133    /// for the invited person and signs in. This is the web app's own enrolment mechanism.134    @discardableResult135    public func enrol(setupLink: String) async throws -> Account {136        guard let token = Self.setupToken(from: setupLink, host: api.baseURL.host) else { throw AuthError(.invalidLink, "This is not a VQuant setup link.") }137        let options = try await post("/api/native/register/options", ["token": .string(token)], authenticated: false)138        guard let req = Self.registrationRequest(options) else { throw AuthError(.server, "The server sent enrolment options this version cannot read.") }139        let r: PasskeyRegistration140        do { r = try await authenticator.register(req) } catch { throw Self.explain(error) }141        let id = r.credentialId.base64URLEncodedString()142        let response: JSONValue = [143            "id": .string(id), "rawId": .string(id), "type": "public-key", "authenticatorAttachment": "platform", "clientExtensionResults": [:],144            "response": ["clientDataJSON": .string(r.clientDataJSON.base64URLEncodedString()), "attestationObject": .string(r.attestationObject.base64URLEncodedString()), "transports": .array(r.transports.map(JSONValue.string))],145        ]146        let answer = try await post("/api/native/register/verify", ["token": .string(token), "response": response, "device": ["name": .string(api.identity.deviceName)]], authenticated: false)147        return try open(answer)148    }149150    /// Server-side view of this device's session. Network errors are thrown, never reported as "signed out".151    public func session() async throws -> SessionInfo { try await api.decode(SessionInfo.self, .get, "/api/native/session") }152153    /// Fresh passkey check for the current session: sensitive operations are accepted for the next five minutes.154    public func reauthenticate() async throws {155        let options = try await post("/api/native/reauth/options", [:], authenticated: true)156        guard let req = Self.assertionRequest(options) else { throw AuthError(.server, "The server sent verification options this version cannot read.") }157        let a: PasskeyAssertion158        do { a = try await authenticator.assert(req) } catch { throw Self.explain(error) }159        _ = try await post("/api/native/reauth/verify", ["response": Self.assertionJSON(a)], authenticated: true)160    }161162    /// Revokes this device's session on the server, then forgets the token (even when the server cannot be reached).163    public func signOut() async {164        _ = try? await api.data(.post, "/api/native/logout")165        api.tokens.clear()166    }167168    public func devices() async throws -> DeviceOverview { try await api.decode(DeviceOverview.self, .get, "/api/native/devices") }169170    /// Ends the session of another device. The server asks for a fresh passkey check: it is performed once, then the call is retried.171    public func revokeDevice(_ id: String) async throws { try await sensitive { try await self.api.data(.delete, "/api/native/devices/\(APIClient.segment(id))") } }172173    public func deletePasskey(_ ref: String) async throws { try await sensitive { try await self.api.data(.delete, "/api/native/passkeys/\(APIClient.segment(ref))") } }174175    private func sensitive(_ call: @Sendable () async throws -> Data) async throws {176        do { _ = try await call() }177        catch let e as APIError where e.kind == .reauthRequired {178            try await reauthenticate()179            _ = try await call()180        }181    }182183    // MARK: Internals184185    private func open(_ answer: JSONValue) throws -> Account {186        guard let s = try? JSONDecoder().decode(OpenedSession.self, from: answer.data()), s.token.hasPrefix("vqn_") else { throw AuthError(.server, "The server did not open a session.") }187        do { try api.tokens.write(s.token) } catch { throw AuthError(.server, "The session could not be saved in the Keychain. \(error.localizedDescription)") }188        return s.user189    }190191    private func post(_ path: String, _ body: [String: JSONValue], authenticated: Bool) async throws -> JSONValue {192        do { return try await api.json(.post, path, body: .object(body), authenticated: authenticated) }193        catch let e as APIError {194            switch e.kind {195            case .network: throw AuthError(.network, e.message)196            case .rateLimited: throw AuthError(.rateLimited, "Too many attempts. Try again in a minute.")197            case .gone: throw AuthError(.expiredLink, "This setup link has expired or was already used. Ask for a new one.")198            case .unauthorized where !authenticated: throw AuthError(.refused, "The server does not know this passkey. Use a passkey created for VQuant, or enrol this Mac with a setup link.")199            case .unauthorized: throw e200            case .rejected: throw AuthError(.refused, "The server refused the enrolment. The setup link may already have been used.")201            default: throw AuthError(.server, e.message)202            }203        }204    }205206    static func assertionJSON(_ a: PasskeyAssertion) -> JSONValue {207        let id = a.credentialId.base64URLEncodedString()208        var response: [String: JSONValue] = ["clientDataJSON": .string(a.clientDataJSON.base64URLEncodedString()), "authenticatorData": .string(a.authenticatorData.base64URLEncodedString()), "signature": .string(a.signature.base64URLEncodedString())]209        if let h = a.userHandle, !h.isEmpty { response["userHandle"] = .string(h.base64URLEncodedString()) }210        return ["id": .string(id), "rawId": .string(id), "type": "public-key", "authenticatorAttachment": "platform", "clientExtensionResults": [:], "response": .object(response)]211    }212213    static func explain(_ error: Error) -> Error {214        if error is AuthError { return error }215        if error is CancellationError { return AuthError(.cancelled, "Verification cancelled.") }216        return AuthError(.refused, "The passkey verification did not complete. \(error.localizedDescription)")217    }218219    /// `PublicKeyCredentialRequestOptionsJSON` → request (challenge and ids are base64url).220    public static func assertionRequest(_ o: JSONValue) -> AssertionRequest? {221        guard let rp = o["rpId"]?.stringValue, let ch = o["challenge"]?.stringValue.flatMap(Data.init(base64URLEncoded:)), !ch.isEmpty else { return nil }222        let allow = (o["allowCredentials"]?.arrayValue ?? []).compactMap { $0["id"]?.stringValue.flatMap(Data.init(base64URLEncoded:)) }223        return AssertionRequest(rpId: rp, challenge: ch, allowCredentials: allow)224    }225226    public static func registrationRequest(_ o: JSONValue) -> RegistrationRequest? {227        guard let rp = o["rp"]?["id"]?.stringValue, let ch = o["challenge"]?.stringValue.flatMap(Data.init(base64URLEncoded:)), !ch.isEmpty,228              let uid = o["user"]?["id"]?.stringValue.flatMap(Data.init(base64URLEncoded:)) else { return nil }229        let exclude = (o["excludeCredentials"]?.arrayValue ?? []).compactMap { $0["id"]?.stringValue.flatMap(Data.init(base64URLEncoded:)) }230        return RegistrationRequest(rpId: rp, challenge: ch, userId: uid, userName: o["user"]?["name"]?.stringValue ?? "VQuant", excludeCredentials: exclude)231    }232233    /// Accepts `https://<host>/setup/<token>` (only for the configured server) or a bare token.234    public static func setupToken(from input: String, host: String?) -> String? {235        let s = input.trimmingCharacters(in: .whitespacesAndNewlines)236        let valid: (String) -> Bool = { $0.range(of: "^[A-Za-z0-9_-]{32,128}$", options: .regularExpression) != nil }237        if valid(s) { return s }238        guard let url = URL(string: s), let h = url.host, h == host, url.pathComponents.count == 3, url.pathComponents[1] == "setup" else { return nil }239        let t = url.pathComponents[2]240        return valid(t) ? t : nil241    }242}243
Files main
Menu

Theme