Cotton code
102 lines · 3.7 KB · SwiftRaw
// Where Cotton chat's secret lives on this phone: one item in the keychain// group the app shares with its notification extension.//// - `key`: this phone's CHAT private key (32 bytes, base64url as the core//   writes it), minted by `chat.key`. Never the vault key: the vault's is read//   behind Face ID, and the extension opening a message on a locked phone//   could never ask for that (`crates/cotton-ffi/src/phone/cotton_chat.rs`).//// The extension reaches no server: the push carries the box it opens. The// device's credential stays in the core.//// It is `AfterFirstUnlockThisDeviceOnly`: readable by the extension while// the phone is locked once it has been unlocked since boot, never synced,// never backed up off the phone. Sign-out forgets it. Nothing here logs.import Foundationimport Security/// Where the chat key is kept: the shared keychain group on a/// phone, memory in a test.public protocol ChatSecrets: Sendable {    func key() -> String?    func saveKey(_ key: String) throws    func forget()}/// Why the keychain refused, by its OSStatus.struct ChatKeychainError: Error, Equatable, Sendable {    public let status: OSStatus}/// The shared keychain group's chat items.public struct ChatKeychain: ChatSecrets {    public static let service = "cotton.chat"    private static let keyAccount = "key"    private let accessGroup: String?    /// `accessGroup` nil files the items 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    }    public func key() -> String? {        read(Self.keyAccount).map { String(decoding: $0, as: UTF8.self) }    }    public func saveKey(_ key: String) throws {        try write(Self.keyAccount, Data(key.utf8))    }    public func forget() {        var query = base()        query[kSecAttrAccount as String] = Self.keyAccount        SecItemDelete(query as CFDictionary)    }    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    }    private func read(_ account: String) -> Data? {        var query = base()        query[kSecAttrAccount as String] = account        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    }    private func write(_ account: String, _ data: Data) throws {        var query = base()        query[kSecAttrAccount as String] = account        SecItemDelete(query as CFDictionary)        query[kSecValueData as String] = data        query[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly        query[kSecAttrSynchronizable as String] = false        let status = SecItemAdd(query as CFDictionary, nil)        guard status == errSecSuccess else { throw ChatKeychainError(status: status) }    }}/// Chat secrets in memory: a test's, never a phone's.public final class MemoryChatSecrets: ChatSecrets, @unchecked Sendable {    private let lock = NSLock()    private var heldKey: String?    public init(key: String? = nil) {        heldKey = key    }    public func key() -> String? { lock.withLock { heldKey } }    public func saveKey(_ key: String) throws { lock.withLock { heldKey = key } }    public func forget() { lock.withLock { heldKey = nil } }}