Repository Public
1import AuthenticationServices2import Foundation34/// Passkeys through the system (iCloud Keychain, Touch ID / Face ID). The relying party is the web5/// application's domain, so the same passkey signs in on the web and in the apps.6@MainActor7final class Passkey: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {8 private var continuation: CheckedContinuation<ASAuthorization, Error>?9 private let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: Config.rpID)1011 private func perform(_ request: ASAuthorizationRequest) async throws -> ASAuthorization {12 try await withCheckedThrowingContinuation { c in13 continuation = c14 let controller = ASAuthorizationController(authorizationRequests: [request])15 controller.delegate = self16 controller.presentationContextProvider = self17 controller.performRequests()18 }19 }20 func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {21 continuation?.resume(returning: authorization); continuation = nil22 }23 func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {24 continuation?.resume(throwing: error); continuation = nil25 }26 func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {27 #if os(macOS)28 return NSApp.keyWindow ?? NSApp.windows.first ?? ASPresentationAnchor()29 #else30 let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first31 return scene?.keyWindow ?? ASPresentationAnchor()32 #endif33 }3435 /// Returns the WebAuthn assertion in the JSON shape the server verifies.36 func assert(options: [String: Any]) async throws -> [String: Any] {37 guard let ch = (options["challenge"] as? String).flatMap(Data.init(base64URL:)) else { throw APIError(status: 0, code: "bad_options", message: "Invalid sign-in options") }38 let req = provider.createCredentialAssertionRequest(challenge: ch)39 req.userVerificationPreference = .required40 guard let a = try await perform(req).credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion else { throw APIError(status: 0, code: "no_credential", message: "No passkey was returned") }41 let id = a.credentialID.base64URL42 return ["id": id, "rawId": id, "type": "public-key", "authenticatorAttachment": "platform", "clientExtensionResults": [String: Any](),43 "response": ["clientDataJSON": a.rawClientDataJSON.base64URL, "authenticatorData": a.rawAuthenticatorData.base64URL,44 "signature": a.signature.base64URL, "userHandle": a.userID.base64URL]]45 }4647 /// Creates a passkey for a new account (invitation or administrator set-up link).48 func register(options: [String: Any]) async throws -> [String: Any] {49 guard let ch = (options["challenge"] as? String).flatMap(Data.init(base64URL:)), let user = options["user"] as? [String: Any],50 let uid = (user["id"] as? String).flatMap(Data.init(base64URL:)), let name = user["name"] as? String51 else { throw APIError(status: 0, code: "bad_options", message: "Invalid registration options") }52 let req = provider.createCredentialRegistrationRequest(challenge: ch, name: name, userID: uid)53 req.userVerificationPreference = .required54 guard let r = try await perform(req).credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration, let att = r.rawAttestationObject55 else { throw APIError(status: 0, code: "no_credential", message: "No passkey was created") }56 let id = r.credentialID.base64URL57 return ["id": id, "rawId": id, "type": "public-key", "authenticatorAttachment": "platform", "clientExtensionResults": [String: Any](),58 "response": ["clientDataJSON": r.rawClientDataJSON.base64URL, "attestationObject": att.base64URL, "transports": ["internal", "hybrid"]]]59 }60}6162extension Data {63 init?(base64URL s: String) {64 var t = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")65 while t.count % 4 != 0 { t += "=" }66 self.init(base64Encoded: t)67 }68 var base64URL: String {69 base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")70 }71}72