SPB Git

Repository Public

PlatformPasskeyProvider.swift 6.0 KB 114 lines swift

1import AuthenticationServices2import Foundation34/// System passkeys through AuthenticationServices (iCloud Keychain / platform authenticator).5/// The relying party is the product domain; the app must carry the Associated Domains entitlement6/// `webcredentials:<relying party>` and the domain must publish the matching apple-app-site-association.7@MainActor8public final class PlatformPasskeyProvider: NSObject, PasskeyProvider {9    public typealias AnchorProvider = @MainActor () -> ASPresentationAnchor?1011    private let relyingPartyID: String12    private let anchor: AnchorProvider13    private var active: Ceremony?1415    public init(relyingPartyID: String = "clustr.spboucher.ai", anchor: @escaping AnchorProvider) {16        self.relyingPartyID = relyingPartyID17        self.anchor = anchor18    }1920    public func assertion(_ request: PasskeyAssertionRequest) async throws -> PasskeyAssertion {21        guard request.relyingPartyID == relyingPartyID else { throw PasskeyError.invalidOptions("unexpected rpId \(request.relyingPartyID)") }22        let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: relyingPartyID)23        let r = provider.createCredentialAssertionRequest(challenge: request.challenge)24        r.userVerificationPreference = .init(rawValue: request.userVerification)25        if !request.allowedCredentialIDs.isEmpty {26            r.allowedCredentials = request.allowedCredentialIDs.map(ASAuthorizationPlatformPublicKeyCredentialDescriptor.init(credentialID:))27        }28        let authorization = try await perform(r)29        guard let c = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion else {30            throw PasskeyError.failed(code: -1, message: "Unexpected credential type")31        }32        return PasskeyAssertion(credentialID: c.credentialID, clientDataJSON: c.rawClientDataJSON,33                                authenticatorData: c.rawAuthenticatorData, signature: c.signature,34                                userHandle: c.userID, attachment: "platform")35    }3637    public func registration(_ request: PasskeyRegistrationRequest) async throws -> PasskeyRegistration {38        guard request.relyingPartyID == relyingPartyID else { throw PasskeyError.invalidOptions("unexpected rp.id \(request.relyingPartyID)") }39        let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: relyingPartyID)40        let r = provider.createCredentialRegistrationRequest(challenge: request.challenge, name: request.userName, userID: request.userID)41        r.displayName = request.userDisplayName42        r.userVerificationPreference = .init(rawValue: request.userVerification)43        r.attestationPreference = .init(rawValue: request.attestation)44        if #available(macOS 14.4, iOS 17.4, *), !request.excludedCredentialIDs.isEmpty {45            r.excludedCredentials = request.excludedCredentialIDs.map(ASAuthorizationPlatformPublicKeyCredentialDescriptor.init(credentialID:))46        }47        let authorization = try await perform(r)48        guard let c = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration,49              let attestation = c.rawAttestationObject else {50            throw PasskeyError.failed(code: -1, message: "Unexpected credential type")51        }52        return PasskeyRegistration(credentialID: c.credentialID, clientDataJSON: c.rawClientDataJSON,53                                   attestationObject: attestation, transports: ["internal", "hybrid"], attachment: "platform")54    }5556    private func perform(_ request: ASAuthorizationRequest) async throws -> ASAuthorization {57        if active != nil { throw PasskeyError.failed(code: -2, message: "Another passkey ceremony is in progress") }58        let ceremony = Ceremony(controller: ASAuthorizationController(authorizationRequests: [request]), anchor: anchor())59        active = ceremony60        defer { active = nil }61        return try await withTaskCancellationHandler {62            try await ceremony.run()63        } onCancel: {64            Task { @MainActor in ceremony.cancel() }65        }66    }6768    @MainActor69    private final class Ceremony: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {70        let controller: ASAuthorizationController71        let anchorWindow: ASPresentationAnchor?72        var continuation: CheckedContinuation<ASAuthorization, Error>?7374        init(controller: ASAuthorizationController, anchor: ASPresentationAnchor?) {75            self.controller = controller76            self.anchorWindow = anchor77        }7879        func run() async throws -> ASAuthorization {80            try await withCheckedThrowingContinuation { cont in81                continuation = cont82                controller.delegate = self83                controller.presentationContextProvider = self84                controller.performRequests()85            }86        }8788        func cancel() { controller.cancel() }8990        func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {91            anchorWindow ?? ASPresentationAnchor()92        }9394        func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {95            continuation?.resume(returning: authorization)96            continuation = nil97        }9899        func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {100            let ns = error as NSError101            let mapped: PasskeyError102            if ns.domain == ASAuthorizationError.errorDomain, ns.code == ASAuthorizationError.canceled.rawValue {103                mapped = .cancelled104            } else {105                // 1004 (failed) is what the system returns when the Associated Domains association is missing or the106                // app runs from a location the system daemon cannot read; keep the code for diagnostics.107                mapped = .failed(code: ns.code, message: ns.localizedDescription)108            }109            continuation?.resume(throwing: mapped)110            continuation = nil111        }112    }113}114
Files main
Menu

Theme