Cotton code
147 lines · 6.1 KB · SwiftRaw
// Where a passkey's private half lives on this phone: one item per credential// in the keychain group Cotton Keys shares with its credential provider.//// The item is DEVICE-LOCAL PLAINTEXT under the device's own protection// (`kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`, never synced, never// backed up off the phone); the row's `private_key_enc` is the synced copy,// sealed under the vault. The provider writes an item when it registers and// reads one to sign; the app reads one for the call that seals it into a row,// writes one for a row made on another device (`passkey.mirror`), and removes// the item of a row that is gone.//// The scalar is 32 bytes; the item's `generic` attribute carries what the// picker and the identity store need (site, site name, account, account id,// made) — never the key. Nothing here logs.import Foundationimport Security/// What a kept passkey says about itself, without its key.public struct PasskeyKeychainItem: Codable, Equatable, Sendable {    public var credentialId: String    public var rpId: String    public var rpName: String?    public var userName: String?    public var userHandle: String    public var createdAt: String    public init(credentialId: String, rpId: String, rpName: String?, userName: String?, userHandle: String, createdAt: String) {        self.credentialId = credentialId        self.rpId = rpId        self.rpName = rpName        self.userName = userName        self.userHandle = userHandle        self.createdAt = createdAt    }    private enum CodingKeys: String, CodingKey {        case credentialId = "credential_id"        case rpId = "rp_id"        case rpName = "rp_name"        case userName = "user_name"        case userHandle = "user_handle"        case createdAt = "created_at"    }}/// Why the keychain refused, by its OSStatus.struct PasskeyKeychainError: Error, Equatable, Sendable {    let status: OSStatus}/// Where passkey items are kept: the shared keychain group on a phone, a/// dictionary in a test.public protocol PasskeyKeys: Sendable {    func save(_ item: PasskeyKeychainItem, scalar: Data) throws    func scalar(credentialId: String) -> Data?    func items(rpId: String?) -> [PasskeyKeychainItem]    func remove(credentialId: String)}/// The shared keychain group's passkey items.public struct PasskeyKeychain: PasskeyKeys {    /// The service every passkey item is filed under.    public static let service = "cotton.keys.passkey"    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.    public init(accessGroup: String? = PasskeyKeychain.sharedGroup()) {        self.accessGroup = accessGroup    }    /// The group the app and its provider share: this bundle's    /// `CottonKeychainGroup`, when a signed build stamped it team-prefixed.    public static func sharedGroup(bundle: Bundle = .main) -> String? {        guard let group = bundle.object(forInfoDictionaryKey: "CottonKeychainGroup") as? String,            let dot = group.firstIndex(of: "."), group.index(after: dot) < group.endIndex        else { return nil }        let team = group[..<dot]        guard team.count == 10, team.allSatisfy({ $0.isASCII && ($0.isUppercase || $0.isNumber) }) else { return nil }        return group    }    private func base() -> [String: Any] {        var query: [String: Any] = [            kSecClass as String: kSecClassGenericPassword,            kSecAttrService as String: Self.service,        ]        if let accessGroup { query[kSecAttrAccessGroup as String] = accessGroup }        return query    }    /// Keep `scalar` for `item`, replacing an item for the same credential.    public func save(_ item: PasskeyKeychainItem, scalar: Data) throws {        remove(credentialId: item.credentialId)        var query = base()        query[kSecAttrAccount as String] = item.credentialId        query[kSecAttrLabel as String] = item.rpId        query[kSecAttrGeneric as String] = try JSONEncoder().encode(item)        query[kSecValueData as String] = scalar        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 scalar kept for this credential, or nil.    public func scalar(credentialId: String) -> Data? {        var query = base()        query[kSecAttrAccount as String] = credentialId        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 passkey, or those for one site — without their keys.    public func items(rpId: String? = nil) -> [PasskeyKeychainItem] {        var query = base()        if let rpId { query[kSecAttrLabel as String] = rpId }        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(PasskeyKeychainItem.self, from: generic)        }        .sorted { ($0.rpId, $0.userName ?? "") < ($1.rpId, $1.userName ?? "") }    }    /// The item for one credential, without its key.    public func item(credentialId: String) -> PasskeyKeychainItem? {        items().first { $0.credentialId == credentialId }    }    /// Forget one credential's item.    public func remove(credentialId: String) {        var query = base()        query[kSecAttrAccount as String] = credentialId        SecItemDelete(query as CFDictionary)    }}