Branchwell

Graphley / app · graphley.ai / Sources / AnalyticsKit / Keychain.swift

Raw 3.0 KB on d80f63aea8f10988b2fe7107ba87bf71b30173fb
1import Foundation
2import Security
3
4/// Credentials live only here, never in the workspace file or in iCloud data.
5/// Items are synchronizable, so iCloud Keychain carries them to the user's other Macs.
6public enum Keychain {
7 public enum Item: String, CaseIterable, Sendable {
8 case googleRefreshToken = "google.refresh-token"
9 case googleClientID = "google.client-id" // optional: the user's own OAuth client
10 case googleServiceAccount = "google.service-account" // optional: a service account key JSON, used instead of sign-in
11 case appStoreKeyID = "asc.key-id"
12 case appStoreIssuerID = "asc.issuer-id"
13 case appStorePrivateKey = "asc.private-key" // contents of the .p8 file
14 case appStoreVendorNumber = "asc.vendor-number"
15 case youtubeAPIKey = "youtube.api-key"
16 case bingAPIKey = "bing.api-key" // Bing Webmaster Tools → Settings → API access
17 case xBearerToken = "x.bearer-token" // X API app bearer token (public follower count)
18 case instagramToken = "instagram.access-token" // Instagram Graph API token for the account
19 case openTalonConnection = "opentalon.connection" // {"port":…, "token":…} of OpenTalon's local MCP server
20 }
21
22 private static let service = "com.protomota.graphley"
23
24 public static func get(_ item: Item) -> String? {
25 var query = base(item)
26 query[kSecReturnData as String] = true
27 query[kSecMatchLimit as String] = kSecMatchLimitOne
28 var out: AnyObject?
29 guard SecItemCopyMatching(query as CFDictionary, &out) == errSecSuccess, let data = out as? Data else { return nil }
30 return String(data: data, encoding: .utf8)
31 }
32
33 public static func has(_ item: Item) -> Bool { get(item) != nil }
34
35 public static func set(_ value: String, for item: Item) throws {
36 let data = Data(value.utf8)
37 let status = SecItemUpdate(base(item) as CFDictionary, [kSecValueData as String: data] as CFDictionary)
38 if status == errSecItemNotFound {
39 var add = base(item); add[kSecValueData as String] = data
40 add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
41 let s = SecItemAdd(add as CFDictionary, nil)
42 guard s == errSecSuccess else { throw KeychainError(status: s) }
43 } else if status != errSecSuccess {
44 throw KeychainError(status: status)
45 }
46 }
47
48 public static func remove(_ item: Item) { SecItemDelete(base(item) as CFDictionary) }
49
50 private static func base(_ item: Item) -> [String: Any] {
51 [kSecClass as String: kSecClassGenericPassword,
52 kSecAttrService as String: service,
53 kSecAttrAccount as String: item.rawValue,
54 kSecAttrSynchronizable as String: kCFBooleanTrue as Any]
55 }
56}
57
58public struct KeychainError: Error, CustomStringConvertible {
59 public let status: OSStatus
60 public var description: String { "Keychain error \(status): \(SecCopyErrorMessageString(status, nil) as String? ?? "unknown")" }
61}