Repository Public
1// SP Notes Core2// File: Sources/SPNotesAPI/PasskeyAuthorizer.swift3// Description: The device half of the passkey ceremonies: a protocol the apps (and tests) can replace, and the default4// implementation that drives ASAuthorizationController for platform passkeys.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import AuthenticationServices9import Foundation1011/// Runs the system passkey sheet. The private key never leaves the Secure Enclave / the passkey provider: the app12/// only receives a signed answer to forward to the server.13@MainActor14public protocol PasskeyAuthorizing: AnyObject, Sendable {15 /// Asks the person to verify with an existing passkey (sign-in, step-up).16 func assertion(for options: PasskeyRequestOptions) async throws -> PasskeyAssertionCredential17 /// Creates a platform passkey on this device.18 func registration(for options: PasskeyCreationOptions) async throws -> PasskeyRegistrationCredential19}2021/// `PasskeyAuthorizing` on top of `ASAuthorizationController` (platform passkeys: this device, iCloud Keychain or a22/// third-party provider, and nearby devices through the system sheet).23@MainActor24public final class SystemPasskeyAuthorizer: NSObject, PasskeyAuthorizing {25 private enum Outcome: Sendable {26 case assertion(PasskeyAssertionCredential)27 case registration(PasskeyRegistrationCredential)28 }2930 private let anchor: @MainActor () -> ASPresentationAnchor31 private let fallbackRelyingParty: String?32 private let preferImmediatelyAvailableCredentials: Bool33 private var continuation: CheckedContinuation<Outcome, Error>?34 private var controller: ASAuthorizationController?3536 /// - Parameters:37 /// - fallbackRelyingParty: used when the server options carry no `rpId` (`APIConfiguration.relyingPartyID`).38 /// - preferImmediatelyAvailableCredentials: iOS only — fail with `PasskeyError.noCredentials` instead of39 /// offering a nearby device when this device holds no passkey (useful for a silent attempt at launch).40 /// - anchor: the window the system sheet is attached to.41 public init(fallbackRelyingParty: String? = nil, preferImmediatelyAvailableCredentials: Bool = false, anchor: @escaping @MainActor () -> ASPresentationAnchor) {42 self.anchor = anchor43 self.fallbackRelyingParty = fallbackRelyingParty44 self.preferImmediatelyAvailableCredentials = preferImmediatelyAvailableCredentials45 }4647 public func assertion(for options: PasskeyRequestOptions) async throws -> PasskeyAssertionCredential {48 guard let relyingParty = options.rpId ?? fallbackRelyingParty, !relyingParty.isEmpty else { throw PasskeyError.invalidOptions("no relying party id") }49 guard !options.challenge.isEmpty else { throw PasskeyError.invalidOptions("empty challenge") }50 let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: relyingParty)51 let request = provider.createCredentialAssertionRequest(challenge: options.challenge)52 request.userVerificationPreference = .required53 if !options.allowCredentials.isEmpty {54 request.allowedCredentials = options.allowCredentials.map { ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0.id) }55 }56 guard case .assertion(let credential) = try await perform(request, immediate: preferImmediatelyAvailableCredentials) else {57 throw PasskeyError.failed(code: 0, message: "Unexpected credential type.")58 }59 return credential60 }6162 public func registration(for options: PasskeyCreationOptions) async throws -> PasskeyRegistrationCredential {63 guard let relyingParty = options.rp.id ?? fallbackRelyingParty, !relyingParty.isEmpty else { throw PasskeyError.invalidOptions("no relying party id") }64 guard !options.challenge.isEmpty, !options.user.id.isEmpty else { throw PasskeyError.invalidOptions("empty challenge or user id") }65 let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: relyingParty)66 let request = provider.createCredentialRegistrationRequest(challenge: options.challenge, name: options.user.name, userID: options.user.id)67 request.userVerificationPreference = .required68 if let displayName = options.user.displayName { request.displayName = displayName }69 if !options.excludeCredentials.isEmpty {70 request.excludedCredentials = options.excludeCredentials.map { ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0.id) }71 }72 guard case .registration(let credential) = try await perform(request, immediate: false) else {73 throw PasskeyError.failed(code: 0, message: "Unexpected credential type.")74 }75 return credential76 }7778 // MARK: ASAuthorizationController bridge7980 private func perform(_ request: ASAuthorizationRequest, immediate: Bool) async throws -> Outcome {81 guard continuation == nil else { throw PasskeyError.inProgress }82 let controller = ASAuthorizationController(authorizationRequests: [request])83 controller.delegate = self84 controller.presentationContextProvider = self85 self.controller = controller86 return try await withTaskCancellationHandler {87 try await withCheckedThrowingContinuation { (c: CheckedContinuation<Outcome, Error>) in88 continuation = c89 if Task.isCancelled {90 finish(.failure(PasskeyError.cancelled))91 return92 }93 #if os(iOS)94 if immediate {95 controller.performRequests(options: .preferImmediatelyAvailableCredentials)96 } else {97 controller.performRequests()98 }99 #else100 controller.performRequests()101 #endif102 }103 } onCancel: {104 Task { @MainActor [weak self] in self?.controller?.cancel() }105 }106 }107108 private func finish(_ result: Result<Outcome, Error>) {109 let c = continuation110 continuation = nil111 controller = nil112 c?.resume(with: result.mapError { PasskeyError.from($0) })113 }114}115116extension SystemPasskeyAuthorizer: ASAuthorizationControllerDelegate {117 public func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {118 switch authorization.credential {119 case let assertion as ASAuthorizationPlatformPublicKeyCredentialAssertion:120 finish(.success(.assertion(PasskeyCeremony.assertionCredential(from: assertion))))121 case let registration as ASAuthorizationPlatformPublicKeyCredentialRegistration:122 finish(Result { .registration(try PasskeyCeremony.registrationCredential(from: registration)) })123 default:124 finish(.failure(PasskeyError.failed(code: 0, message: "Unexpected credential type.")))125 }126 }127128 public func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {129 finish(.failure(error))130 }131}132133extension SystemPasskeyAuthorizer: ASAuthorizationControllerPresentationContextProviding {134 public func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {135 anchor()136 }137}138