Jobley / app / Sources / JobleyKit / Keychain.swift
| 1 | import Foundation |
| 2 | import Security |
| 3 | |
| 4 | /// The session token a passkey sign-in returns, for the curator or a moderator. It lives only in the |
| 5 | /// Keychain, never in defaults, files or MCP arguments. The MCP process (the same executable) reads it |
| 6 | /// from here too. Nobody types or pastes it: people sign in with a passkey. |
| 7 | public enum TokenStore { |
| 8 | public static let service = "com.protomota.jobley" |
| 9 | static let account = "api-token" |
| 10 | |
| 11 | /// Tests, screenshots and unsigned dev builds can pass a dev server session in the environment instead. |
| 12 | public static var environmentToken: String? { |
| 13 | let value = ProcessInfo.processInfo.environment["JOBLEY_TOKEN"] |
| 14 | return (value?.isEmpty ?? true) ? nil : value |
| 15 | } |
| 16 | |
| 17 | public static func load() -> String? { |
| 18 | if let environmentToken { return environmentToken } |
| 19 | var query = base |
| 20 | query[kSecReturnData as String] = true |
| 21 | query[kSecMatchLimit as String] = kSecMatchLimitOne |
| 22 | var out: AnyObject? |
| 23 | guard SecItemCopyMatching(query as CFDictionary, &out) == errSecSuccess, let data = out as? Data else { return nil } |
| 24 | return String(data: data, encoding: .utf8) |
| 25 | } |
| 26 | |
| 27 | public static func save(_ token: String) throws { |
| 28 | let data = Data(token.trimmingCharacters(in: .whitespacesAndNewlines).utf8) |
| 29 | let status = SecItemUpdate(base as CFDictionary, [kSecValueData as String: data] as CFDictionary) |
| 30 | if status == errSecItemNotFound { |
| 31 | var add = base |
| 32 | add[kSecValueData as String] = data |
| 33 | add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock |
| 34 | let added = SecItemAdd(add as CFDictionary, nil) |
| 35 | guard added == errSecSuccess else { throw KeychainError(status: added) } |
| 36 | } else if status != errSecSuccess { |
| 37 | throw KeychainError(status: status) |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | public static func remove() { SecItemDelete(base as CFDictionary) } |
| 42 | |
| 43 | private static var base: [String: Any] { |
| 44 | [kSecClass as String: kSecClassGenericPassword, |
| 45 | kSecAttrService as String: service, |
| 46 | kSecAttrAccount as String: account] |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | public struct KeychainError: Error, LocalizedError { |
| 51 | public let status: OSStatus |
| 52 | public var errorDescription: String? { "The Keychain refused to save your sign-in (\(status))." } |
| 53 | } |