Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Claude Remote / Codex Remote9// File : Packages/ClaudeRemoteKit/Sources/ClaudeRemoteAuth/Passkeys.swift10// Module : ClaudeRemoteAuth11// Repository : https://git.spboucher.ai/claude-remote-apple12// Project Website : https://claude.spboucher.ai13// Created : 2026-11-2914// Last Modified : 2026-11-2915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import AuthenticationServices89import ClaudeRemoteModels90import Foundation9192public struct PasskeyError: Error, Hashable, Sendable, LocalizedError {93 public enum Reason: Hashable, Sendable {94 /// The user dismissed the system sheet.95 case cancelled96 /// The app is not (yet) associated with the domain: missing `webcredentials:` entitlement97 /// or the apple-app-site-association file was not fetched by the system.98 case notAssociated99 /// Another ceremony is already on screen.100 case busy101 /// No window to present from.102 case notInteractive103 /// A passkey for this account already exists on this device (registration).104 case alreadyRegistered105 case failed106 }107 public var reason: Reason108 public var message: String109 public init(_ reason: Reason, _ message: String) {110 self.reason = reason111 self.message = message112 }113 public var errorDescription: String? { message }114}115116/// A WebAuthn authenticator. The system implementation shows Touch ID / Face ID through117/// AuthenticationServices; tests use `SoftwareAuthenticator` (ClaudeRemoteTestSupport).118public protocol PasskeyAuthenticator: Sendable {119 /// Assertion (sign-in). Empty `allowCredentials` = discoverable credentials.120 func assertion(relyingParty: String, challenge: Data, allowCredentials: [Data]) async throws -> PasskeyAssertionCredential121 /// Creation of a new passkey for the signed-in account.122 func registration(relyingParty: String, challenge: Data, userName: String, userID: Data, excludeCredentials: [Data]) async throws -> PasskeyRegistrationCredential123}124125/// Passkeys through `ASAuthorizationPlatformPublicKeyCredentialProvider`: the same passkey as the126/// website (iCloud Keychain or a password manager extension), user verification required.127///128/// Requirements on the app target: Associated Domains `webcredentials:<host>` and the server's129/// apple-app-site-association listing the app id (contract §1).130public final class SystemPasskeyAuthenticator: PasskeyAuthenticator {131 private let anchor: @MainActor @Sendable () -> ASPresentationAnchor?132133 /// - Parameter anchor: the window the system sheet is presented from.134 public init(anchor: @escaping @MainActor @Sendable () -> ASPresentationAnchor?) {135 self.anchor = anchor136 }137138 public func assertion(relyingParty: String, challenge: Data, allowCredentials: [Data]) async throws -> PasskeyAssertionCredential {139 let credential = try await Ceremony.run(anchor: anchor) {140 let request = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: relyingParty)141 .createCredentialAssertionRequest(challenge: challenge)142 request.userVerificationPreference = .required143 request.allowedCredentials = allowCredentials.map { ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0) }144 return [request]145 } map: { authorization -> PasskeyAssertionCredential? in146 guard let a = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion else { return nil }147 return PasskeyAssertionCredential(credentialID: a.credentialID, clientDataJSON: a.rawClientDataJSON,148 authenticatorData: a.rawAuthenticatorData, signature: a.signature, userHandle: a.userID)149 }150 guard let credential else { throw PasskeyError(.failed, "Unexpected passkey type.") }151 return credential152 }153154 public func registration(relyingParty: String, challenge: Data, userName: String, userID: Data, excludeCredentials: [Data]) async throws -> PasskeyRegistrationCredential {155 let credential = try await Ceremony.run(anchor: anchor) {156 let request = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: relyingParty)157 .createCredentialRegistrationRequest(challenge: challenge, name: userName, userID: userID)158 request.userVerificationPreference = .required159 if #available(macOS 14.4, iOS 17.4, *) {160 request.excludedCredentials = excludeCredentials.map { ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0) }161 }162 return [request]163 } map: { authorization -> PasskeyRegistrationCredential? in164 guard let c = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration,165 let attestation = c.rawAttestationObject else { return nil }166 return PasskeyRegistrationCredential(credentialID: c.credentialID, clientDataJSON: c.rawClientDataJSON, attestationObject: attestation)167 }168 guard let credential else { throw PasskeyError(.failed, "The device did not provide an attestation.") }169 return credential170 }171}172173/// One `ASAuthorizationController` round trip bridged to async/await.174@MainActor175private final class Ceremony: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {176 private static var active: Ceremony?177 private var continuation: CheckedContinuation<ASAuthorization, Error>?178 private var controller: ASAuthorizationController?179 private let window: ASPresentationAnchor180181 private init(window: ASPresentationAnchor) { self.window = window }182183 static func run<T: Sendable>(184 anchor: @MainActor @Sendable () -> ASPresentationAnchor?,185 requests: @MainActor () -> [ASAuthorizationRequest],186 map: @MainActor (ASAuthorization) -> T187 ) async throws -> T {188 guard active == nil else { throw PasskeyError(.busy, "A verification is already in progress.") }189 guard let window = anchor() else { throw PasskeyError(.notInteractive, "Verification needs an active window.") }190 let ceremony = Ceremony(window: window)191 active = ceremony192 defer { active = nil }193 let authorization = try await withCheckedThrowingContinuation { (c: CheckedContinuation<ASAuthorization, Error>) in194 ceremony.continuation = c195 let controller = ASAuthorizationController(authorizationRequests: requests())196 controller.delegate = ceremony197 controller.presentationContextProvider = ceremony198 ceremony.controller = controller199 controller.performRequests()200 }201 return map(authorization)202 }203204 func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor { window }205206 func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {207 continuation?.resume(returning: authorization)208 continuation = nil209 }210211 func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {212 continuation?.resume(throwing: Self.explain(error))213 continuation = nil214 }215216 static func explain(_ error: Error) -> PasskeyError {217 let ns = error as NSError218 // Diagnostic only: domain and code. Never challenges or credential material.219 CRAuthLog.logger.error("passkey ceremony failed: \(ns.domain, privacy: .public) \(ns.code, privacy: .public)")220 let detail = ((ns.userInfo[NSLocalizedFailureReasonErrorKey] as? String) ?? ns.localizedDescription).lowercased()221 if detail.contains("associated domain") || detail.contains("not associated") || detail.contains("application identifier") {222 return PasskeyError(.notAssociated, "The system has not validated the association between this app and the passkey domain yet. Check the network and try again in a few minutes.")223 }224 guard let e = error as? ASAuthorizationError else { return PasskeyError(.failed, "The verification did not complete.") }225 switch e.code {226 case .canceled: return PasskeyError(.cancelled, "Verification cancelled.")227 case .notInteractive: return PasskeyError(.notInteractive, "Verification needs an active window.")228 case .matchedExcludedCredential: return PasskeyError(.alreadyRegistered, "This device already has a passkey for this account.")229 default: return PasskeyError(.failed, "The verification did not complete. Check that a passkey for this site is available on this device.")230 }231 }232}233234import os235enum CRAuthLog {236 static let logger = Logger(subsystem: "ai.spboucher.clauderemote.kit", category: "auth")237}238