SPB Git

Repository Public

KeychainStore.swift 4.1 KB 88 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatSecurity/Sources/KeychainStore.swift3// Description: Generic-password Keychain storage (device-only, available after first unlock) with typed errors.4import Foundation5import Security67public enum KeychainError: LocalizedError, Sendable, Equatable {8    case notAvailable(OSStatus)      // no keychain entitlement / no keychain in this process9    case interactionNotAllowed10    case unexpectedData11    case status(OSStatus)12    public var errorDescription: String? {13        switch self {14        case .notAvailable(let s): "The Keychain is not available to this process (status \(s))."15        case .interactionNotAllowed: "The Keychain is locked."16        case .unexpectedData: "The Keychain returned data in an unexpected format."17        case .status(let s): (SecCopyErrorMessageString(s, nil) as String?) ?? "Keychain error \(s)."18        }19    }20    static func from(_ status: OSStatus) -> KeychainError {21        switch status {22        case errSecMissingEntitlement, errSecNotAvailable, errSecNoDefaultKeychain: .notAvailable(status)23        case errSecInteractionNotAllowed: .interactionNotAllowed24        default: .status(status)25        }26    }27}2829public struct KeychainStore: Sendable {30    public let service: String31    public let accessGroup: String?32    public init(service: String = "ai.spboucher.localchat", accessGroup: String? = nil) { self.service = service; self.accessGroup = accessGroup }3334    private func base(_ account: String?) -> [String: Any] {35        var q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service]36        if let account { q[kSecAttrAccount as String] = account }37        if let accessGroup { q[kSecAttrAccessGroup as String] = accessGroup }38        return q39    }4041    public func data(for account: String) throws -> Data? {42        var q = base(account); q[kSecReturnData as String] = true; q[kSecMatchLimit as String] = kSecMatchLimitOne43        var out: CFTypeRef?44        let status = SecItemCopyMatching(q as CFDictionary, &out)45        if status == errSecItemNotFound { return nil }46        guard status == errSecSuccess else { throw KeychainError.from(status) }47        guard let data = out as? Data else { throw KeychainError.unexpectedData }48        return data49    }5051    public func string(for account: String) throws -> String? {52        guard let d = try data(for: account) else { return nil }53        guard let s = String(data: d, encoding: .utf8) else { throw KeychainError.unexpectedData }54        return s55    }5657    public func set(_ data: Data, for account: String) throws {58        let attrs: [String: Any] = [kSecValueData as String: data, kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly]59        var status = SecItemUpdate(base(account) as CFDictionary, attrs as CFDictionary)60        if status == errSecItemNotFound {61            var q = base(account); attrs.forEach { q[$0.key] = $0.value }62            status = SecItemAdd(q as CFDictionary, nil)63        }64        guard status == errSecSuccess else { throw KeychainError.from(status) }65    }6667    public func set(_ string: String, for account: String) throws { try set(Data(string.utf8), for: account) }6869    @discardableResult70    public func delete(_ account: String) throws -> Bool {71        let status = SecItemDelete(base(account) as CFDictionary)72        if status == errSecItemNotFound { return false }73        guard status == errSecSuccess else { throw KeychainError.from(status) }74        return true75    }7677    public func accounts() throws -> [String] {78        var q = base(nil); q[kSecReturnAttributes as String] = true; q[kSecMatchLimit as String] = kSecMatchLimitAll79        var out: CFTypeRef?80        let status = SecItemCopyMatching(q as CFDictionary, &out)81        if status == errSecItemNotFound { return [] }82        guard status == errSecSuccess else { throw KeychainError.from(status) }83        return ((out as? [[String: Any]]) ?? []).compactMap { $0[kSecAttrAccount as String] as? String }.sorted()84    }8586    public func deleteAll() throws { for a in try accounts() { try delete(a) } }87}88
Files main
Menu

Theme