import Foundation import Security /// Keeps the passkey sign-in session in this device's Keychain (never synced). public enum SessionKeychain { private static func item(_ account: String) -> [String: Any] { [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: "com.protomota.graphley.owner-metrics", kSecAttrAccount as String: account, kSecAttrSynchronizable as String: false, kSecUseDataProtectionKeychain as String: true, ] } public static func read() throws -> String? { var query = item("session") query[kSecReturnData as String] = true var result: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &result) if status == errSecItemNotFound { return nil } guard status == errSecSuccess, let data = result as? Data, let session = String(data: data, encoding: .utf8), MetricsClient.isValidSession(session) else { throw MetricsError.keychain } return session } public static func save(_ session: String) throws { guard MetricsClient.isValidSession(session) else { throw MetricsError.invalidResponse } let data = Data(session.utf8) var status = SecItemUpdate(item("session") as CFDictionary, [kSecValueData as String: data] as CFDictionary) if status == errSecItemNotFound { var record = item("session") record[kSecValueData as String] = data record[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly status = SecItemAdd(record as CFDictionary, nil) } guard status == errSecSuccess else { throw MetricsError.keychain } } public static func remove() throws { let status = SecItemDelete(item("session") as CFDictionary) guard status == errSecSuccess || status == errSecItemNotFound else { throw MetricsError.keychain } } /// The old pasted viewer token is no longer accepted; drop it from the Keychain. public static func removeLegacyViewerToken() { SecItemDelete(item("viewer") as CFDictionary) } }