Repository Public
1import Foundation2import Security34/// Where secrets (AI provider keys) live. The protocol lets tests use an in-memory store.5protocol SecretStore: Sendable {6 func secret(for account: String) -> String?7 @discardableResult func setSecret(_ value: String?, for account: String) -> Bool8}910/// Generic-password items in the user's keychain. Values are never logged, cached on disk or placed in URLs.11struct KeychainStore: SecretStore {12 var service = "ai.spboucher.spbrowser.provider-keys"1314 private func baseQuery(_ account: String) -> [String: Any] {15 [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account]16 }1718 func secret(for account: String) -> String? {19 var query = baseQuery(account)20 query[kSecReturnData as String] = true21 query[kSecMatchLimit as String] = kSecMatchLimitOne22 var item: CFTypeRef?23 guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess, let data = item as? Data else { return nil }24 return String(data: data, encoding: .utf8)25 }2627 @discardableResult28 func setSecret(_ value: String?, for account: String) -> Bool {29 let query = baseQuery(account)30 guard let value, !value.isEmpty, let data = value.data(using: .utf8) else {31 let status = SecItemDelete(query as CFDictionary)32 return status == errSecSuccess || status == errSecItemNotFound33 }34 let update = SecItemUpdate(query as CFDictionary, [kSecValueData as String: data] as CFDictionary)35 if update == errSecSuccess { return true }36 guard update == errSecItemNotFound else { return false }37 var add = query38 add[kSecValueData as String] = data39 add[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly40 return SecItemAdd(add as CFDictionary, nil) == errSecSuccess41 }42}4344final class InMemorySecretStore: SecretStore, @unchecked Sendable {45 private var values: [String: String] = [:]46 private let lock = NSLock()4748 func secret(for account: String) -> String? { lock.lock(); defer { lock.unlock() }; return values[account] }4950 @discardableResult51 func setSecret(_ value: String?, for account: String) -> Bool {52 lock.lock(); defer { lock.unlock() }53 values[account] = (value?.isEmpty ?? true) ? nil : value54 return true55 }56}57