Branchwell

Graphley / app · graphley.ai / Sources / OwnerMetricsKit / SessionKeychain.swift

Raw 2.1 KB on d69ca9c4c8ff088be085e80dbb7478e9463bddf8
1import Foundation
2import Security
3
4/// Keeps the passkey sign-in session in this device's Keychain (never synced).
5public enum SessionKeychain {
6 private static func item(_ account: String) -> [String: Any] {
7 [
8 kSecClass as String: kSecClassGenericPassword,
9 kSecAttrService as String: "com.protomota.graphley.owner-metrics",
10 kSecAttrAccount as String: account,
11 kSecAttrSynchronizable as String: false,
12 kSecUseDataProtectionKeychain as String: true,
13 ]
14 }
15
16 public static func read() throws -> String? {
17 var query = item("session")
18 query[kSecReturnData as String] = true
19 var result: CFTypeRef?
20 let status = SecItemCopyMatching(query as CFDictionary, &result)
21 if status == errSecItemNotFound { return nil }
22 guard status == errSecSuccess, let data = result as? Data, let session = String(data: data, encoding: .utf8),
23 MetricsClient.isValidSession(session) else { throw MetricsError.keychain }
24 return session
25 }
26
27 public static func save(_ session: String) throws {
28 guard MetricsClient.isValidSession(session) else { throw MetricsError.invalidResponse }
29 let data = Data(session.utf8)
30 var status = SecItemUpdate(item("session") as CFDictionary, [kSecValueData as String: data] as CFDictionary)
31 if status == errSecItemNotFound {
32 var record = item("session")
33 record[kSecValueData as String] = data
34 record[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly
35 status = SecItemAdd(record as CFDictionary, nil)
36 }
37 guard status == errSecSuccess else { throw MetricsError.keychain }
38 }
39
40 public static func remove() throws {
41 let status = SecItemDelete(item("session") as CFDictionary)
42 guard status == errSecSuccess || status == errSecItemNotFound else { throw MetricsError.keychain }
43 }
44
45 /// The old pasted viewer token is no longer accepted; drop it from the Keychain.
46 public static func removeLegacyViewerToken() {
47 SecItemDelete(item("viewer") as CFDictionary)
48 }
49}