Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Auth/SystemPasskeyAuthenticator.swift3// Description: Passkey ceremonies through AuthenticationServices (Touch ID, iCloud Keychain, a nearby iPhone). The app never sees biometric data or private keys.4import AppKit5import AuthenticationServices6import VQuantCore78/// System implementation of `PasskeyAuthenticator`. Requires the `webcredentials:vquant.spboucher.ai` associated9/// domain and the server's apple-app-site-association file; macOS shows its own sheet and verifies the user.10nonisolated final class SystemPasskeyAuthenticator: PasskeyAuthenticator, Sendable {11 func assert(_ request: AssertionRequest) async throws -> PasskeyAssertion {12 try await PasskeyCeremony.run { ceremony in13 let r = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: request.rpId).createCredentialAssertionRequest(challenge: request.challenge)14 r.userVerificationPreference = .required15 r.allowedCredentials = request.allowCredentials.map { ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0) }16 ceremony.start([r])17 } map: { credential in18 guard let a = credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion else { throw AuthError(.refused, "Unexpected kind of passkey.") }19 return PasskeyAssertion(credentialId: a.credentialID, clientDataJSON: a.rawClientDataJSON, authenticatorData: a.rawAuthenticatorData, signature: a.signature, userHandle: a.userID)20 }21 }2223 func register(_ request: RegistrationRequest) async throws -> PasskeyRegistration {24 try await PasskeyCeremony.run { ceremony in25 let r = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: request.rpId).createCredentialRegistrationRequest(challenge: request.challenge, name: request.userName, userID: request.userId)26 r.userVerificationPreference = .required27 r.excludedCredentials = request.excludeCredentials.map { ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0) }28 ceremony.start([r])29 } map: { credential in30 guard let c = credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration, let att = c.rawAttestationObject else { throw AuthError(.refused, "The device did not return an attestation.") }31 return PasskeyRegistration(credentialId: c.credentialID, clientDataJSON: c.rawClientDataJSON, attestationObject: att)32 }33 }34}3536/// One ASAuthorizationController round trip, bridged to async/await.37private final class PasskeyCeremony: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {38 private var continuation: CheckedContinuation<ASAuthorizationCredential, Error>?39 private var controller: ASAuthorizationController?40 private static var active: PasskeyCeremony?4142 static func run<T: Sendable>(_ configure: @MainActor (PasskeyCeremony) -> Void, map: @MainActor (ASAuthorizationCredential) throws -> T) async throws -> T {43 if active != nil { throw AuthError(.cancelled, "A verification is already in progress.") }44 let ceremony = PasskeyCeremony(); active = ceremony45 defer { active = nil }46 let credential = try await withCheckedThrowingContinuation { (c: CheckedContinuation<ASAuthorizationCredential, Error>) in47 ceremony.continuation = c48 configure(ceremony)49 }50 return try map(credential)51 }5253 func start(_ requests: [ASAuthorizationRequest]) {54 let c = ASAuthorizationController(authorizationRequests: requests)55 c.delegate = self; c.presentationContextProvider = self56 controller = c57 c.performRequests()58 }5960 func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {61 NSApp.keyWindow ?? NSApp.mainWindow ?? NSApp.windows.first { $0.isVisible } ?? ASPresentationAnchor()62 }6364 func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {65 continuation?.resume(returning: authorization.credential); continuation = nil66 }6768 func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {69 continuation?.resume(throwing: Self.explain(error)); continuation = nil70 }7172 static func explain(_ error: Error) -> AuthError {73 let ns = error as NSError74 // diagnostic only: error domain, code and reason — never credentials or challenges75 NSLog("VQuant passkey error: domain=%@ code=%ld reason=%@", ns.domain, ns.code, (ns.userInfo[NSLocalizedFailureReasonErrorKey] as? String) ?? ns.localizedDescription)76 let detail = (ns.userInfo[NSLocalizedFailureReasonErrorKey] as? String ?? ns.localizedDescription).lowercased()77 if detail.contains("not associated with domain") || detail.contains("associated domain") || detail.contains("application identifier") || detail.contains("webcredentials") {78 return AuthError(.notAssociated, "macOS has not (yet) confirmed that this application may use the passkeys of vquant.spboucher.ai. Check the Internet connection and try again in a few minutes. Development builds cannot use passkeys.")79 }80 guard let e = error as? ASAuthorizationError else { return AuthError(.refused, "The verification did not complete.") }81 switch e.code {82 case .canceled: return AuthError(.cancelled, "Verification cancelled.")83 case .notInteractive: return AuthError(.cancelled, "The verification needs an active window.")84 case .matchedExcludedCredential: return AuthError(.refused, "This Mac already holds a passkey for this account. Use “Sign in with a passkey”.")85 default: return AuthError(.refused, "The verification did not complete. Check that Touch ID or iCloud Keychain is available.")86 }87 }88}89