SPB Git

Repository Public

SystemPasskeyAuthorizer.swift 5.0 KB 81 lines swift

1import AuthenticationServices2import Foundation34/// Passkey ceremonies through the system authenticator: Touch ID on Mac, Face ID / Touch ID on iPhone and iPad,5/// or the device passcode where the system allows it. The app never sees biometric data — only the signed result.6struct SystemPasskeyAuthorizer: PasskeyAuthorizer {7    /// The window the system sheet is attached to.8    let anchor: @MainActor @Sendable () -> ASPresentationAnchor?910    func register(challenge: Data, relyingParty: String, userID: Data, userName: String) async throws -> PasskeyRegistration {11        let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: relyingParty)12        let request = provider.createCredentialRegistrationRequest(challenge: challenge, name: userName, userID: userID)13        request.userVerificationPreference = .required14        let authorization = try await PasskeyCeremony.run(request: request, anchor: anchor)15        guard let credential = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration,16              let attestation = credential.rawAttestationObject else { throw PasskeyError.failed(L("The system did not return a passkey.")) }17        return PasskeyRegistration(credentialID: credential.credentialID, clientDataJSON: credential.rawClientDataJSON, attestationObject: attestation)18    }1920    func assert(challenge: Data, relyingParty: String, allowedCredentials: [Data]) async throws -> PasskeyAssertion {21        let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: relyingParty)22        let request = provider.createCredentialAssertionRequest(challenge: challenge)23        request.userVerificationPreference = .required24        if !allowedCredentials.isEmpty { request.allowedCredentials = allowedCredentials.map(ASAuthorizationPlatformPublicKeyCredentialDescriptor.init(credentialID:)) }25        let authorization = try await PasskeyCeremony.run(request: request, anchor: anchor)26        guard let credential = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion else {27            throw PasskeyError.failed(L("The system did not return a passkey."))28        }29        return PasskeyAssertion(credentialID: credential.credentialID, clientDataJSON: credential.rawClientDataJSON,30                                authenticatorData: credential.rawAuthenticatorData, signature: credential.signature, userHandle: credential.userID)31    }32}3334/// One authorization request and its delegate callbacks, bridged to async/await.35@MainActor36private final class PasskeyCeremony: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {37    private var continuation: CheckedContinuation<ASAuthorization, Error>?38    private let window: ASPresentationAnchor39    private var controller: ASAuthorizationController?40    private static var active: Set<PasskeyCeremony> = []4142    private init(window: ASPresentationAnchor) { self.window = window }4344    static func run(request: ASAuthorizationRequest, anchor: @MainActor @Sendable () -> ASPresentationAnchor?) async throws -> ASAuthorization {45        guard let window = anchor() else { throw PasskeyError.notAvailable }46        let ceremony = PasskeyCeremony(window: window)47        active.insert(ceremony)48        defer { active.remove(ceremony) }49        return try await withCheckedThrowingContinuation { continuation in50            ceremony.continuation = continuation51            let controller = ASAuthorizationController(authorizationRequests: [request])52            controller.delegate = ceremony53            controller.presentationContextProvider = ceremony54            ceremony.controller = controller55            controller.performRequests()56        }57    }5859    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor { window }6061    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {62        continuation?.resume(returning: authorization)63        continuation = nil64    }6566    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {67        let ns = error as NSError68        let mapped: PasskeyError69        if ns.domain == ASAuthorizationError.errorDomain, ns.code == ASAuthorizationError.canceled.rawValue {70            // The same code is used when no passkey exists for this site on the device.71            mapped = ns.localizedDescription.localizedCaseInsensitiveContains("no credentials") ? .failed(L("No passkey for SP Browser was found on this device.")) : .cancelled72        } else if ns.localizedDescription.localizedCaseInsensitiveContains("not associated with domain") {73            mapped = .failed(L("This copy of SP Browser is not yet linked to the SP Browser service. Install the released app in Applications and try again in a few minutes."))74        } else {75            mapped = .failed(ns.localizedDescription)76        }77        continuation?.resume(throwing: mapped)78        continuation = nil79    }80}81
Files main
Menu

Theme