Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: App/SessionStore.swift3// Description: Who is signed in on this Mac: launch check, passkey sign-in, setup-link enrolment, Touch ID app lock, sign-out, server-side expiry.4import LocalAuthentication5import SwiftUI6import VQuantCore78@Observable final class SessionStore {9 enum Phase: Equatable {10 case starting11 case signedOut12 /// a session exists but the owner must unlock it with Touch ID13 case locked14 case signedIn(Account)15 }1617 private(set) var phase: Phase = .starting18 /// The server could not be reached at launch: the session is assumed valid and cached content is shown.19 private(set) var unverified = false20 private(set) var busy = false21 var message: String?22 private(set) var device: DeviceInfo?2324 @ObservationIgnored private let auth: AuthService25 @ObservationIgnored private let tokens: TokenStore26 @ObservationIgnored private let cache: DiskCache27 @ObservationIgnored private let settings: SettingsStore28 /// Called when a person becomes signed in / stops being signed in (the app starts and stops its stores).29 @ObservationIgnored var onSignedIn: (() -> Void)?30 @ObservationIgnored var onSignedOut: ((_ clearCache: Bool) -> Void)?3132 init(auth: AuthService, tokens: TokenStore, cache: DiskCache, settings: SettingsStore) {33 self.auth = auth; self.tokens = tokens; self.cache = cache; self.settings = settings34 }3536 var account: Account? { if case .signedIn(let a) = phase { a } else { nil } }37 var isSignedIn: Bool { account != nil }3839 func launch() async {40 guard phase == .starting else { return }41 if settings.appLock, cache.read(Account.self, for: "account") != nil { phase = .locked; return }42 await verify()43 }4445 /// Asks the server who this device is signed in as.46 func verify() async {47 guard auth.hasStoredSession else { phase = .signedOut; return }48 do {49 let s = try await auth.session()50 cache.write(s.user, for: "account")51 device = s.device; unverified = false52 enter(s.user)53 } catch let e as APIError where e.kind == .network {54 // offline at launch: the last known account opens the cached content; nothing is assumed about the server's state55 if let a = cache.read(Account.self, for: "account")?.value { unverified = true; enter(a) }56 else { phase = .signedOut; message = e.message }57 } catch let e as APIError where e.kind == .unauthorized {58 // the server ended this session (revoked from another device, or unused for 90 days)59 tokens.clear(); cache.removeAll()60 phase = .signedOut61 message = "This Mac was signed out of VQuant. Sign in again with your passkey."62 } catch {63 phase = .signedOut; message = error.localizedDescription64 }65 }6667 private func enter(_ a: Account) {68 let was = account69 phase = .signedIn(a)70 if was == nil { onSignedIn?() }71 }7273 func signIn() async { await ceremony { try await self.auth.signIn() } }74 func enrol(link: String) async { await ceremony { try await self.auth.enrol(setupLink: link) } }7576 private func ceremony(_ run: @escaping () async throws -> Account) async {77 guard !busy else { return }78 busy = true; message = nil79 defer { busy = false }80 do {81 let a = try await run()82 // a different person signing in on this Mac must never see the previous person's cached data83 if let old = cache.read(Account.self, for: "account")?.value, old.id != a.id { cache.removeAll() }84 cache.write(a, for: "account")85 unverified = false86 enter(a)87 device = try? await auth.session().device88 } catch let e as AuthError where e.code == .cancelled {89 message = nil90 } catch { message = error.localizedDescription }91 }9293 func signOut() async {94 busy = true; defer { busy = false }95 await auth.signOut()96 device = nil97 phase = .signedOut98 onSignedOut?(true)99 }100101 /// The server answered 401 to an authenticated call.102 func serverEndedSession() {103 guard isSignedIn else { return }104 tokens.clear(); device = nil105 phase = .signedOut106 message = "This Mac was signed out of VQuant. Sign in again with your passkey."107 onSignedOut?(true)108 }109110 // MARK: App lock (Touch ID)111112 var biometryName: String {113 let c = LAContext(); _ = c.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)114 switch c.biometryType { case .touchID: return "Touch ID"; case .faceID: return "Face ID"; case .opticID: return "Optic ID"; default: return "your Mac password" }115 }116117 func lock() {118 guard isSignedIn, settings.appLock else { return }119 (tokens as? KeychainTokenStore)?.lock()120 phase = .locked121 onSignedOut?(false)122 }123124 /// Touch ID (or the login password) releases the session token from the Keychain; biometric data stays in the Secure Enclave.125 func unlock() async {126 guard phase == .locked, !busy else { return }127 busy = true; message = nil128 defer { busy = false }129 let context = LAContext()130 context.localizedCancelTitle = "Cancel"131 do {132 try await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: "unlock your VQuant session")133 _ = (tokens as? KeychainTokenStore)?.unlock(with: context)134 phase = .starting135 await verify()136 } catch let e as LAError where e.code == .userCancel || e.code == .appCancel || e.code == .systemCancel {137 message = nil138 } catch { message = "The session could not be unlocked. \(error.localizedDescription)" }139 }140141 /// Turns the lock on or off. Turning it on is confirmed with Touch ID first, so a passer-by cannot change it.142 func setAppLock(_ on: Bool) async -> Bool {143 let context = LAContext()144 do {145 try await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: on ? "protect your VQuant session with \(biometryName)" : "turn off the VQuant lock")146 try (tokens as? KeychainTokenStore)?.setRequireUserPresence(on)147 settings.appLock = on148 return true149 } catch { return false }150 }151}152