Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: App/AppModel.swift3// Description: The app's state: session phase, connectivity, and the read-only data every screen shares (networks, addresses, portfolio, activity, security). It never holds a key or a seed; the only secret it touches is the session token, which lives in the keychain.4import Foundation5import Network6import OSLog7import SPWalletCore89let log = Logger(subsystem: AppEnvironment.keychainService, category: "app")1011/// A value with where it comes from: fresh from the server, or a local snapshot with its date.12struct Sourced<T: Sendable>: Sendable {13 var value: T14 var fetchedAt: Date15 var fromCache: Bool16}1718@MainActor @Observable final class AppModel {19 enum Phase: Equatable {20 case launching21 /// The wallet has no owner passkey yet: setup is done on the signer's terms, not from this app (except the development stack).22 case setupRequired23 case signedOut24 case signedIn25 /// Read-only consultation of the last synchronized data, without a session. No operation is possible.26 case offlineBrowse27 }2829 let configuration: APIConfiguration30 let client: APIClient31 let auth: AuthAPI32 let wallet: WalletAPI33 let transfers: TransfersAPI34 let authenticator: PasskeyAuthenticator35 let lock = AppLock()3637 private(set) var phase: Phase = .launching38 /// The Mac has a network path. False = certainly offline; true says nothing about the wallet being reachable.39 private(set) var pathOnline = true40 /// The last request to the wallet failed for a transport reason.41 private(set) var serverUnreachable = false42 private(set) var busy = false43 var gateMessage: String?4445 private(set) var networks: Sourced<[SPWalletCore.Network]>?46 private(set) var accounts: Sourced<Accounts>?47 private(set) var portfolio: Sourced<Portfolio>?48 private(set) var activity: Sourced<[ActivityItem]>?49 private(set) var security: Sourced<SecurityOverview>?50 private(set) var health: Sourced<HealthReady>?51 private(set) var addressBook: [AddressBookEntry] = []52 /// Until the server answers: its own defaults (French, CAD, balances shown, prices on).53 private(set) var settings: WalletSettings = try! APICoding.decoder().decode(WalletSettings.self, from: Data(#"{"locale":"fr","currency":"CAD","hideBalances":false,"prices":true}"#.utf8))54 private(set) var hasSnapshots = false5556 private var monitor: NWPathMonitor?57 private var pollTask: Task<Void, Never>?58 private var eventsTask: Task<Void, Never>?59 private let snapshots = SnapshotStore.shared6061 var isOffline: Bool { !pathOnline || serverUnreachable }62 /// Operations (anything that prepares, approves or changes something) need a live session and a reachable wallet.63 var canOperate: Bool { phase == .signedIn && !isOffline }64 var currency: FiatCurrency { settings.currency }6566 init() {67 configuration = AppEnvironment.configuration68 client = APIClient(configuration: configuration, tokens: KeychainTokenStore(service: AppEnvironment.keychainService))69 auth = AuthAPI(client); wallet = WalletAPI(client); transfers = TransfersAPI(client)70 #if SPW_DEV71 authenticator = DevPasskey(origin: configuration.originHeader)72 #else73 authenticator = SystemPasskeyAuthenticator()74 #endif75 }7677 // MARK: - Lifecycle7879 func start() async {80 guard monitor == nil else { return }81 let m = NWPathMonitor(); monitor = m82 m.pathUpdateHandler = { [weak self] path in83 let ok = path.status == .satisfied84 Task { @MainActor in85 guard let self, self.pathOnline != ok else { return }86 self.pathOnline = ok87 if ok, self.phase == .signedIn { await self.refreshAll() }88 }89 }90 m.start(queue: DispatchQueue(label: "spw.path"))91 eventsTask = Task { [weak self] in92 guard let self else { return }93 for await e in await self.client.events() { if e == .unauthenticated { self.sessionLost() } }94 }95 await loadSnapshots()96 await resolvePhase()97 }9899 private func resolvePhase() async {100 do {101 let s = try await auth.state()102 serverUnreachable = false103 if s.setupRequired { phase = .setupRequired }104 else if s.authenticated { await enterSignedIn() }105 else { phase = .signedOut }106 } catch {107 noteTransport(error)108 phase = .signedOut109 gateMessage = isOffline ? "Le portefeuille est injoignable. Vérifiez la connexion, ou consultez les dernières données synchronisées." : describe(error)110 }111 }112113 func retryConnection() async { gateMessage = nil; await resolvePhase() }114115 func signIn() async {116 guard !busy else { return }117 busy = true; gateMessage = nil; defer { busy = false }118 do {119 try await auth.login(with: authenticator)120 serverUnreachable = false121 await enterSignedIn()122 } catch PasskeyError.cancelled { gateMessage = nil }123 catch { noteTransport(error); gateMessage = describe(error) }124 }125126 /// The shell appears at once (with the local snapshot when there is one); the first reads complete in the background.127 private func enterSignedIn() async {128 phase = .signedIn129 startPolling()130 Task { await refreshAll() }131 }132133 func signOut(eraseLocalData: Bool) async {134 pollTask?.cancel(); pollTask = nil135 await auth.logout()136 if eraseLocalData { await eraseLocal() }137 phase = .signedOut; gateMessage = nil138 }139140 func revokeAllSessions() async throws {141 try await auth.revokeAllSessions()142 pollTask?.cancel(); pollTask = nil143 phase = .signedOut; gateMessage = "Toutes les sessions ont été révoquées."144 }145146 private func sessionLost() {147 guard phase == .signedIn else { return }148 pollTask?.cancel(); pollTask = nil149 phase = .signedOut150 gateMessage = "La session a expiré (30 minutes d’inactivité ou 12 heures). Reconnectez-vous avec votre passkey."151 }152153 /// Read-only consultation of the snapshots; the Mac's owner is verified first.154 func browseOffline() async {155 guard hasSnapshots else { return }156 if AppLock.available { await lock.unlockForBrowse(); if lock.browseDenied { return } }157 phase = .offlineBrowse158 }159 func leaveOfflineBrowse() async { phase = .signedOut; await resolvePhase() }160161 func eraseLocal() async {162 await snapshots.eraseAll()163 networks = nil; accounts = nil; portfolio = nil; activity = nil; security = nil; health = nil; addressBook = []; hasSnapshots = false164 }165166 #if SPW_DEV167 /// Development stack only: enrol the software passkey as the owner with the stack's one-time setup token.168 func devSetup(token: String) async {169 busy = true; defer { busy = false }170 do {171 struct Options: Decodable, Sendable { let challengeId: String; let options: PasskeyCreationOptions }172 let o: Options = try await client.post("/auth/setup/options")173 let reg = try await authenticator.register(o.options, rpId: configuration.rpId)174 struct Body: Encodable, Sendable { let challengeId: String; let response: PasskeyRegistration; let setupToken: String; let label: String }175 let _: OKResponse = try await client.post("/auth/setup/verify", body: Body(challengeId: o.challengeId, response: reg, setupToken: token, label: "SP Wallet Dev"))176 await enterSignedIn()177 } catch { gateMessage = describe(error) }178 }179 #endif180181 // MARK: - Data182183 private func startPolling() {184 pollTask?.cancel()185 pollTask = Task { [weak self] in186 var tick = 0187 while !Task.isCancelled {188 try? await Task.sleep(for: .seconds(30))189 guard let self, self.phase == .signedIn, !Task.isCancelled else { return }190 // nothing is fetched while the app is in the background or the Mac is offline191 guard AppActivity.isActive, self.pathOnline else { continue }192 tick += 1193 await self.refreshPortfolio()194 if tick % 2 == 0 { await self.refreshActivity() }195 if tick % 4 == 0 { await self.refreshHealth() }196 }197 }198 }199200 func refreshAll() async {201 guard phase == .signedIn else { return }202 async let a: Void = refreshStatic()203 async let b: Void = refreshPortfolio()204 async let c: Void = refreshActivity()205 async let d: Void = refreshSecurity()206 async let e: Void = refreshHealth()207 _ = await (a, b, c, d, e)208 }209210 private func fetch<T: Codable & Sendable>(_ key: String, _ call: @Sendable () async throws -> T) async -> Sourced<T>? {211 do {212 let v = try await call()213 serverUnreachable = false214 await snapshots.save(v, as: key); hasSnapshots = true215 return Sourced(value: v, fetchedAt: Date(), fromCache: false)216 } catch { noteTransport(error); return nil }217 }218219 func refreshStatic() async {220 let w = wallet221 if let v = await fetch("networks", { try await w.networks() }) { networks = v } else { networks?.fromCache = true }222 if let v = await fetch("accounts", { try await w.accounts() }) { accounts = v } else { accounts?.fromCache = true }223 if let s = try? await w.settings() { settings = s; await snapshots.save(s, as: "settings") }224 if let b = try? await w.addressBook() { addressBook = b; await snapshots.save(b, as: "addressbook") }225 }226 func refreshPortfolio() async {227 let w = wallet228 if let v = await fetch("portfolio", { try await w.portfolio() }) { portfolio = v; await ValueHistory.shared.record(v.value, currency: settings.currency) } else { portfolio?.fromCache = true }229 }230 func refreshActivity() async {231 let w = wallet232 if let v = await fetch("activity", { try await w.activity(limit: 500) }) { activity = v } else { activity?.fromCache = true }233 }234 func refreshSecurity() async {235 let w = wallet236 if let v = await fetch("security", { try await w.securityOverview() }) { security = v } else { security?.fromCache = true }237 }238 func refreshHealth() async {239 let w = wallet240 if let v = await fetch("health", { try await w.healthReady() }) { health = v } else { health?.fromCache = true }241 }242 func refreshAddressBook() async { if let b = try? await wallet.addressBook() { addressBook = b } }243244 func update(settings s: WalletSettings) async {245 do { settings = try await wallet.update(settings: s) } catch { noteTransport(error) }246 }247248 private func loadSnapshots() async {249 func cached<T: Codable & Sendable>(_ key: String) async -> Sourced<T>? {250 guard let s: Snapshot<T> = await snapshots.load(key) else { return nil }251 return Sourced(value: s.value, fetchedAt: s.savedAt, fromCache: true)252 }253 networks = await cached("networks"); accounts = await cached("accounts"); portfolio = await cached("portfolio")254 activity = await cached("activity"); security = await cached("security"); health = await cached("health")255 if let s: Snapshot<WalletSettings> = await snapshots.load("settings") { settings = s.value }256 if let b: Snapshot<[AddressBookEntry]> = await snapshots.load("addressbook") { addressBook = b.value }257 hasSnapshots = portfolio != nil || accounts != nil258 }259260 // MARK: - Errors261262 private func noteTransport(_ error: Error) {263 if let e = error as? APIError, e.isOffline { serverUnreachable = true }264 else if (error as? URLError) != nil { serverUnreachable = true }265 }266267 func describe(_ error: Error) -> String {268 switch error {269 case PasskeyError.cancelled: return "Demande annulée."270 case PasskeyError.noCredential: return "Aucune passkey de ce portefeuille n’est disponible sur ce Mac. Vérifiez le trousseau iCloud, ou approuvez avec un appareil à proximité."271 case PasskeyError.notAvailable(let s): return "Ce Mac ne peut pas utiliser les passkeys de \(configuration.rpId) pour l’instant (\(s))."272 case PasskeyError.failed(let s): return "Passkey : \(s)"273 case let e as ApprovalError: return ErrorText.approval(e)274 case let e as APIError: return ErrorText.api(e)275 default: return error.localizedDescription276 }277 }278279 // MARK: - Lookups280281 func network(_ id: String) -> SPWalletCore.Network? { networks?.value.first { $0.id == id } }282 func address(on network: String) -> String? { accounts?.value.accounts.first { $0.network == network }?.address }283 func price(_ symbol: String) -> MarketPrice? { settings.prices ? portfolio?.value.prices?[symbol] : nil }284}285286/// Whether the app is frontmost enough to deserve network traffic (set by the app delegate).287@MainActor enum AppActivity { static var isActive = true }288