Cotton code
123 lines · 5.5 KB · SwiftRaw
// A COTTON-ACCOUNT PASSKEY ON THE IPHONE: the WebAuthn JSON// the core hands over (`personal.passkeyBegin`'s and `signin.passkeyOptions`'// `requestJson`) read into what AuthenticationServices takes, and the sheet's// answer written back as the WebAuthn JSON the Worker checks// (`apps/business/src/passkey.ts` `verifyCreate` / `verifyGet`). Pure, so a// test holds both spellings; the sheet itself is `CottonUI/Join/AccountPasskeySheet.swift`.//// Every binary field is base64url without padding, as the Worker writes and// reads them. The challenge goes to the sheet as the BYTES the Worker's text// names: the sheet puts it back into clientDataJSON as base64url, which is// the Worker's text again.import Foundationpublic enum AccountPasskeyJSON {    /// An assertion request (`navigator.credentials.get`'s options).    public struct Request: Equatable, Sendable {        public let rpId: String        public let challenge: Data    }    /// A creation request (`navigator.credentials.create`'s options).    public struct Creation: Equatable, Sendable {        public let rpId: String        public let challenge: Data        public let userId: Data        public let userName: String        /// The passkeys this account already has, so the sheet will not make a second on the same provider.        public let exclude: [Data]    }    /// What the sheet made or used, as raw bytes.    public struct Assertion: Equatable, Sendable {        public let credentialId: Data        public let clientDataJSON: Data        public let authenticatorData: Data        public let signature: Data        public let userHandle: Data?        public init(credentialId: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userHandle: Data?) {            self.credentialId = credentialId            self.clientDataJSON = clientDataJSON            self.authenticatorData = authenticatorData            self.signature = signature            self.userHandle = userHandle        }    }    public struct Registration: Equatable, Sendable {        public let credentialId: Data        public let clientDataJSON: Data        public let attestationObject: Data        public init(credentialId: Data, clientDataJSON: Data, attestationObject: Data) {            self.credentialId = credentialId            self.clientDataJSON = clientDataJSON            self.attestationObject = attestationObject        }    }    public static func request(_ json: String) -> Request? {        guard let object = parse(json), let rpId = object["rpId"] as? String, !rpId.isEmpty,            let challenge = (object["challenge"] as? String).flatMap(decode)        else { return nil }        return Request(rpId: rpId, challenge: challenge)    }    public static func creation(_ json: String) -> Creation? {        guard let object = parse(json),            let rp = object["rp"] as? [String: Any], let rpId = rp["id"] as? String, !rpId.isEmpty,            let user = object["user"] as? [String: Any], let userId = (user["id"] as? String).flatMap(decode),            let challenge = (object["challenge"] as? String).flatMap(decode)        else { return nil }        let name = (user["name"] as? String) ?? (user["displayName"] as? String) ?? ""        let exclude = (object["excludeCredentials"] as? [[String: Any]] ?? []).compactMap { ($0["id"] as? String).flatMap(decode) }        return Creation(rpId: rpId, challenge: challenge, userId: userId, userName: name, exclude: exclude)    }    /// The sign-in's answer, as `verifyGet` reads it.    public static func json(_ assertion: Assertion) -> String {        var response: [String: Any] = [            "clientDataJSON": encode(assertion.clientDataJSON),            "authenticatorData": encode(assertion.authenticatorData),            "signature": encode(assertion.signature),        ]        if let handle = assertion.userHandle { response["userHandle"] = encode(handle) }        return write(credential: assertion.credentialId, response: response)    }    /// The new passkey, as `verifyCreate` reads it.    public static func json(_ registration: Registration) -> String {        write(credential: registration.credentialId, response: [            "clientDataJSON": encode(registration.clientDataJSON),            "attestationObject": encode(registration.attestationObject),        ])    }    private static func write(credential: Data, response: [String: Any]) -> String {        let id = encode(credential)        let object: [String: Any] = [            "id": id, "rawId": id, "type": "public-key", "authenticatorAttachment": "platform",            "response": response, "clientExtensionResults": [String: Any](),        ]        let data = (try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])) ?? Data()        return String(decoding: data, as: UTF8.self)    }    private static func parse(_ json: String) -> [String: Any]? {        (try? JSONSerialization.jsonObject(with: Data(json.utf8))) as? [String: Any]    }    /// base64url, no padding.    public static func encode(_ data: Data) -> String {        data.base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_")            .replacingOccurrences(of: "=", with: "")    }    public static func decode(_ text: String) -> Data? {        var base = text.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")        while base.count % 4 != 0 { base += "=" }        return Data(base64Encoded: base)    }}