Cotton code
258 lines · 12.7 KB · SwiftRaw
// What Cotton Keys does with passkeys another app hands over.////   the Passwords app (Credential Exchange, iOS 26)//     → the app opens with ASCredentialExchangeActivity, its token in//       userInfo[ASCredentialImportToken]   (`CottonUI/Boot/KeysImport.swift`)//     → ASCredentialImportManager.importCredentials(token:) → ASExportedCredentialData//     → `exportJSON` — CXF 1.0 JSON written from Apple's typed values by the//       spec's names (ids base64url, times UNIX seconds)//     → `run(json:)` → `passkey.importCxf` (each passkey sealed under the VMK)////   Apple Passwords' CSV (Passwords' Plus door, `CottonUI/Deck/Shell/DeckDoors.swift`)//     → `csv(_:)` → `password.importCsv` (each login sealed under the VMK)//// A Credential Exchange export's logins land beside its passkeys// (`passkey.importCxf` answers them as `passwords`).//// A locked vault refuses the whole export; when the person is here this// device's vault key is read once (the read IS the Face ID prompt) and lent// for that one call, never kept.//// THE DEVELOPER LOG (subsystem com.cottondb.keys, category import) is how the// first real export teaches Apple's shape: the exporter, every skip reason,// every field name the export used that CXF 1.0 does not name, and a refusal's// words. Never a key, never a user name, never a site's account.import Foundationimport OSLog#if os(iOS)    import AuthenticationServices#endif/// One import's outcome, for the toast.public struct PasskeyImported: Equatable, Sendable {    public struct Skip: Equatable, Sendable {        public var title: String        public var reason: String        public init(title: String, reason: String) {            self.title = title            self.reason = reason        }    }    /// The passkeys written, by site.    public var sites: [String]    /// The passwords written, by site.    public var passwords: [String] = []    /// What was not written, and why.    public var skipped: [Skip]    /// Who made the export.    public var exporter: String    /// The refusal's words when nothing was written; nil when it was read.    public var refused: String?    /// Whether the refusal was the vault's (open it and import again).    public var locked: Bool    public init(sites: [String], skipped: [Skip], exporter: String, refused: String?, locked: Bool) {        self.sites = sites        self.skipped = skipped        self.exporter = exporter        self.refused = refused        self.locked = locked    }    /// Nothing written, for this reason.    public static func refused(_ reason: String) -> PasskeyImported {        PasskeyImported(sites: [], skipped: [], exporter: "", refused: reason, locked: false)    }}/// Cotton Keys' Credential Exchange import.public struct PasskeyImport: Sendable {    private let core: any CottonCalling    private let keyring: VaultKeyring    /// The developer log: names and reasons, never a key or a user name.    public static let log = Logger(subsystem: "com.cottondb.keys", category: "import")    public init(core: any CottonCalling, keyring: VaultKeyring = VaultKeyring()) {        self.core = core        self.keyring = keyring    }    /// The export's CXF JSON through `passkey.importCxf`. `presence` says the    /// person is here, so a locked vault may ask for Face ID once.    public func run(json: String, presence: Bool = true) async -> PasskeyImported {        await call(CottonMethod.passkeyImportCxf, ["json": json], presence: presence, read: Self.read)    }    /// Apple Passwords' CSV export through `password.importCsv`, as `run`    /// takes a Credential Exchange export.    public func csv(_ text: String, presence: Bool = true) async -> PasskeyImported {        await call(CottonMethod.passwordImportCsv, ["csv": text], presence: presence, read: Self.readCsv)    }    private func call(_ method: String, _ request: [String: String], presence: Bool,                      read: (JSONValue) -> PasskeyImported) async -> PasskeyImported {        do {            return read(try await core.callJSON(method, request))        } catch let refusal as CottonCallError where refusal.code == "vault_locked" && presence {            Self.log.notice("import: the vault is locked; asking for this device's vault key once")            guard let key = await vaultKey() else { return Self.refusal(refusal, locked: true) }            var lent = request            lent["privateKey"] = key            do {                return read(try await core.callJSON(method, lent))            } catch let again as CottonCallError {                return Self.refusal(again, locked: again.code == "vault_locked")            } catch {                return Self.refusal(CottonCallError(code: "unreadable", message: error.localizedDescription), locked: false)            }        } catch let refusal as CottonCallError {            return Self.refusal(refusal, locked: refusal.code == "vault_locked")        } catch {            return Self.refusal(CottonCallError(code: "unreadable", message: error.localizedDescription), locked: false)        }    }    static func read(_ answer: JSONValue) -> PasskeyImported {        let exporter = answer["exporter"]?.string ?? ""        let sites = (answer["imported"]?.array ?? []).compactMap { $0["rp_id"]?.string }        let skipped = (answer["skipped"]?.array ?? []).map {            PasskeyImported.Skip(title: $0["title"]?.string ?? "", reason: $0["reason"]?.string ?? "")        }        let unnamed = answer["unnamed"]?.strings ?? []        log.notice("import: from \(exporter, privacy: .public): \(sites.count) imported, \(skipped.count) skipped")        for skip in skipped {            log.notice("import: skipped \(skip.title, privacy: .public): \(skip.reason, privacy: .public)")        }        if !unnamed.isEmpty {            log.notice("import: fields CXF 1.0 does not name: \(unnamed.joined(separator: ", "), privacy: .public)")        }        var outcome = PasskeyImported(sites: sites, skipped: skipped, exporter: exporter, refused: nil, locked: false)        outcome.passwords = (answer["passwords"]?.array ?? []).compactMap { $0["site"]?.string }        return outcome    }    /// `password.importCsv`'s answer: `{imported: [{id, site, username}],    /// skipped: [{title, reason}], unnamed}`.    static func readCsv(_ answer: JSONValue) -> PasskeyImported {        let skipped = (answer["skipped"]?.array ?? []).map {            PasskeyImported.Skip(title: $0["title"]?.string ?? "", reason: $0["reason"]?.string ?? "")        }        var outcome = PasskeyImported(sites: [], skipped: skipped, exporter: "", refused: nil, locked: false)        outcome.passwords = (answer["imported"]?.array ?? []).compactMap { $0["site"]?.string }        let unnamed = answer["unnamed"]?.strings ?? []        log.notice("import: csv: \(outcome.passwords.count) imported, \(skipped.count) skipped")        for skip in skipped {            log.notice("import: skipped \(skip.title, privacy: .public): \(skip.reason, privacy: .public)")        }        if !unnamed.isEmpty {            log.notice("import: csv columns the reader does not name: \(unnamed.joined(separator: ", "), privacy: .public)")        }        return outcome    }    static func refusal(_ refusal: CottonCallError, locked: Bool) -> PasskeyImported {        log.error("import: refused \(refusal.code, privacy: .public): \(refusal.message, privacy: .public)")        return PasskeyImported(sites: [], skipped: [], exporter: "", refused: refusal.message, locked: locked)    }    /// This device's vault key, read once after the presence prompt; nil on    /// cancel or with no key.    private func vaultKey() async -> String? {        let keyring = self.keyring        return await Task.detached(priority: .userInitiated) { try? keyring.privateKey() }.value    }    /// RFC 4648 §5 base64url without padding (CXF 1.0 §2.1 b64url).    static func base64url(_ data: Data) -> String {        data.base64EncodedString()            .replacingOccurrences(of: "+", with: "-")            .replacingOccurrences(of: "/", with: "_")            .replacingOccurrences(of: "=", with: "")    }    /// A JSON encoder speaking CXF 1.0 §2.1's spellings: binary as base64url,    /// times as whole UNIX seconds. Apple's own encoding of an export is read    /// through it for its field names (the developer log).    public static func encoder() -> JSONEncoder {        let encoder = JSONEncoder()        encoder.dataEncodingStrategy = .custom { data, encoder in            var one = encoder.singleValueContainer()            try one.encode(base64url(data))        }        encoder.dateEncodingStrategy = .custom { date, encoder in            var one = encoder.singleValueContainer()            try one.encode(Int64(date.timeIntervalSince1970.rounded(.down)))        }        encoder.outputFormatting = [.sortedKeys]        return encoder    }    #if os(iOS)        /// The handed-over export as CXF 1.0 JSON, written from Apple's typed        /// values by the spec's names (§3.1 header, §3.2.1 account, §3.2.3        /// item, §3.3.12 passkey) rather than by Apple's own coding keys, which        /// no document says. A non-passkey credential is written as its kind        /// alone, for the core to skip in words. Apple's own encoding is read        /// for its field NAMES only, into the developer log.        @available(iOS 26.0, *)        public static func exportJSON(_ data: ASExportedCredentialData) throws -> String {            if let own = try? encoder().encode(data), let top = try? JSONSerialization.jsonObject(with: own) as? [String: Any] {                log.notice("import: Apple's own encoding names: \(top.keys.sorted().joined(separator: ", "), privacy: .public)")            }            let accounts: [[String: Any]] = data.accounts.map { account in                [                    "id": base64url(account.id), "username": account.userName, "email": account.email,                    "collections": [Any](),                    "items": account.items.map { item -> [String: Any] in                        var one: [String: Any] = [                            "id": base64url(item.id), "title": item.title,                            "credentials": item.credentials.map(credential),                        ]                        if let subtitle = item.subtitle { one["subtitle"] = subtitle }                        if let created = item.created { one["creationAt"] = Int64(created.timeIntervalSince1970.rounded(.down)) }                        return one                    },                ]            }            let root: [String: Any] = [                "version": ["major": 1, "minor": 0],                "exporterRpId": data.exporterRelyingPartyIdentifier,                "exporterDisplayName": data.exporterDisplayName,                "timestamp": Int64(data.timestamp.timeIntervalSince1970.rounded(.down)),                "accounts": accounts,            ]            return String(decoding: try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys]), as: UTF8.self)        }        @available(iOS 26.0, *)        private static func credential(_ credential: ASImportableCredential) -> [String: Any] {            if case .passkey(let passkey) = credential {                var one: [String: Any] = [                    "type": "passkey", "credentialId": base64url(passkey.credentialID), "rpId": passkey.relyingPartyIdentifier,                    "username": passkey.userName, "userDisplayName": passkey.userDisplayName,                    "userHandle": base64url(passkey.userHandle), "key": base64url(passkey.key),                ]                if #available(iOS 26.4, *), passkey.fido2Extensions != nil {                    // Their members are not carried (CXF §3.3.12.2); said so the log names them.                    log.notice("import: a passkey carried fido2Extensions, not imported")                }                return one            }            // The case's own name (totp, basicAuthentication, …): the kind the core names when it skips it.            let kind = Mirror(reflecting: credential).children.first?.label ?? "unknown"            return ["type": kind]        }        /// The export a Credential Exchange token names, read from the system.        @available(iOS 26.0, *)        public static func exported(token: UUID) async throws -> String {            let data = try await ASCredentialImportManager().importCredentials(token: token)            log.notice("import: handed over by \(data.exporterDisplayName, privacy: .public) (\(data.exporterRelyingPartyIdentifier, privacy: .public)), \(data.accounts.count) accounts, format \(data.formatVersion.rawValue, privacy: .public)")            return try exportJSON(data)        }    #endif}