SPB Git

Repository Public

PasskeyCeremony.swift 14.7 KB 336 lines swift

1// SP Notes Core2// File: Sources/SPNotesAPI/PasskeyCeremony.swift3// Description: The pure half of the WebAuthn ceremonies: decoding the options JSON the server sends and encoding the4//              authenticator's answer into the exact JSON bodies the server verifies. No system UI here.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import AuthenticationServices9import Foundation1011// MARK: - Options sent by the server1213/// A credential reference of `allowCredentials` / `excludeCredentials`.14public struct PasskeyCredentialDescriptor: Decodable, Sendable, Equatable {15    public var id: Data16    public var transports: [String]?1718    public init(id: Data, transports: [String]? = nil) {19        self.id = id20        self.transports = transports21    }2223    enum CodingKeys: String, CodingKey { case id, transports }2425    public init(from decoder: Decoder) throws {26        let c = try decoder.container(keyedBy: CodingKeys.self)27        id = try c.decodeBase64URL(forKey: .id)28        transports = try c.decodeIfPresent([String].self, forKey: .transports)29    }30}3132/// `PublicKeyCredentialRequestOptionsJSON` (sign-in, step-up).33public struct PasskeyRequestOptions: Decodable, Sendable, Equatable {34    public var challenge: Data35    /// Relying party identifier (`note.spboucher.ai`).36    public var rpId: String?37    /// Empty = any discoverable passkey of the relying party.38    public var allowCredentials: [PasskeyCredentialDescriptor]39    public var userVerification: String?40    /// Milliseconds.41    public var timeout: Double?4243    public init(challenge: Data, rpId: String?, allowCredentials: [PasskeyCredentialDescriptor] = [], userVerification: String? = "required", timeout: Double? = nil) {44        self.challenge = challenge45        self.rpId = rpId46        self.allowCredentials = allowCredentials47        self.userVerification = userVerification48        self.timeout = timeout49    }5051    enum CodingKeys: String, CodingKey { case challenge, rpId, allowCredentials, userVerification, timeout }5253    public init(from decoder: Decoder) throws {54        let c = try decoder.container(keyedBy: CodingKeys.self)55        challenge = try c.decodeBase64URL(forKey: .challenge)56        rpId = try c.decodeIfPresent(String.self, forKey: .rpId)57        allowCredentials = try c.decodeIfPresent([PasskeyCredentialDescriptor].self, forKey: .allowCredentials) ?? []58        userVerification = try c.decodeIfPresent(String.self, forKey: .userVerification)59        timeout = try c.decodeIfPresent(Double.self, forKey: .timeout)60    }61}6263/// `PublicKeyCredentialCreationOptionsJSON` (adding a passkey).64public struct PasskeyCreationOptions: Decodable, Sendable, Equatable {65    public struct RelyingParty: Decodable, Sendable, Equatable {66        public var id: String?67        public var name: String6869        public init(id: String?, name: String) {70            self.id = id71            self.name = name72        }73    }7475    public struct User: Decodable, Sendable, Equatable {76        public var id: Data77        public var name: String78        public var displayName: String?7980        public init(id: Data, name: String, displayName: String? = nil) {81            self.id = id82            self.name = name83            self.displayName = displayName84        }8586        enum CodingKeys: String, CodingKey { case id, name, displayName }8788        public init(from decoder: Decoder) throws {89            let c = try decoder.container(keyedBy: CodingKeys.self)90            id = try c.decodeBase64URL(forKey: .id)91            name = try c.decode(String.self, forKey: .name)92            displayName = try c.decodeIfPresent(String.self, forKey: .displayName)93        }94    }9596    public var challenge: Data97    public var rp: RelyingParty98    public var user: User99    public var excludeCredentials: [PasskeyCredentialDescriptor]100    public var attestation: String?101    /// Milliseconds.102    public var timeout: Double?103104    public init(challenge: Data, rp: RelyingParty, user: User, excludeCredentials: [PasskeyCredentialDescriptor] = [], attestation: String? = nil, timeout: Double? = nil) {105        self.challenge = challenge106        self.rp = rp107        self.user = user108        self.excludeCredentials = excludeCredentials109        self.attestation = attestation110        self.timeout = timeout111    }112113    enum CodingKeys: String, CodingKey { case challenge, rp, user, excludeCredentials, attestation, timeout }114115    public init(from decoder: Decoder) throws {116        let c = try decoder.container(keyedBy: CodingKeys.self)117        challenge = try c.decodeBase64URL(forKey: .challenge)118        rp = try c.decode(RelyingParty.self, forKey: .rp)119        user = try c.decode(User.self, forKey: .user)120        excludeCredentials = try c.decodeIfPresent([PasskeyCredentialDescriptor].self, forKey: .excludeCredentials) ?? []121        attestation = try c.decodeIfPresent(String.self, forKey: .attestation)122        timeout = try c.decodeIfPresent(Double.self, forKey: .timeout)123    }124}125126extension KeyedDecodingContainer {127    /// A base64url (or base64) string, with or without padding.128    func decodeBase64URL(forKey key: Key) throws -> Data {129        let text = try decode(String.self, forKey: key)130        guard let data = Base64URL.decode(text) else {131            throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "not base64url")132        }133        return data134    }135}136137// MARK: - Answers sent to the server138139/// `{}`140public struct EmptyJSONObject: Codable, Sendable, Equatable {141    public init() {}142}143144/// `AuthenticationResponseJSON`: the `response` member of a `login/verify` or `reauth/verify` body.145/// Binary fields are base64url without padding.146public struct PasskeyAssertionCredential: Encodable, Sendable, Equatable {147    public struct Response: Encodable, Sendable, Equatable {148        public var clientDataJSON: String149        public var authenticatorData: String150        public var signature: String151        public var userHandle: String?152    }153154    public var id: String155    public var rawId: String156    public var type: String157    public var response: Response158    public var clientExtensionResults: EmptyJSONObject159    public var authenticatorAttachment: String160}161162/// `RegistrationResponseJSON`: the `response` member of a `passkeys/verify` body.163public struct PasskeyRegistrationCredential: Encodable, Sendable, Equatable {164    public struct Response: Encodable, Sendable, Equatable {165        public var clientDataJSON: String166        public var attestationObject: String167        public var transports: [String]168    }169170    public var id: String171    public var rawId: String172    public var type: String173    public var response: Response174    public var clientExtensionResults: EmptyJSONObject175    public var authenticatorAttachment: String176}177178/// Pure helpers of the passkey ceremonies (testable without AuthenticationServices objects).179public enum PasskeyCeremony {180    /// Key under which the transport keeps the ceremony cookie between `options` and `verify`.181    public enum Kind: String, Sendable, CaseIterable {182        case login, reauth, register183    }184185    // MARK: decoding186187    /// Decodes request options from the server's JSON: either the options object itself or the `{ "options": … }` envelope.188    public static func decodeRequestOptions(_ json: Data) throws -> PasskeyRequestOptions {189        try decodeOptions(json)190    }191192    /// Decodes creation options from the server's JSON: either the options object itself or the `{ "options": … }` envelope.193    public static func decodeCreationOptions(_ json: Data) throws -> PasskeyCreationOptions {194        try decodeOptions(json)195    }196197    private struct Envelope<Options: Decodable>: Decodable { var options: Options }198199    private static func decodeOptions<Options: Decodable>(_ json: Data) throws -> Options {200        let decoder = JSONDecoder()201        if let envelope = try? decoder.decode(Envelope<Options>.self, from: json) { return envelope.options }202        do { return try decoder.decode(Options.self, from: json) } catch {203            throw PasskeyError.invalidOptions(HTTPResponse.describe(error))204        }205    }206207    // MARK: encoding208209    /// Builds the assertion answer from the raw fields of the authenticator.210    /// - Parameter userHandle: omitted from the JSON when `nil` or empty.211    public static func assertionCredential(credentialID: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userHandle: Data?) -> PasskeyAssertionCredential {212        let id = Base64URL.encode(credentialID)213        return PasskeyAssertionCredential(214            id: id, rawId: id, type: "public-key",215            response: .init(216                clientDataJSON: Base64URL.encode(clientDataJSON),217                authenticatorData: Base64URL.encode(authenticatorData),218                signature: Base64URL.encode(signature),219                userHandle: userHandle.flatMap { $0.isEmpty ? nil : Base64URL.encode($0) }220            ),221            clientExtensionResults: EmptyJSONObject(), authenticatorAttachment: "platform"222        )223    }224225    /// Builds the registration answer from the raw fields of the authenticator.226    public static func registrationCredential(credentialID: Data, clientDataJSON: Data, attestationObject: Data) -> PasskeyRegistrationCredential {227        let id = Base64URL.encode(credentialID)228        return PasskeyRegistrationCredential(229            id: id, rawId: id, type: "public-key",230            response: .init(231                clientDataJSON: Base64URL.encode(clientDataJSON),232                attestationObject: Base64URL.encode(attestationObject),233                transports: ["internal", "hybrid"]234            ),235            clientExtensionResults: EmptyJSONObject(), authenticatorAttachment: "platform"236        )237    }238239    private struct AssertionBody: Encodable { var response: PasskeyAssertionCredential }240    private struct RegistrationBody: Encodable {241        var response: PasskeyRegistrationCredential242        var label: String?243    }244245    /// The body of `POST /api/auth/login/verify` and `POST /api/auth/reauth/verify`: `{ "response": … }` (sorted keys).246    public static func assertionVerifyBody(_ credential: PasskeyAssertionCredential) throws -> Data {247        try APIJSON.encoder().encode(AssertionBody(response: credential))248    }249250    /// The body of `POST /api/auth/passkeys/verify`: `{ "response": …, "label"?: … }` (sorted keys). The label is251    /// trimmed, cut to 60 characters and omitted when empty.252    public static func registrationVerifyBody(_ credential: PasskeyRegistrationCredential, label: String?) throws -> Data {253        let trimmed = label.map { String($0.trimmingCharacters(in: .whitespacesAndNewlines).prefix(60)) }254        return try APIJSON.encoder().encode(RegistrationBody(response: credential, label: trimmed?.isEmpty == false ? trimmed : nil))255    }256257    // MARK: adapters from AuthenticationServices258259    public static func assertionCredential(from assertion: ASAuthorizationPlatformPublicKeyCredentialAssertion) -> PasskeyAssertionCredential {260        assertionCredential(261            credentialID: assertion.credentialID, clientDataJSON: assertion.rawClientDataJSON,262            authenticatorData: assertion.rawAuthenticatorData, signature: assertion.signature, userHandle: assertion.userID263        )264    }265266    public static func registrationCredential(from registration: ASAuthorizationPlatformPublicKeyCredentialRegistration) throws -> PasskeyRegistrationCredential {267        guard let attestation = registration.rawAttestationObject else {268            throw PasskeyError.failed(code: 0, message: "The authenticator returned no attestation object.")269        }270        return registrationCredential(credentialID: registration.credentialID, clientDataJSON: registration.rawClientDataJSON, attestationObject: attestation)271    }272}273274// MARK: - Errors275276/// What can go wrong on the device side of a ceremony.277public enum PasskeyError: Error, Sendable, Equatable {278    /// The person dismissed the system sheet.279    case cancelled280    /// No passkey of this relying party is available on the device.281    case noCredentials282    /// Registration: this device already holds one of the account's passkeys.283    case alreadyRegistered284    /// The system could not show its sheet (no window, app in the background).285    case notInteractive286    /// Another ceremony is already on screen.287    case inProgress288    /// The app is not associated with the relying party domain (associated domains / AASA file).289    case notAssociated(String)290    /// The options sent by the server cannot be used.291    case invalidOptions(String)292    /// Any other `ASAuthorizationError`.293    case failed(code: Int, message: String)294295    public var isCancelled: Bool { self == .cancelled }296297    /// Maps what `ASAuthorizationController` reports.298    public static func from(_ error: Error) -> PasskeyError {299        if let e = error as? PasskeyError { return e }300        if error is CancellationError { return .cancelled }301        let ns = error as NSError302        guard ns.domain == ASAuthorizationError.errorDomain else { return .failed(code: ns.code, message: ns.localizedDescription) }303        let detail = [ns.userInfo[NSLocalizedFailureReasonErrorKey] as? String, ns.userInfo[NSDebugDescriptionErrorKey] as? String, ns.localizedDescription]304            .compactMap { $0 }.joined(separator: " ")305        let lowered = detail.lowercased()306        switch ASAuthorizationError.Code(rawValue: ns.code) {307        case .canceled?:308            // With "prefer immediately available credentials" the system reports the absence of a passkey as a cancellation.309            return lowered.contains("no credentials") ? .noCredentials : .cancelled310        case .notInteractive?:311            return .notInteractive312        case .matchedExcludedCredential?:313            return .alreadyRegistered314        default:315            if lowered.contains("not associated") || lowered.contains("associated domain") { return .notAssociated(detail) }316            if lowered.contains("no credentials") { return .noCredentials }317            return .failed(code: ns.code, message: detail)318        }319    }320}321322extension PasskeyError: LocalizedError {323    public var errorDescription: String? {324        switch self {325        case .cancelled: return "The passkey verification was cancelled."326        case .noCredentials: return "No passkey for this account is available on this device."327        case .alreadyRegistered: return "This device already has a passkey for this account."328        case .notInteractive: return "The passkey sheet could not be shown."329        case .inProgress: return "A passkey verification is already in progress."330        case .notAssociated(let detail): return "The app is not associated with the server domain yet. \(detail)"331        case .invalidOptions(let detail): return "The server sent unusable passkey options: \(detail)"332        case .failed(_, let message): return message333        }334    }335}336
Files main
Menu

Theme