import AuthenticationServices import JobleyKit #if os(macOS) import AppKit #else import UIKit #endif /// Asks the system for a passkey: sign in with one (assertion) or make a new one (registration). /// The apps' `webcredentials:jobley.ai` associated domain lets them use jobley.ai passkeys. @MainActor final class PasskeyAuthorizer: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding { private var continuation: CheckedContinuation? private var controller: ASAuthorizationController? /// The WebAuthn assertion JSON for `challenge`, from a passkey the person picks. func signIn(_ challenge: PasskeyChallenge) async throws -> [String: Any] { guard let bytes = challenge.challenge else { throw PasskeyError.badReply } let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: challenge.relyingParty) let request = provider.createCredentialAssertionRequest(challenge: bytes) request.userVerificationPreference = .required let authorization = try await perform(request) guard let credential = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion else { throw PasskeyError.badReply } return PasskeyResponse.assertion(credentialID: credential.credentialID, clientDataJSON: credential.rawClientDataJSON, authenticatorData: credential.rawAuthenticatorData, signature: credential.signature, userID: credential.userID) } /// The WebAuthn registration JSON for `challenge`: a new passkey for the person it names. func register(_ challenge: PasskeyChallenge) async throws -> [String: Any] { guard let bytes = challenge.challenge, let userID = challenge.userID, let user = challenge.options.user else { throw PasskeyError.badReply } let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: challenge.relyingParty) let request = provider.createCredentialRegistrationRequest(challenge: bytes, name: user.name, userID: userID) request.userVerificationPreference = .required request.excludedCredentials = challenge.excludedCredentialIDs.map { ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0) } let authorization = try await perform(request) guard let credential = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration, let attestation = credential.rawAttestationObject else { throw PasskeyError.badReply } return PasskeyResponse.registration(credentialID: credential.credentialID, clientDataJSON: credential.rawClientDataJSON, attestationObject: attestation) } private func perform(_ request: ASAuthorizationRequest) async throws -> ASAuthorization { try await withCheckedThrowingContinuation { continuation in self.continuation = continuation let controller = ASAuthorizationController(authorizationRequests: [request]) controller.delegate = self controller.presentationContextProvider = self self.controller = controller controller.performRequests() } } nonisolated func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) { MainActor.assumeIsolated { finish(.success(authorization)) } } nonisolated func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) { MainActor.assumeIsolated { let cancelled = (error as? ASAuthorizationError)?.code == .canceled finish(.failure(cancelled ? PasskeyError.cancelled : error)) } } private func finish(_ result: Result) { continuation?.resume(with: result) continuation = nil controller = nil } nonisolated func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor { MainActor.assumeIsolated { #if os(macOS) return NSApplication.shared.keyWindow ?? NSApplication.shared.windows.first ?? ASPresentationAnchor() #else let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } return scenes.flatMap(\.windows).first(where: \.isKeyWindow) ?? scenes.first?.windows.first ?? ASPresentationAnchor() #endif } } /// What this device is called, so a person can tell their passkeys apart. static var deviceName: String { #if os(macOS) return Host.current().localizedName ?? "Mac" #else return UIDevice.current.name #endif } } enum PasskeyError: Error, LocalizedError { case cancelled, badReply, badLink var errorDescription: String? { switch self { case .cancelled: "Passkey sign-in was cancelled." case .badReply: "The passkey reply couldn't be read. Please try again." case .badLink: "That doesn't look like a Jobley setup link. Paste the whole link you were given." } } }