import Foundation import Security /// Credentials live only here, never in the workspace files, iCloud data or MCP arguments. /// Items are synchronizable, so iCloud Keychain carries them to the user's other Macs. public enum Keychain { public enum Item: Sendable, Hashable { case plaidClientID, plaidSecret case claudeKey, openAIKey /// A connection's own secret: the SimpleFIN access URL or a Plaid access token. case connection(String) var account: String { switch self { case .plaidClientID: "plaid.client-id" case .plaidSecret: "plaid.secret" case .claudeKey: "ask.claude-key" case .openAIKey: "ask.openai-key" case .connection(let id): "connection.\(id)" } } } public static let service = "com.protomota.bucksley" /// Tests and the unsigned dev build use an in-memory store instead of the real Keychain. nonisolated(unsafe) public static var memory: [String: String]? = ProcessInfo.processInfo.environment["BUCKSLEY_MEMORY_KEYCHAIN"] != nil ? [:] : nil private static let memoryLock = NSLock() public static func get(_ item: Item) -> String? { if memory != nil { memoryLock.lock(); defer { memoryLock.unlock() }; return memory?[item.account] } var query = base(item) query[kSecReturnData as String] = true query[kSecMatchLimit as String] = kSecMatchLimitOne var out: AnyObject? guard SecItemCopyMatching(query as CFDictionary, &out) == errSecSuccess, let data = out as? Data else { return nil } return String(data: data, encoding: .utf8) } public static func has(_ item: Item) -> Bool { get(item) != nil } public static func set(_ value: String, for item: Item) throws { if memory != nil { memoryLock.lock(); memory?[item.account] = value; memoryLock.unlock(); return } let data = Data(value.utf8) let status = SecItemUpdate(base(item) as CFDictionary, [kSecValueData as String: data] as CFDictionary) if status == errSecItemNotFound { var add = base(item); add[kSecValueData as String] = data add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock let s = SecItemAdd(add as CFDictionary, nil) guard s == errSecSuccess else { throw KeychainError(status: s) } } else if status != errSecSuccess { throw KeychainError(status: status) } } public static func remove(_ item: Item) { if memory != nil { memoryLock.lock(); memory?[item.account] = nil; memoryLock.unlock(); return } SecItemDelete(base(item) as CFDictionary) } private static func base(_ item: Item) -> [String: Any] { [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: item.account, kSecAttrSynchronizable as String: kCFBooleanTrue as Any] } } public struct KeychainError: Error, CustomStringConvertible { public let status: OSStatus public var description: String { "Keychain error \(status): \(SecCopyErrorMessageString(status, nil) as String? ?? "unknown")" } }