Repository Public
1// SP Wallet iOS2// File: Core/Authentication/PlatformPasskeyAuthenticator.swift3// Description: The device's passkeys through AuthenticationServices (iCloud Keychain / a nearby device). The system sheet performs4// Face ID / Touch ID itself and returns a WebAuthn assertion: that signed assertion — not a local biometric5// success — is what the server and the isolated signer verify.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import AuthenticationServices10import SPWalletCore11import UIKit1213@MainActor14final class PlatformPasskeyAuthenticator: NSObject, PasskeyAuthenticator, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {15 private var continuation: CheckedContinuation<ASAuthorization, Error>?16 private var controller: ASAuthorizationController?1718 func assert(_ options: PasskeyRequestOptions, rpId: String) async throws -> PasskeyAssertion {19 guard let challenge = options.challengeData else { throw PasskeyError.failed("bad challenge") }20 let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: rpId)21 let request = provider.createCredentialAssertionRequest(challenge: challenge)22 request.userVerificationPreference = .required23 if let allow = options.allowCredentials, !allow.isEmpty {24 request.allowedCredentials = allow.compactMap { $0.idData }.map { ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0) }25 }26 let auth = try await perform(request)27 guard let c = auth.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion else { throw PasskeyError.failed("unexpected credential type") }28 return PasskeyAssertion(credentialId: c.credentialID, clientDataJSON: c.rawClientDataJSON, authenticatorData: c.rawAuthenticatorData,29 signature: c.signature, userHandle: c.userID, attachment: c.attachment == .crossPlatform ? "cross-platform" : "platform")30 }3132 func register(_ options: PasskeyCreationOptions, rpId: String) async throws -> PasskeyRegistration {33 guard let challenge = options.challengeData, let userId = options.userIdData else { throw PasskeyError.failed("bad registration options") }34 let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: rpId)35 let request = provider.createCredentialRegistrationRequest(challenge: challenge, name: options.user.name, userID: userId)36 request.userVerificationPreference = .required37 request.displayName = options.user.displayName38 if let exclude = options.excludeCredentials {39 request.excludedCredentials = exclude.compactMap { $0.idData }.map { ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0) }40 }41 let auth = try await perform(request)42 guard let c = auth.credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration, let att = c.rawAttestationObject else { throw PasskeyError.failed("unexpected credential type") }43 return PasskeyRegistration(credentialId: c.credentialID, clientDataJSON: c.rawClientDataJSON, attestationObject: att)44 }4546 private func perform(_ request: ASAuthorizationRequest) async throws -> ASAuthorization {47 guard continuation == nil else { throw PasskeyError.failed("another passkey request is in progress") }48 let c = ASAuthorizationController(authorizationRequests: [request])49 c.delegate = self50 c.presentationContextProvider = self51 controller = c52 return try await withCheckedThrowingContinuation { k in53 continuation = k54 c.performRequests()55 }56 }5758 private func finish(_ result: Result<ASAuthorization, Error>) {59 let k = continuation60 continuation = nil; controller = nil61 k?.resume(with: result)62 }6364 nonisolated func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {65 nonisolated(unsafe) let a = authorization66 Task { @MainActor in self.finish(.success(a)) }67 }6869 nonisolated func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {70 let mapped = Self.map(error)71 Task { @MainActor in self.finish(.failure(mapped)) }72 }7374 nonisolated static func map(_ error: Error) -> PasskeyError {75 let ns = error as NSError76 guard ns.domain == ASAuthorizationError.errorDomain, let code = ASAuthorizationError.Code(rawValue: ns.code) else { return .failed(ns.localizedDescription) }77 switch code {78 case .canceled: return .cancelled79 case .notInteractive, .notHandled: return .notAvailable(ns.localizedDescription)80 case .failed:81 // 1004 with "not associated with domain": the associated domain has not been validated on this device yet82 return ns.localizedDescription.localizedCaseInsensitiveContains("associated") ? .notAvailable(ns.localizedDescription) : .failed(ns.localizedDescription)83 default: return .failed(ns.localizedDescription)84 }85 }8687 func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {88 let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }89 let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first90 return scene?.keyWindow ?? ASPresentationAnchor()91 }92}93