SPB Git

Repository Public

AuthService.swift 3.7 KB 81 lines swift

1// SP Notes Core2// File: Sources/SPNotesAPI/AuthService.swift3// Description: The complete passkey flows of the apps — sign-in, step-up, adding a passkey, sign-out — composed from4//              the typed endpoints, the system authorizer and the token store behind the transport.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910/// Sign-in and session management. Errors are `APIError` for the network half and `PasskeyError` for the device half11/// (`PasskeyError.cancelled` when the person dismisses the sheet).12public final class AuthService: Sendable {13    public let api: NotesAPI14    private let authorizer: any PasskeyAuthorizing1516    public init(api: NotesAPI, authorizer: any PasskeyAuthorizing) {17        self.api = api18        self.authorizer = authorizer19    }2021    /// Whether a session token is held. The server may still refuse it: the first 401 clears it and emits22    /// `SessionEvent.signedOut` on `HTTPClient.sessionEvents()`.23    public var isSignedIn: Bool {24        get async { await api.client.hasSession }25    }2627    /// Sign-in: challenge from the server → system passkey sheet → verification by the server → session token stored.28    @discardableResult29    public func signIn() async throws -> LoginResult {30        let options = try await api.loginOptions()31        let credential = try await authorizer.assertion(for: options)32        let result = try await api.loginVerify(credential)33        guard await api.client.hasSession else { throw APIError.invalidResponse }   // 200 without a session cookie34        return result35    }3637    /// Step-up: a fresh passkey verification for the current session. Unlocks the sensitive operations for a few38    /// minutes (`freshForMs`) and rotates the session token.39    @discardableResult40    public func stepUp() async throws -> ReauthResult {41        let options = try await api.reauthOptions()42        let credential = try await authorizer.assertion(for: options)43        return try await api.reauthVerify(credential)44    }4546    /// Creates a passkey for this device and registers it on the account.47    /// - Parameters:48    ///   - label: name shown in the passkey list (≤ 60 characters); the server derives one from the User-Agent otherwise.49    ///   - stepUpIfNeeded: when the server asks for a fresh verification (`reauth_required`), run `stepUp()` once50    ///     and try again instead of throwing.51    @discardableResult52    public func addPasskey(label: String? = nil, stepUpIfNeeded: Bool = true) async throws -> PasskeyAdded {53        let options: PasskeyCreationOptions54        do {55            options = try await api.passkeyRegistrationOptions()56        } catch let error as APIError where error.needsReauth && stepUpIfNeeded {57            try await stepUp()58            options = try await api.passkeyRegistrationOptions()59        }60        let credential = try await authorizer.registration(for: options)61        return try await api.passkeyRegistrationVerify(credential, label: label)62    }6364    /// Runs an operation that needs a fresh verification; on `reauth_required` performs a step-up and runs it once more.65    public func withFreshSession<T: Sendable>(_ operation: @Sendable () async throws -> T) async throws -> T {66        do {67            return try await operation()68        } catch let error as APIError where error.needsReauth {69            try await stepUp()70            return try await operation()71        }72    }7374    /// Sign-out: asks the server to revoke the session (best effort: offline is not an obstacle), then forgets the75    /// token on the device in every case.76    public func signOut() async {77        if await api.client.hasSession { _ = try? await api.logout() }78        await api.client.clearSession()79    }80}81
Files main
Menu

Theme