import Foundation import Security /// Credentials live only here, never in the workspace file or in iCloud data. /// Items are synchronizable, so iCloud Keychain carries them to the user's other Macs. public enum Keychain { public enum Item: String, CaseIterable, Sendable { case googleRefreshToken = "google.refresh-token" case googleClientID = "google.client-id" // optional: the user's own OAuth client case googleServiceAccount = "google.service-account" // optional: a service account key JSON, used instead of sign-in case appStoreKeyID = "asc.key-id" case appStoreIssuerID = "asc.issuer-id" case appStorePrivateKey = "asc.private-key" // contents of the .p8 file case appStoreVendorNumber = "asc.vendor-number" case youtubeAPIKey = "youtube.api-key" case bingAPIKey = "bing.api-key" // Bing Webmaster Tools → Settings → API access case xBearerToken = "x.bearer-token" // X API app bearer token (public follower count) case instagramToken = "instagram.access-token" // Instagram Graph API token for the account case openTalonConnection = "opentalon.connection" // {"port":…, "token":…} of OpenTalon's local MCP server } private static let service = "com.protomota.graphley" public static func get(_ item: Item) -> String? { 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 { 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) { 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.rawValue, 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")" } }