Cotton code
99 lines · 5.5 KB · SwiftRaw
// The system passkey sheet for a Cotton-account passkey:// AuthenticationServices' platform provider, user verification required, for// the relying party the core's request names. What goes in and comes out is// `CottonKit/AccountPasskeyJSON.swift`'s; this file only raises the sheet and// waits for it. Which provider keeps the passkey (iCloud Keychain, Cotton// Keys, another) is the phone's choice, never this file's.//// The relying party's host must name this app in its// `apple-app-site-association` (`webcredentials`), and the app must carry the// `webcredentials:` associated domain; without both the sheet refuses.#if os(iOS)    import AuthenticationServices    import CottonKit    import UIKit    /// Why the sheet gave nothing back.    enum AccountPasskeyRefusal: Error, Equatable {        /// The person closed the sheet, or the phone holds no passkey for Cotton.        case cancelled        /// The request did not read, or the sheet failed.        case failed    }    @MainActor    final class AccountPasskeySheet: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {        private var waiting: CheckedContinuation<ASAuthorization, Error>?        private var controller: ASAuthorizationController?        /// Sign in: the sheet over every passkey this phone holds for the relying party.        static func signIn(requestJSON: String) async throws(AccountPasskeyRefusal) -> String {            guard let asked = AccountPasskeyJSON.request(requestJSON) else { throw .failed }            let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: asked.rpId)            let request = provider.createCredentialAssertionRequest(challenge: asked.challenge)            request.userVerificationPreference = .required            let got = try await AccountPasskeySheet().run(request)            guard let credential = got.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion else { throw .failed }            return AccountPasskeyJSON.json(AccountPasskeyJSON.Assertion(                credentialId: credential.credentialID, clientDataJSON: credential.rawClientDataJSON,                authenticatorData: credential.rawAuthenticatorData ?? Data(), signature: credential.signature ?? Data(),                userHandle: credential.userID))        }        /// Add: a new passkey for this account, on whichever provider the phone keeps passkeys in.        static func add(requestJSON: String) async throws(AccountPasskeyRefusal) -> String {            guard let asked = AccountPasskeyJSON.creation(requestJSON) else { throw .failed }            let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: asked.rpId)            let request = provider.createCredentialRegistrationRequest(challenge: asked.challenge, name: asked.userName, userID: asked.userId)            request.userVerificationPreference = .required            request.attestationPreference = .none            request.excludedCredentials = asked.exclude.map { ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0) }            let got = try await AccountPasskeySheet().run(request)            guard let credential = got.credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration,                let attestation = credential.rawAttestationObject            else { throw .failed }            return AccountPasskeyJSON.json(AccountPasskeyJSON.Registration(                credentialId: credential.credentialID, clientDataJSON: credential.rawClientDataJSON, attestationObject: attestation))        }        private func run(_ request: ASAuthorizationRequest) async throws(AccountPasskeyRefusal) -> ASAuthorization {            do {                return try await withCheckedThrowingContinuation { continuation in                    waiting = continuation                    let controller = ASAuthorizationController(authorizationRequests: [request])                    controller.delegate = self                    controller.presentationContextProvider = self                    self.controller = controller                    controller.performRequests()                }            } catch let error as ASAuthorizationError where error.code == .canceled {                throw .cancelled            } catch {                Log.write("passkey sheet: \((error as NSError).domain) \((error as NSError).code)")                throw .failed            }        }        nonisolated func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {            MainActor.assumeIsolated { finish(.success(authorization)) }        }        nonisolated func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {            MainActor.assumeIsolated { finish(.failure(error)) }        }        private func finish(_ result: Result<ASAuthorization, Error>) {            waiting?.resume(with: result)            waiting = nil            controller = nil        }        nonisolated func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {            MainActor.assumeIsolated {                let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }                return scenes.flatMap(\.windows).first(where: \.isKeyWindow) ?? scenes.first.map { UIWindow(windowScene: $0) } ?? UIWindow()            }        }    }#endif