Jobley / app · jobley.ai / Sources / JobleyUI / PasskeyAuthorizer.swift
| 1 | import AuthenticationServices |
| 2 | import JobleyKit |
| 3 | #if os(macOS) |
| 4 | import AppKit |
| 5 | #else |
| 6 | import UIKit |
| 7 | #endif |
| 8 | |
| 9 | /// Asks the system for a passkey: sign in with one (assertion) or make a new one (registration). |
| 10 | /// The apps' `webcredentials:jobley.ai` associated domain lets them use jobley.ai passkeys. |
| 11 | @MainActor |
| 12 | final class PasskeyAuthorizer: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding { |
| 13 | private var continuation: CheckedContinuation<ASAuthorization, Error>? |
| 14 | private var controller: ASAuthorizationController? |
| 15 | |
| 16 | /// The WebAuthn assertion JSON for `challenge`, from a passkey the person picks. |
| 17 | func signIn(_ challenge: PasskeyChallenge) async throws -> [String: Any] { |
| 18 | guard let bytes = challenge.challenge else { throw PasskeyError.badReply } |
| 19 | let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: challenge.relyingParty) |
| 20 | let request = provider.createCredentialAssertionRequest(challenge: bytes) |
| 21 | request.userVerificationPreference = .required |
| 22 | let authorization = try await perform(request) |
| 23 | guard let credential = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion else { throw PasskeyError.badReply } |
| 24 | return PasskeyResponse.assertion(credentialID: credential.credentialID, clientDataJSON: credential.rawClientDataJSON, |
| 25 | authenticatorData: credential.rawAuthenticatorData, signature: credential.signature, userID: credential.userID) |
| 26 | } |
| 27 | |
| 28 | /// The WebAuthn registration JSON for `challenge`: a new passkey for the person it names. |
| 29 | func register(_ challenge: PasskeyChallenge) async throws -> [String: Any] { |
| 30 | guard let bytes = challenge.challenge, let userID = challenge.userID, let user = challenge.options.user else { throw PasskeyError.badReply } |
| 31 | let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: challenge.relyingParty) |
| 32 | let request = provider.createCredentialRegistrationRequest(challenge: bytes, name: user.name, userID: userID) |
| 33 | request.userVerificationPreference = .required |
| 34 | request.excludedCredentials = challenge.excludedCredentialIDs.map { ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0) } |
| 35 | let authorization = try await perform(request) |
| 36 | guard let credential = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration, |
| 37 | let attestation = credential.rawAttestationObject else { throw PasskeyError.badReply } |
| 38 | return PasskeyResponse.registration(credentialID: credential.credentialID, clientDataJSON: credential.rawClientDataJSON, attestationObject: attestation) |
| 39 | } |
| 40 | |
| 41 | private func perform(_ request: ASAuthorizationRequest) async throws -> ASAuthorization { |
| 42 | try await withCheckedThrowingContinuation { continuation in |
| 43 | self.continuation = continuation |
| 44 | let controller = ASAuthorizationController(authorizationRequests: [request]) |
| 45 | controller.delegate = self |
| 46 | controller.presentationContextProvider = self |
| 47 | self.controller = controller |
| 48 | controller.performRequests() |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | nonisolated func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) { |
| 53 | MainActor.assumeIsolated { finish(.success(authorization)) } |
| 54 | } |
| 55 | |
| 56 | nonisolated func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) { |
| 57 | MainActor.assumeIsolated { |
| 58 | let cancelled = (error as? ASAuthorizationError)?.code == .canceled |
| 59 | finish(.failure(cancelled ? PasskeyError.cancelled : error)) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | private func finish(_ result: Result<ASAuthorization, Error>) { |
| 64 | continuation?.resume(with: result) |
| 65 | continuation = nil |
| 66 | controller = nil |
| 67 | } |
| 68 | |
| 69 | nonisolated func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor { |
| 70 | MainActor.assumeIsolated { |
| 71 | #if os(macOS) |
| 72 | return NSApplication.shared.keyWindow ?? NSApplication.shared.windows.first ?? ASPresentationAnchor() |
| 73 | #else |
| 74 | let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } |
| 75 | return scenes.flatMap(\.windows).first(where: \.isKeyWindow) ?? scenes.first?.windows.first ?? ASPresentationAnchor() |
| 76 | #endif |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | /// What this device is called, so a person can tell their passkeys apart. |
| 81 | static var deviceName: String { |
| 82 | #if os(macOS) |
| 83 | return Host.current().localizedName ?? "Mac" |
| 84 | #else |
| 85 | return UIDevice.current.name |
| 86 | #endif |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | enum PasskeyError: Error, LocalizedError { |
| 91 | case cancelled, badReply, badLink |
| 92 | |
| 93 | var errorDescription: String? { |
| 94 | switch self { |
| 95 | case .cancelled: "Passkey sign-in was cancelled." |
| 96 | case .badReply: "The passkey reply couldn't be read. Please try again." |
| 97 | case .badLink: "That doesn't look like a Jobley setup link. Paste the whole link you were given." |
| 98 | } |
| 99 | } |
| 100 | } |