Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Auth/TokenStore.swift3// Description: Where the device session token lives: the Keychain in the app, memory in tests. Nothing else is ever stored.4import Foundation5import LocalAuthentication6import Security7import os89/// Holds the opaque device token issued by the server. The token is the only credential the app keeps: passkey10/// private keys stay in the system authenticator and biometric data never reaches the app.11public protocol TokenStore: Sendable {12 func read() -> String?13 func write(_ token: String) throws14 func clear()15}1617public final class MemoryTokenStore: TokenStore {18 private let value: OSAllocatedUnfairLock<String?>19 public init(_ initial: String? = nil) { value = OSAllocatedUnfairLock(initialState: initial) }20 public func read() -> String? { value.withLock { $0 } }21 public func write(_ token: String) throws { value.withLock { $0 = token } }22 public func clear() { value.withLock { $0 = nil } }23}2425public struct KeychainError: Error, Sendable, LocalizedError {26 public let status: OSStatus27 public var errorDescription: String? { "Keychain error \(status): \((SecCopyErrorMessageString(status, nil) as String?) ?? "unknown")" }28}2930/// Generic-password item, readable only while this Mac is unlocked and never synchronised or migrated to another device.31/// The value is read from the Keychain once and kept in memory for the life of the process (a request is sent every few seconds).32///33/// With `requireUserPresence`, the item is stored behind an access control that asks for Touch ID (or the login34/// password) each time the app starts: the token cannot be read without the owner present.35public final class KeychainTokenStore: TokenStore {36 private let service: String37 private let account: String38 private struct State { var loaded = false; var token: String?; var presence = false }39 private let state = OSAllocatedUnfairLock(initialState: State())4041 public init(service: String, account: String, requireUserPresence: Bool = false) {42 self.service = service; self.account = account43 state.withLock { $0.presence = requireUserPresence }44 }4546 private func base(dataProtection: Bool) -> [CFString: Any] {47 var q: [CFString: Any] = [kSecClass: kSecClassGenericPassword, kSecAttrService: service, kSecAttrAccount: account, kSecAttrSynchronizable: false]48 if dataProtection { q[kSecUseDataProtectionKeychain] = true }49 return q50 }5152 public func read() -> String? {53 state.withLock { s in54 if s.loaded { return s.token }55 s.token = Self.fetch(base(dataProtection: true), context: nil) ?? Self.fetch(base(dataProtection: false), context: nil)56 s.loaded = true57 return s.token58 }59 }6061 /// Reads the item with an authenticated context (after Touch ID): used at launch when the item is presence-protected.62 public func unlock(with context: LAContext) -> String? {63 // the Keychain call happens outside the lock: the context is not Sendable and the read may take a moment64 let token = Self.fetch(base(dataProtection: true), context: context) ?? Self.fetch(base(dataProtection: false), context: context)65 state.withLock { $0.token = token; $0.loaded = true }66 return token67 }6869 /// Forgets the in-memory copy so the next read goes back to the Keychain (app lock).70 public func lock() { state.withLock { $0.loaded = false; $0.token = nil } }7172 public func setRequireUserPresence(_ on: Bool) throws {73 let current = read()74 state.withLock { $0.presence = on }75 if let current { try write(current) }76 }7778 public func write(_ token: String) throws {79 let presence = state.withLock { $0.presence }80 for dp in [true, false] { SecItemDelete(base(dataProtection: dp) as CFDictionary) }81 var status = errSecMissingEntitlement82 // The data-protection keychain needs the app's keychain access group (signed release build); an unsigned83 // development build falls back to the login keychain.84 for dp in [true, false] {85 var q = base(dataProtection: dp)86 q[kSecValueData] = Data(token.utf8)87 q[kSecAttrLabel] = "VQuant session"88 if presence, dp, let ac = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, .userPresence, nil) {89 q[kSecAttrAccessControl] = ac90 } else {91 q[kSecAttrAccessible] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly92 }93 status = SecItemAdd(q as CFDictionary, nil)94 if status == errSecSuccess { break }95 }96 guard status == errSecSuccess else { throw KeychainError(status: status) }97 state.withLock { $0.token = token; $0.loaded = true }98 }99100 public func clear() {101 for dp in [true, false] { SecItemDelete(base(dataProtection: dp) as CFDictionary) }102 state.withLock { $0.token = nil; $0.loaded = true }103 }104105 private static func fetch(_ base: [CFString: Any], context: LAContext?) -> String? {106 var q = base107 q[kSecReturnData] = true108 q[kSecMatchLimit] = kSecMatchLimitOne109 if let context { q[kSecUseAuthenticationContext] = context }110 else {111 // never raise a system prompt from an ordinary read: a presence-protected item is read through unlock(with:)112 let silent = LAContext(); silent.interactionNotAllowed = true113 q[kSecUseAuthenticationContext] = silent114 }115 var out: CFTypeRef?116 guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess, let d = out as? Data, let s = String(data: d, encoding: .utf8), !s.isEmpty else { return nil }117 return s118 }119}120