Repository Public
1import Foundation23/// Options of an assertion (sign-in or step-up), parsed from the server's `public_key` JSON4/// (`PublicKeyCredentialRequestOptions`, base64url binary fields).5public struct PasskeyAssertionRequest: Sendable, Equatable {6 public var relyingPartyID: String7 public var challenge: Data8 public var allowedCredentialIDs: [Data]9 public var userVerification: String10 public var timeoutMilliseconds: Int?11}1213/// Options of a registration (invitation setup or "add a passkey"), parsed from the server's `public_key` JSON14/// (`PublicKeyCredentialCreationOptions`).15public struct PasskeyRegistrationRequest: Sendable, Equatable {16 public var relyingPartyID: String17 public var relyingPartyName: String18 public var userID: Data19 public var userName: String20 public var userDisplayName: String21 public var challenge: Data22 public var excludedCredentialIDs: [Data]23 public var algorithms: [Int]24 public var userVerification: String25 public var attestation: String26 public var timeoutMilliseconds: Int?27}2829/// Raw result of an assertion ceremony, as produced by an authenticator.30public struct PasskeyAssertion: Sendable, Equatable {31 public var credentialID: Data32 public var clientDataJSON: Data33 public var authenticatorData: Data34 public var signature: Data35 public var userHandle: Data?36 public var attachment: String?37 public init(credentialID: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userHandle: Data?, attachment: String? = "platform") {38 self.credentialID = credentialID; self.clientDataJSON = clientDataJSON; self.authenticatorData = authenticatorData39 self.signature = signature; self.userHandle = userHandle; self.attachment = attachment40 }41}4243/// Raw result of a registration ceremony.44public struct PasskeyRegistration: Sendable, Equatable {45 public var credentialID: Data46 public var clientDataJSON: Data47 public var attestationObject: Data48 public var transports: [String]49 public var attachment: String?50 public init(credentialID: Data, clientDataJSON: Data, attestationObject: Data, transports: [String] = ["internal", "hybrid"], attachment: String? = "platform") {51 self.credentialID = credentialID; self.clientDataJSON = clientDataJSON; self.attestationObject = attestationObject52 self.transports = transports; self.attachment = attachment53 }54}5556public enum PasskeyError: Error, Sendable, Equatable {57 case cancelled58 case noCredential59 case invalidOptions(String)60 case failed(code: Int, message: String)6162 public var apiError: APIError {63 switch self {64 case .cancelled: return APIError(code: APIError.codePasskeyCancelled, message: "Passkey ceremony cancelled")65 case .noCredential: return APIError(code: APIError.codePasskey, message: "No passkey available for this site")66 case .invalidOptions(let m): return APIError(code: APIError.codePasskey, message: "Invalid WebAuthn options: \(m)")67 case .failed(let code, let message): return APIError(code: APIError.codePasskey, message: "\(message) (\(code))")68 }69 }70}7172/// Performs WebAuthn ceremonies. Production: `PlatformPasskeyProvider` (AuthenticationServices, system passkeys).73/// Tests / Debug against a local backend: `SoftwareAuthenticator`.74public protocol PasskeyProvider: Sendable {75 func assertion(_ request: PasskeyAssertionRequest) async throws -> PasskeyAssertion76 func registration(_ request: PasskeyRegistrationRequest) async throws -> PasskeyRegistration77}7879/// Mapping between the server's WebAuthn JSON and the raw ceremony values. The output shapes are exactly what a80/// browser's `PublicKeyCredential.toJSON()` produces, which is what the server (go-webauthn) parses.81public enum WebAuthnJSON {82 public static func assertionRequest(from publicKey: JSONValue) throws -> PasskeyAssertionRequest {83 guard let challenge = publicKey["challenge"]?.stringValue.flatMap(Base64URL.decode), !challenge.isEmpty else {84 throw PasskeyError.invalidOptions("challenge")85 }86 guard let rp = publicKey["rpId"]?.stringValue, !rp.isEmpty else { throw PasskeyError.invalidOptions("rpId") }87 return PasskeyAssertionRequest(88 relyingPartyID: rp, challenge: challenge,89 allowedCredentialIDs: try credentialIDs(publicKey["allowCredentials"]),90 userVerification: publicKey["userVerification"]?.stringValue ?? "required",91 timeoutMilliseconds: publicKey["timeout"]?.intValue)92 }9394 public static func registrationRequest(from publicKey: JSONValue) throws -> PasskeyRegistrationRequest {95 guard let challenge = publicKey["challenge"]?.stringValue.flatMap(Base64URL.decode), !challenge.isEmpty else {96 throw PasskeyError.invalidOptions("challenge")97 }98 guard let rp = publicKey["rp"], let rpID = rp["id"]?.stringValue, !rpID.isEmpty else { throw PasskeyError.invalidOptions("rp.id") }99 guard let user = publicKey["user"], let uid = user["id"]?.stringValue.flatMap(Base64URL.decode), !uid.isEmpty,100 let name = user["name"]?.stringValue else { throw PasskeyError.invalidOptions("user") }101 let algs = publicKey["pubKeyCredParams"]?.arrayValue?.compactMap { $0["alg"]?.intValue } ?? []102 return PasskeyRegistrationRequest(103 relyingPartyID: rpID, relyingPartyName: rp["name"]?.stringValue ?? rpID,104 userID: uid, userName: name, userDisplayName: user["displayName"]?.stringValue ?? name,105 challenge: challenge, excludedCredentialIDs: try credentialIDs(publicKey["excludeCredentials"]),106 algorithms: algs,107 userVerification: publicKey["authenticatorSelection"]?["userVerification"]?.stringValue ?? "required",108 attestation: publicKey["attestation"]?.stringValue ?? "none",109 timeoutMilliseconds: publicKey["timeout"]?.intValue)110 }111112 private static func credentialIDs(_ list: JSONValue?) throws -> [Data] {113 guard let items = list?.arrayValue else { return [] }114 return try items.map {115 guard let id = $0["id"]?.stringValue.flatMap(Base64URL.decode) else { throw PasskeyError.invalidOptions("credential id") }116 return id117 }118 }119120 /// `AuthenticatorAssertionResponse` credential, as `PublicKeyCredential.toJSON()`.121 public static func credential(_ a: PasskeyAssertion) -> JSONValue {122 var response: [String: JSONValue] = [123 "clientDataJSON": .string(Base64URL.encode(a.clientDataJSON)),124 "authenticatorData": .string(Base64URL.encode(a.authenticatorData)),125 "signature": .string(Base64URL.encode(a.signature)),126 ]127 if let h = a.userHandle, !h.isEmpty { response["userHandle"] = .string(Base64URL.encode(h)) }128 var out: [String: JSONValue] = [129 "id": .string(Base64URL.encode(a.credentialID)),130 "rawId": .string(Base64URL.encode(a.credentialID)),131 "type": .string("public-key"),132 "response": .object(response),133 "clientExtensionResults": .object([:]),134 ]135 if let at = a.attachment { out["authenticatorAttachment"] = .string(at) }136 return .object(out)137 }138139 /// `AuthenticatorAttestationResponse` credential, as `PublicKeyCredential.toJSON()`.140 public static func credential(_ r: PasskeyRegistration) -> JSONValue {141 var out: [String: JSONValue] = [142 "id": .string(Base64URL.encode(r.credentialID)),143 "rawId": .string(Base64URL.encode(r.credentialID)),144 "type": .string("public-key"),145 "response": .object([146 "clientDataJSON": .string(Base64URL.encode(r.clientDataJSON)),147 "attestationObject": .string(Base64URL.encode(r.attestationObject)),148 "transports": .array(r.transports.map(JSONValue.string)),149 ]),150 "clientExtensionResults": .object([:]),151 ]152 if let at = r.attachment { out["authenticatorAttachment"] = .string(at) }153 return .object(out)154 }155}156