Cotton code
87 lines · 3.5 KB · SwiftRaw
import Foundationimport Security/// The app's keychain items, under the one service `com.decemberfm.cotton.mac`:/// the device token, the owner's number, and the Mail/// credentials. Every account is prefixed `importer.` because the same service/// name also holds CottonDB's own items (its device key, its vault key), and/// this app never reads or touches those.enum Keychain {    /// The bundle's own id: a flavour's items (AppModel.flavour) never meet the installed app's.    static let service = Bundle.main.bundleIdentifier ?? "com.decemberfm.cotton.mac"    enum Account {        static let token = "importer.token"        static let phone = "importer.phone"        static func credentials(_ source: Source) -> String { "importer.credentials.\(source.rawValue)" }    }    static func read(_ account: String) -> String? {        let query: [String: Any] = [            kSecClass as String: kSecClassGenericPassword,            kSecAttrService as String: service,            kSecAttrAccount as String: account,            kSecReturnData as String: true,            kSecMatchLimit as String: kSecMatchLimitOne,        ]        var result: CFTypeRef?        guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess,              let data = result as? Data        else { return nil }        return String(data: data, encoding: .utf8)    }    @discardableResult    static func write(_ account: String, _ value: String) -> Bool {        let base: [String: Any] = [            kSecClass as String: kSecClassGenericPassword,            kSecAttrService as String: service,            kSecAttrAccount as String: account,        ]        let data = Data(value.utf8)        let updated = SecItemUpdate(base as CFDictionary, [kSecValueData as String: data] as CFDictionary)        if updated == errSecSuccess { return true }        guard updated == errSecItemNotFound else { return false }        var add = base        add[kSecValueData as String] = data        add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock        return SecItemAdd(add as CFDictionary, nil) == errSecSuccess    }    static func delete(_ account: String) {        let query: [String: Any] = [            kSecClass as String: kSecClassGenericPassword,            kSecAttrService as String: service,            kSecAttrAccount as String: account,        ]        SecItemDelete(query as CFDictionary)    }    /// Mail: the address and app password, as one item, and the IMAP server's    /// address when the address's own is not known.    struct Credentials: Codable, Sendable {        var address: String        var password: String        var server: String? = nil        /// What the core's `credentials` command takes.        var args: [String: String] {            var args = ["address": address, "password": password]            if let server, !server.isEmpty { args["imapHost"] = server }            return args        }    }    static func credentials(_ source: Source) -> Credentials? {        guard let text = read(Account.credentials(source)) else { return nil }        return try? JSONDecoder().decode(Credentials.self, from: Data(text.utf8))    }    @discardableResult    static func saveCredentials(_ credentials: Credentials, for source: Source) -> Bool {        guard let data = try? JSONEncoder().encode(credentials),              let text = String(data: data, encoding: .utf8)        else { return false }        return write(Account.credentials(source), text)    }}