Cotton code
143 lines · 6.1 KB · SwiftRaw
// Where Cotton Keys' credential provider fills a password from: one item per// login in the keychain group the app shares with its provider, as a// passkey's private half lives there (`PasskeyKeychain`).//// The provider holds no core and cannot open a row, so the APP keeps this// copy: after each pass it asks the core (`password.mirror`) for every login// sealed on the owner's devices that this keychain lacks or holds at another// stamp, writes those, and removes the ones the core names gone// (`PasswordArrivals`). The item is DEVICE-LOCAL PLAINTEXT under the// device's own protection (`kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`,// never synced, never backed up off the phone); the row's `value_enc` is the// synced copy, sealed under the vault. A login the Worker sealed (k1) never// reaches it.//// A second service keeps what the provider was handed to SAVE (iOS 26.2's// save request) until the app seals it into a row: the provider writes the// password here under a fresh pending id and a mailbox entry names that id,// never the password (`PasswordMailbox`).//// The item's `generic` attribute carries what the list and the identity store// need (id, site, account, name, stamp), never the password. Nothing here// logs.import Foundationimport Security/// What a kept login says about itself, without its password.public struct PasswordKeychainItem: Codable, Equatable, Sendable {    /// The `secret` row's id (a pending save's own id in the pending store).    public var id: String    /// The login's site, a host (`password.list`'s `site`).    public var site: String    public var username: String?    public var name: String?    /// The core's stamp for what this copy was made from (`password.mirror`).    public var stamp: String    public init(id: String, site: String, username: String?, name: String?, stamp: String) {        self.id = id        self.site = site        self.username = username        self.name = name        self.stamp = stamp    }}/// Where password items are kept: the shared keychain group on a phone, a/// dictionary in a test.public protocol PasswordKeys: Sendable {    func save(_ item: PasswordKeychainItem, password: Data) throws    func password(id: String) -> Data?    func items() -> [PasswordKeychainItem]    func remove(id: String)}/// The shared keychain group's password items, under one service.public struct PasswordKeychain: PasswordKeys {    /// The logins the provider fills from.    public static let service = "cotton.keys.password"    /// What the provider was handed to save, waiting for the app.    public static let pendingService = "cotton.keys.password.pending"    private let service: String    private let accessGroup: String?    /// `accessGroup` nil files the item where the system does (a test, an    /// unsigned build); a shipping build names the shared group, as    /// ``PasskeyKeychain/sharedGroup(bundle:)`` reads it.    public init(service: String = PasswordKeychain.service, accessGroup: String? = PasskeyKeychain.sharedGroup()) {        self.service = service        self.accessGroup = accessGroup    }    /// The store of saves waiting for the app.    public static func pending(accessGroup: String? = PasskeyKeychain.sharedGroup()) -> PasswordKeychain {        PasswordKeychain(service: pendingService, accessGroup: accessGroup)    }    private func base() -> [String: Any] {        var query: [String: Any] = [            kSecClass as String: kSecClassGenericPassword,            kSecAttrService as String: service,        ]        if let accessGroup { query[kSecAttrAccessGroup as String] = accessGroup }        return query    }    /// Keep `password` for `item`, replacing an item with the same id.    public func save(_ item: PasswordKeychainItem, password: Data) throws {        remove(id: item.id)        var query = base()        query[kSecAttrAccount as String] = item.id        query[kSecAttrLabel as String] = item.site        query[kSecAttrGeneric as String] = try JSONEncoder().encode(item)        query[kSecValueData as String] = password        query[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly        query[kSecAttrSynchronizable as String] = false        let status = SecItemAdd(query as CFDictionary, nil)        guard status == errSecSuccess else { throw PasskeyKeychainError(status: status) }    }    /// The password kept under this id, or nil.    public func password(id: String) -> Data? {        var query = base()        query[kSecAttrAccount as String] = id        query[kSecReturnData as String] = true        query[kSecMatchLimit as String] = kSecMatchLimitOne        var found: CFTypeRef?        guard SecItemCopyMatching(query as CFDictionary, &found) == errSecSuccess else { return nil }        return found as? Data    }    /// Every kept login, without its password, by site then account.    public func items() -> [PasswordKeychainItem] {        var query = base()        query[kSecReturnAttributes as String] = true        query[kSecMatchLimit as String] = kSecMatchLimitAll        var found: CFTypeRef?        guard SecItemCopyMatching(query as CFDictionary, &found) == errSecSuccess,            let rows = found as? [[String: Any]]        else { return [] }        return rows.compactMap { row in            guard let generic = row[kSecAttrGeneric as String] as? Data else { return nil }            return try? JSONDecoder().decode(PasswordKeychainItem.self, from: generic)        }        .sorted { ($0.site, $0.username ?? "") < ($1.site, $1.username ?? "") }    }    /// The logins kept for one service identifier: the site itself, or a    /// site under it (`accounts.invented.test` for `invented.test`), or the    /// host of an address.    public func items(for service: String) -> [PasswordKeychainItem] {        let host = (URL(string: service)?.host ?? service).lowercased()        return items().filter { $0.site == host || host.hasSuffix("." + $0.site) || $0.site.hasSuffix("." + host) }    }    /// Forget one item.    public func remove(id: String) {        var query = base()        query[kSecAttrAccount as String] = id        SecItemDelete(query as CFDictionary)    }}