SPB Git

Repository Public

AppModel.swift 22.2 KB 527 lines swift

1// The one observable object behind every screen: it owns the engine, mirrors its snapshots for SwiftUI and carries2// the behaviours that are the same on macOS and iOS (unlock, lock, auto-lock, clipboard, live events, AutoFill3// identities, ingestion of items created by the extension).4import AuthenticationServices5import Foundation6import LocalAuthentication7import Observation8import SharedVaultKit9#if os(macOS)10import AppKit11#else12import UIKit13#endif1415struct Toast: Identifiable, Equatable {16    enum Kind { case ok, info, error }17    let id = UUID()18    var text: String19    var kind: Kind = .ok20}2122@MainActor23@Observable24final class AppModel {25    enum KitReason: Equatable { case new, rotated, rekeyed }26    enum Phase: Equatable {27        case loading, welcome, join(invite: String), pairing, recover, locked, main28        case recoveryKit(key: String, reason: KitReason)29        case fatal(String)30    }3132    // ── engine ──33    @ObservationIgnored let engine: VaultEngine34    @ObservationIgnored let keyStore: any DeviceKeyStore35    let prefs = Preferences()3637    // ── snapshots ──38    private(set) var phase: Phase = .loading39    private(set) var items: [ItemView] = []40    private(set) var vaults: [VaultView] = []41    /// nil until the first snapshot (SyncHealth has no public initialiser).42    private(set) var health: SyncHealth?43    private(set) var account: AccountView?44    private(set) var identity: DeviceIdentity?45    /// Bumped by live events so that the matching screens reload.46    private(set) var devicesTick = 047    private(set) var sharesTick = 048    private(set) var approvalsTick = 049    private(set) var activityTick = 050    /// Number of pairing pokes received while unlocked (badge on Devices).51    var pairingHint = false5253    // ── UI state shared with menus and commands ──54    var section: SidebarSection = .allItems55    var selectedItemID: String?56    var query = ""57    var editor: EditorRequest?58    var searchFocusTick = 059    /// Bumped by `reveal`: the iPhone layout switches to the Items tab.60    private(set) var revealTick = 061    var toast: Toast?62    /// Message shown on the welcome / locked screens (e.g. "this device was removed").63    var notice: String?64    var busy = false65    /// True while the app must hide its content (inactive, app switcher).66    var covered = false6768    @ObservationIgnored private var changesTask: Task<Void, Never>?69    @ObservationIgnored private var eventsTask: Task<Void, Never>?70    @ObservationIgnored private var lockTask: Task<Void, Never>?71    @ObservationIgnored private var identitiesTask: Task<Void, Never>?72    @ObservationIgnored private var lastActivity = Date()73    /// Called after the item list changed while unlocked (macOS: optional Spotlight index).74    @ObservationIgnored var onItemsChanged: (@MainActor ([ItemView]) -> Void)?75    /// Called after the vault locked (macOS: Spotlight index stays, menus update).76    @ObservationIgnored var onLocked: (@MainActor () -> Void)?7778    static let shared = AppModel()7980    init() {81        #if SPV_DEV82        DevSupport.resetIfAsked()83        #endif84        var failure: String?85        var store: any LocalStore = MemoryStore()86        var keys: any DeviceKeyStore = InMemoryKeyStore()87        do {88            store = try AppEnvironment.makeStore()89            keys = try AppEnvironment.makeKeyStore()90        } catch { failure = "SP Vault cannot open its local storage: \(error.localizedDescription)" }91        keyStore = keys92        let passkeys: any PasskeyProvider93        #if SPV_DEV94        passkeys = (try? DevSupport.makePasskeys()) ?? DevSoftwarePasskeys(file: FileManager.default.temporaryDirectory.appendingPathComponent("spv-dev-passkeys.json"), origin: AppEnvironment.origin)95        #else96        passkeys = SystemPasskeys(relyingParty: AppEnvironment.relyingParty) { AppModel.presentationAnchor() }97        #endif98        engine = VaultEngine(transport: URLSessionTransport(baseURL: AppEnvironment.baseURL), store: store, keyStore: keys, passkeys: passkeys, platformLabel: AppEnvironment.deviceLabel)99        if let failure { phase = .fatal(failure) }100    }101102    static func presentationAnchor() -> ASPresentationAnchor {103        #if os(macOS)104        return NSApp.keyWindow ?? NSApp.mainWindow ?? NSApp.windows.first ?? ASPresentationAnchor()105        #else106        let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }107        return scenes.flatMap(\.windows).first(where: \.isKeyWindow) ?? scenes.first.map { ASPresentationAnchor(windowScene: $0) } ?? ASPresentationAnchor()108        #endif109    }110111    // ── lifecycle ──112    func start() async {113        guard changesTask == nil else { return }114        if case .fatal = phase { return }115        do {116            let state = try await engine.load()117            identity = await engine.deviceIdentity118            account = await engine.accountInfo119            if phase == .loading { phase = state == .none ? .welcome : .locked }120        } catch { phase = .fatal("SP Vault cannot read its local state: \(error.localizedDescription)") }121        let changes = engine.changes122        changesTask = Task { [weak self] in123            for await _ in changes { await self?.refresh() }124        }125        startAutoLockTimer()126        #if SPV_DEV127        DevScenario.runIfAsked(self)128        #endif129    }130131    private func refresh() async {132        let unlocked = await engine.isUnlocked133        let list = await engine.list(), vs = await engine.vaults(), h = await engine.syncHealth()134        identity = await engine.deviceIdentity135        account = await engine.accountInfo136        health = h137        vaults = vs138        let changed = list != items139        items = list140        if !unlocked {141            if phase == .main { didLock() }142            if identity == nil, phase == .locked || phase == .main { phase = .welcome }143        } else if changed {144            scheduleIdentitySync()145            onItemsChanged?(list)146        }147        if let id = selectedItemID, !list.contains(where: { $0.id == id }) { selectedItemID = nil }148    }149150    var isUnlocked: Bool { phase == .main }151    var handle: String { identity?.handle ?? account?.handle ?? "" }152    func setPhase(_ p: Phase) { phase = p }153154    // ── derived lists ──155    func items(in section: SidebarSection) -> [ItemView] {156        var list = items.filter { section.contains($0) }157        let q = query.trimmingCharacters(in: .whitespaces)158        if !q.isEmpty { list = list.filter { SPV1.matchesQuery(haystack: SPV1.searchText($0.item), query: q) } }159        return list.sorted { ItemMeta.displayTitle($0.item).localizedCaseInsensitiveCompare(ItemMeta.displayTitle($1.item)) == .orderedAscending }160    }161162    func count(in section: SidebarSection) -> Int { items.reduce(0) { $0 + (section.contains($1) ? 1 : 0) } }163    func item(_ id: String?) -> ItemView? { id.flatMap { id in items.first { $0.id == id } } }164    var selectedItem: ItemView? { item(selectedItemID) }165    func vault(_ id: String) -> VaultView? { vaults.first { $0.vaultId == id } }166    var writableVaults: [VaultView] { vaults.filter { $0.role != .reader } }167    var defaultVaultId: String? {168        if case .vault(let id) = section, vault(id)?.role != .reader { return id }169        return writableVaults.first?.vaultId170    }171172    // ── errors ──173    /// A sentence for the user; nil when the user simply cancelled.174    func errorText(_ error: Error) -> String? {175        if error is CancellationError { return nil }176        if let e = error as? PasskeyError, e == .cancelled { return nil }177        if let e = error as? LAError, [.userCancel, .appCancel, .systemCancel].contains(e.code) { return nil }178        if let e = error as? ApiError {179            if e.isOffline { return "The server cannot be reached. Check the connection and try again." }180            switch e.code {181            case "rate_limited": return "Too many attempts. Wait a moment and try again."182            case "invite_invalid", "invalid_invite": return "This invitation is not valid or has expired. Ask for a new one."183            case "handle_taken": return "This handle is already taken."184            case "reauth_required": return "This action needs a fresh confirmation. Try again."185            default: return e.message == e.code ? "The server refused the request (\(e.code))." : e.message186            }187        }188        if let e = error as? VaultError { return VaultErrorText.describe(e) }189        return (error as? LocalizedError)?.errorDescription ?? error.localizedDescription190    }191192    /// Runs an action, shows `success` as a toast, returns the error text (nil on success or cancellation).193    @discardableResult194    func perform(_ success: String? = nil, _ op: () async throws -> Void) async -> String? {195        busy = true196        defer { busy = false }197        do {198            try await op()199            if let success { show(success) }200            return nil201        } catch {202            if let e = error as? ApiError, e.code == "device_revoked" {203                notice = e.message204                phase = .welcome205                return nil206            }207            return errorText(error)208        }209    }210211    /// Like `perform`, but failures are shown as an error toast (actions without a form to show them in).212    func act(_ success: String? = nil, _ op: () async throws -> Void) async {213        if let message = await perform(success, op) { show(message, kind: .error) }214    }215216    func show(_ text: String, kind: Toast.Kind = .ok) {217        let t = Toast(text: text, kind: kind)218        toast = t219        #if os(macOS)220        NSAccessibility.post(element: NSApp as Any, notification: .announcementRequested, userInfo: [.announcement: text, .priority: NSAccessibilityPriorityLevel.high.rawValue])221        #else222        UIAccessibility.post(notification: .announcement, argument: text)223        #endif224        Task { [weak self] in225            try? await Task.sleep(for: .seconds(kind == .error ? 6 : 2.8))226            if self?.toast?.id == t.id { self?.toast = nil }227        }228    }229230    // ── presence ──231    /// Unlocks the engine with a context that already passed biometrics / passcode, so that one prompt covers both232    /// device keys, and opens the items the AutoFill extension left behind with the same context. Runs off the main233    /// actor so that the (non-Sendable) context can be handed over to the engine. Dev builds use software keys and never prompt.234    nonisolated private static func unlockEngine(_ engine: VaultEngine, keyStore: any DeviceKeyStore, reason: String) async throws -> (pending: [PendingItems.Entry], queue: PendingItems?) {235        #if SPV_DEV236        let ctx: LAContext? = nil237        #else238        let ctx: LAContext? = LAContext()239        if let ctx {240            ctx.touchIDAuthenticationAllowableReuseDuration = 10241            ctx.localizedCancelTitle = "Cancel"242            try await ctx.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)243        }244        #endif245        // items created by the AutoFill extension while the app was closed (see PendingItems.swift)246        var pending: [PendingItems.Entry] = []247        let queue = try? PendingItems()248        if let queue, queue.count > 0, let id = try? keyStore.loadIdentity(), let keys = try? keyStore.loadKeys(context: ctx) {249            pending = queue.load(identity: id, keys: keys)250        }251        try await engine.unlock(context: ctx)252        return (pending, queue)253    }254255    // ── unlock / lock ──256    func unlock() async {257        guard phase == .locked else { return }258        notice = nil259        let message = await perform {260            var pending: [PendingItems.Entry] = []261            var queue: PendingItems?262            do { (pending, queue) = try await AppModel.unlockEngine(self.engine, keyStore: self.keyStore, reason: "Unlock your vault") }263            catch EngineError.noCachedEnvelope {264                // enrolled but never unlocked offline (should not happen): fall back to the passkey sign-in265                if try await self.engine.signIn() == .pending { self.phase = .pairing; return }266            }267            self.phase = .main268            self.didUnlock()269            if let queue, !pending.isEmpty { await self.ingest(pending, from: queue) }270        }271        if let message { notice = message }272    }273274    private func ingest(_ pending: [PendingItems.Entry], from queue: PendingItems) async {275        guard let vaultId = await engine.vaults().first(where: { $0.role != .reader })?.vaultId else { return }276        var done = Set<String>()277        for p in pending {278            if (try? await engine.saveItem(vaultId: vaultId, id: nil, item: p.item)) != nil { done.insert(p.id) }279        }280        queue.remove(ids: done)281        if !done.isEmpty { show(done.count == 1 ? "1 item created from AutoFill was saved to your vault" : "\(done.count) items created from AutoFill were saved to your vault", kind: .info) }282    }283284    /// After any path that leaves the engine unlocked (unlock, registration, pairing, recovery).285    func didUnlock() {286        touch()287        startEvents()288        scheduleIdentitySync()289        Task { await self.refresh() }290        if prefs.notifications { Task { await Notifier.requestAuthorization() } }291    }292293    func lock() {294        guard phase == .main else { return }295        Task { await engine.lock() }296        didLock()297    }298299    private func didLock() {300        phase = identity == nil ? .welcome : .locked301        eventsTask?.cancel(); eventsTask = nil302        editor = nil; selectedItemID = nil; query = ""303        items = []; vaults = []304        onLocked?()305    }306307    // ── onboarding ──308    func signInExisting() async -> String? {309        notice = nil310        return await perform {311            switch try await self.engine.signIn() {312            case .pending: self.phase = .pairing313            case .unlocked: self.phase = .main; self.didUnlock()314            }315        }316    }317318    func register(invite: String, handle: String) async -> String? {319        await perform {320            let key = try await self.engine.register(invite: invite, handle: handle)321            self.didUnlock()322            self.phase = .recoveryKit(key: key, reason: .new)323        }324    }325326    func recover(handle: String, recoveryKey: String) async -> String? {327        await perform {328            try await self.engine.recover(handle: handle, recoveryKey: recoveryKey)329            self.phase = .main330            self.didUnlock()331            self.show("Vault recovered on this device", kind: .info)332        }333    }334335    /// The pairing screen finished: this device is enrolled and unlocked.336    func pairingCompleted() {337        phase = .main338        didUnlock()339    }340341    func finishRecoveryKit() {342        phase = .main343        Task { await refresh() }344    }345346    func signOut() async {347        await engine.signOut()348        await CredentialIdentitySync.clear()349        didLock()350    }351352    /// Erases everything SP Vault keeps on this device. The account and the other devices are not affected.353    func removeThisDevice() async {354        await act {355            await self.engine.signOut()356            try await self.engine.forget()357            await CredentialIdentitySync.clear()358            (try? PendingItems())?.removeAll()359            self.identity = nil360            self.didLock()361            self.phase = .welcome362        }363    }364365    /// Extracts the invitation token from a pasted link (`…/#/join/<token>`), a `spvault://join/<token>` URL or a bare token.366    static func inviteToken(from text: String) -> String? {367        var t = text.trimmingCharacters(in: .whitespacesAndNewlines)368        if let r = t.range(of: "/join/") { t = String(t[r.upperBound...]) }369        t = t.trimmingCharacters(in: CharacterSet(charactersIn: "/# "))370        guard t.count >= 16, t.count <= 128, t.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-" || $0 == "_") }) else { return nil }371        return t372    }373374    func open(url: URL) {375        guard let token = AppModel.inviteToken(from: url.absoluteString), url.absoluteString.contains("join") else { return }376        if phase == .welcome || phase == .loading { phase = .join(invite: token) }377        else { show("This device already has a vault. Remove it first to accept another invitation.", kind: .info) }378    }379380    // ── items ──381    /// Shows an item in the item list (from the Security Center, search, Spotlight).382    func reveal(_ id: String) {383        query = ""384        section = .allItems385        selectedItemID = id386        revealTick += 1387    }388389    func newItem(_ type: ItemType = .login) {390        guard isUnlocked else { return }391        guard let vaultId = defaultVaultId else { show("No vault you can write to", kind: .error); return }392        editor = EditorRequest(vaultId: vaultId, recordId: nil, item: SPV1.newItem(type))393    }394395    func edit(_ v: ItemView) { editor = EditorRequest(vaultId: v.vaultId, recordId: v.recordId, item: v.item) }396397    func toggleFavorite(_ v: ItemView) async {398        var it = v.item399        it.favorite.toggle()400        await act(it.favorite ? "Added to favorites" : "Removed from favorites") { try await self.engine.saveItem(vaultId: v.vaultId, id: v.recordId, item: it) }401    }402403    func trash(_ v: ItemView) async {404        await act("Moved to trash") { try await self.engine.trashItem(vaultId: v.vaultId, id: v.recordId) }405    }406407    func restore(_ v: ItemView) async {408        await act("Restored") { try await self.engine.restoreItem(vaultId: v.vaultId, id: v.recordId) }409    }410411    func deleteForever(_ v: ItemView) async {412        await act("Deleted permanently") { try await self.engine.deleteItem(vaultId: v.vaultId, id: v.recordId) }413    }414415    func syncNow() async {416        await act { try await self.engine.sync() }417        await refresh()418    }419420    // ── clipboard ──421    func copy(_ value: String, label: String, secret: Bool = true) {422        guard !value.isEmpty else { return }423        touch()424        SecureClipboard.copy(value, secret: secret, clearAfter: prefs.clipboardClearSeconds)425        let suffix = secret && prefs.clipboardClearSeconds > 0 ? " — clears in \(prefs.clipboardClearSeconds) s" : ""426        show("\(label) copied\(suffix)")427        #if os(iOS)428        UINotificationFeedbackGenerator().notificationOccurred(.success)429        #endif430    }431432    func copyPassword(_ v: ItemView? = nil) {433        guard let v = v ?? selectedItem else { return }434        guard let secret = SPV1.primarySecret(v.item) else { show("This item has no password", kind: .info); return }435        let def = v.item.type.template.fields.first { $0.kind == .secret }436        copy(secret, label: def?.label ?? "Password")437    }438439    func copyUsername(_ v: ItemView? = nil) {440        guard let v = v ?? selectedItem else { return }441        guard let u = v.item.fields["username"] ?? v.item.fields["userName"], !u.isEmpty else { show("This item has no username", kind: .info); return }442        copy(u, label: "Username", secret: false)443    }444445    func copyOneTimeCode(_ v: ItemView? = nil) {446        guard let v = v ?? selectedItem else { return }447        guard let t = v.item.fields["totp"], !t.isEmpty, let p = try? SPV1.parseTotp(t), let code = try? SPV1.totp(p) else { show("This item has no one-time code", kind: .info); return }448        copy(code.code, label: "One-time code")449    }450451    // ── auto-lock ──452    /// Any user activity postpones the auto-lock.453    func touch() { lastActivity = Date() }454455    private func startAutoLockTimer() {456        lockTask?.cancel()457        lockTask = Task { [weak self] in458            while !Task.isCancelled {459                try? await Task.sleep(for: .seconds(5))460                guard let self else { return }461                let limit = self.prefs.autoLockSeconds462                if self.phase == .main, limit > 0, Date().timeIntervalSince(self.lastActivity) >= Double(limit) { self.lock() }463            }464        }465    }466467    /// iOS: called when the app comes back to the foreground after `seconds` in the background.468    func returnedFromBackground(after seconds: TimeInterval) {469        if phase == .main, seconds >= Double(prefs.lockInBackgroundSeconds) { lock() }470        else if phase == .main { Task { try? await engine.sync() } }471    }472473    // ── live events ──474    private func startEvents() {475        eventsTask?.cancel()476        let keyStore = keyStore477        let events = LiveEvents(baseURL: AppEnvironment.baseURL) { (try? keyStore.loadSessionToken()) ?? nil }478        eventsTask = Task { [weak self] in479            for await e in events.stream() {480                guard let self, !Task.isCancelled else { return }481                switch e {482                case .sync: try? await self.engine.sync()483                case .devices: self.devicesTick += 1484                case .pairing:485                    self.devicesTick += 1486                    self.pairingHint = true487                    if self.prefs.notifications { await Notifier.post(.pairing) }488                case .shares:489                    self.sharesTick += 1490                    if self.prefs.notifications { await Notifier.post(.shares) }491                case .approval:492                    self.approvalsTick += 1493                    if self.prefs.notifications { await Notifier.post(.approval) }494                case .activity: self.activityTick += 1495                }496            }497        }498    }499500    // ── AutoFill identities ──501    private func scheduleIdentitySync() {502        identitiesTask?.cancel()503        guard phase == .main || isRecoveryKit else { return }504        identitiesTask = Task { [weak self] in505            try? await Task.sleep(for: .seconds(1.5)) // debounce bursts of sync changes506            guard let self, !Task.isCancelled else { return }507            if self.prefs.autofillSuggestions { await CredentialIdentitySync.replace(with: self.items) }508            else { await CredentialIdentitySync.clear() }509        }510    }511512    func autofillPreferenceChanged() { scheduleIdentitySync() }513514    private var isRecoveryKit: Bool { if case .recoveryKit = phase { return true }; return false }515}516517enum VaultErrorText {518    static func describe(_ e: VaultError) -> String {519        let s = String(describing: e)520        switch s {521        case let x where x.contains("recovery") || x.contains("Recovery") || x.contains("checksum"): return "This recovery key is not valid. Check each group; the last group is a checksum."522        case let x where x.contains("authenticationFailed"): return "SECURITY: the data failed authentication (corrupted or forged). Nothing was changed."523        default: return "The operation failed (\(s))."524        }525    }526}527
Files main
Menu

Theme