import Foundation import Security /// The session token a passkey sign-in returns, for the curator or a moderator. It lives only in the /// Keychain, never in defaults, files or MCP arguments. The MCP process (the same executable) reads it /// from here too. Nobody types or pastes it: people sign in with a passkey. public enum TokenStore { public static let service = "com.protomota.jobley" static let account = "api-token" /// Tests, screenshots and unsigned dev builds can pass a dev server session in the environment instead. public static var environmentToken: String? { let value = ProcessInfo.processInfo.environment["JOBLEY_TOKEN"] return (value?.isEmpty ?? true) ? nil : value } public static func load() -> String? { if let environmentToken { return environmentToken } var query = base 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 save(_ token: String) throws { let data = Data(token.trimmingCharacters(in: .whitespacesAndNewlines).utf8) let status = SecItemUpdate(base as CFDictionary, [kSecValueData as String: data] as CFDictionary) if status == errSecItemNotFound { var add = base add[kSecValueData as String] = data add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock let added = SecItemAdd(add as CFDictionary, nil) guard added == errSecSuccess else { throw KeychainError(status: added) } } else if status != errSecSuccess { throw KeychainError(status: status) } } public static func remove() { SecItemDelete(base as CFDictionary) } private static var base: [String: Any] { [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account] } } public struct KeychainError: Error, LocalizedError { public let status: OSStatus public var errorDescription: String? { "The Keychain refused to save your sign-in (\(status))." } }