SPB Git

Repository Public

RootView.swift 15.8 KB 380 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/RootView.swift8// Module           : Sources9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import SwiftUI42import QyvoraCrypto43import QyvoraUI44import QyvoraVault45import QyvoraWallet4647/// Root of the application: engine self-test first, then the route derived from the wallet state48/// (no wallet → onboarding, full wallet with a locked vault → lock screen, otherwise the main shell; a49/// watch-only wallet has no vault). The privacy cover hides everything whenever the scene is not active.50struct RootView: View {51    @Environment(AppModel.self) private var model52    @Environment(WalletStore.self) private var wallet53    @Environment(\.scenePhase) private var scenePhase54    @Environment(\.accessibilityReduceMotion) private var reduceMotion55    /// True while an onboarding flow is on screen: the wallet may already exist (phrase being written down).56    @State private var onboardingActive = false57    @State private var wasInBackground = false58    /// True from the return to the foreground until the auto-lock policy has been applied: the cover stays on.59    @State private var applyingAutoLock = false6061    var body: some View {62        ZStack {63            switch model.phase {64            case .booting, .selfTesting:65                BootScreen()66                    .transition(.opacity)67            case .failed:68                SelfTestFailureScreen()69                    .transition(.opacity)70            case .ready:71                ready72                    .transition(.opacity)73            }74        }75        .animation(reduceMotion ? nil : .smooth(duration: 0.35), value: model.phase)76        .animation(reduceMotion ? nil : .smooth(duration: 0.35), value: model.route)77        .qScreen()78        .qPrivacyCover(isActive: coverIsActive)79        .task {80            #if DEBUG81            await DebugLaunch.prepareWallet(wallet)82            #endif83            await model.boot()84        }85        .onChange(of: desiredRoute, initial: true) { _, route in86            if let route { model.route = route }87        }88        .onChange(of: scenePhase) { _, phase in sceneChanged(phase) }89        .task(id: autoLockTimerKey) { await autoLockTimer() }90    }9192    var coverIsActive: Bool {93        #if DEBUG94        if DebugLaunch.screen == "privacy-cover" { return true }95        #endif96        return AutoLockRule.coversContent(sceneIsActive: scenePhase == .active, applyingPolicy: applyingAutoLock)97    }9899    /// The route the wallet state calls for; nil while the state is not known yet.100    var desiredRoute: AppRoute? {101        #if DEBUG102        if let forced = DebugLaunch.forcedRoute { return forced }103        #endif104        guard let snapshot = wallet.snapshot else { return nil }105        if !snapshot.hasWallet || onboardingActive { return .onboarding }106        if snapshot.profile.kind == .full, !(snapshot.vault.exists && snapshot.vault.isUnlocked) { return .locked }107        return .main108    }109110    // MARK: Auto-lock111112    /// Maps the scene phases to the events of `AutoLockRule` (QyvoraWallet), where the decisions are made and tested:113    /// leaving for the background locks at once under "immediately" and applies the policy otherwise; coming back114    /// applies the policy (the time spent away counts) before the cover is lifted; becoming merely inactive does115    /// nothing, because the system's Face ID sheet makes the application inactive.116    func sceneChanged(_ phase: ScenePhase) {117        switch phase {118        case .background:119            wasInBackground = true120            perform(.enteredBackground)121        case .active:122            guard wasInBackground else { return }123            wasInBackground = false124            perform(.returnedFromBackground)125        default:126            perform(.becameInactive)127        }128    }129130    func perform(_ event: AutoLockRule.Event) {131        guard let snapshot = wallet.snapshot else { return }132        switch AutoLockRule.action(for: event, policy: snapshot.profile.autoLock, isUnlocked: snapshot.vault.isUnlocked) {133        case .none:134            break135        case .lock:136            Task { await wallet.lock() }137        case .applyPolicy:138            if event == .returnedFromBackground { applyingAutoLock = true }139            Task {140                _ = await wallet.autoLockIfNeeded()141                applyingAutoLock = false142            }143        }144    }145146    /// The timer runs for an unlocked vault while the scene is active.147    var autoLockTimerKey: String {148        guard let snapshot = wallet.snapshot,149              AutoLockRule.timerRuns(policy: snapshot.profile.autoLock, isUnlocked: snapshot.vault.isUnlocked, sceneIsActive: scenePhase == .active) else { return "off" }150        return "on"151    }152153    func autoLockTimer() async {154        guard autoLockTimerKey == "on" else { return }155        while !Task.isCancelled {156            try? await Task.sleep(for: .seconds(AutoLockRule.timerInterval))157            if Task.isCancelled { return }158            if await wallet.autoLockIfNeeded() { return }159        }160    }161162    // MARK: Content163164    @ViewBuilder var ready: some View {165        if let reason = startupError {166            StartupErrorScreen(reason: reason)167        } else if wallet.snapshot == nil, !debugBypassesWallet {168            BootScreen()169        } else {170            routed171        }172    }173174    var startupError: String? {175        #if DEBUG176        if DebugLaunch.screen == "startup-error" { return "DEBUG preview: this line stands for the real error text" }177        #endif178        return wallet.startupError179    }180181    var debugBypassesWallet: Bool {182        #if DEBUG183        return DebugLaunch.forcedRoute != nil184        #else185        return false186        #endif187    }188189    @ViewBuilder var routed: some View {190        #if DEBUG191        if DebugLaunch.screen == "gallery" {192            DebugGallery(section: DebugLaunch.gallerySection)193        } else {194            route195        }196        #else197        route198        #endif199    }200201    @ViewBuilder var route: some View {202        switch model.route {203        case .onboarding:204            OnboardingFlow(isActive: $onboardingActive)205                .transition(.opacity)206        case .locked:207            LockScreen()208                .transition(.opacity)209        case .main:210            MainShell()211                .transition(.opacity)212        }213    }214}215216/// Blocking screen: the wallet storage could not be opened, so nothing of the wallet can be read or written.217struct StartupErrorScreen: View {218    let reason: String219220    var body: some View {221        ScrollView {222            VStack(alignment: .leading, spacing: 22) {223                Image(systemName: "externaldrive.badge.xmark")224                    .font(.system(size: 52, weight: .light))225                    .foregroundStyle(QColor.negative)226                    .accessibilityHidden(true)227                    .padding(.top, 48)228                Text("The wallet storage cannot be opened")229                    .font(.system(.largeTitle, design: .default, weight: .bold))230                    .foregroundStyle(QColor.textPrimary)231                    .accessibilityAddTraits(.isHeader)232                Text("QYVORA could not open its storage on this device, so it cannot read or create a wallet. Nothing was changed.")233                    .font(QFont.body).foregroundStyle(QColor.textPrimary)234                WarningBanner(.info, title: "Your funds are not affected by this screen",235                              message: "They are on the networks, controlled by your recovery phrase. Do not delete the application before trying the steps below: deleting it removes the vault.")236                VStack(alignment: .leading, spacing: 10) {237                    QEyebrow("What to do")238                    Text("1. Close QYVORA and open it again.").font(QFont.callout).foregroundStyle(QColor.textPrimary)239                    Text("2. Check that the device has free storage, then restart it.").font(QFont.callout).foregroundStyle(QColor.textPrimary)240                    Text("3. If it persists, report the detail below. The wallet can be restored from its recovery phrase on another installation.")241                        .font(QFont.callout).foregroundStyle(QColor.textPrimary)242                }243                QCard {244                    VStack(alignment: .leading, spacing: 10) {245                        DetailRow(label: "Detail", value: reason, mono: true)246                        QKeyValueRow("Application", AppInfo.versionAndBuild, mono: true)247                        QKeyValueRow("System", AppInfo.system, mono: true)248                    }249                }250                Link(destination: AppInfo.supportURL) { Label("Contact support", systemImage: "envelope") }251                    .buttonStyle(.qSecondary)252            }253            .padding(.horizontal, 24)254            .padding(.bottom, 32)255            .frame(maxWidth: 560, alignment: .leading)256            .frame(maxWidth: .infinity)257        }258        .qScreen()259    }260}261262/// Shown while the engine checks itself.263struct BootScreen: View {264    var body: some View {265        VStack(spacing: 22) {266            Spacer()267            QMark().frame(width: 120, height: 120)268            Text("QYVORA")269                .font(.system(.title2, design: .default, weight: .semibold))270                .kerning(7)271                .foregroundStyle(QColor.textPrimary)272            Spacer()273            HStack(spacing: 10) {274                ProgressView().controlSize(.small)275                Text("Checking the cryptographic engine")276                    .font(QFont.callout)277                    .foregroundStyle(QColor.textSecondary)278            }279            .padding(.bottom, 36)280            .accessibilityElement(children: .combine)281        }282        .frame(maxWidth: .infinity, maxHeight: .infinity)283        .padding(.horizontal, 24)284        .qScreen()285    }286}287288/// Terminal screen: a known-answer test returned a wrong result, so no cryptographic operation can be trusted.289/// There is deliberately no way to continue.290struct SelfTestFailureScreen: View {291    @Environment(AppModel.self) private var model292293    var body: some View {294        ScrollView {295            VStack(alignment: .leading, spacing: 24) {296                Image(systemName: "xmark.octagon")297                    .font(.system(size: 52, weight: .light))298                    .foregroundStyle(QColor.negative)299                    .accessibilityHidden(true)300                    .padding(.top, 48)301                VStack(alignment: .leading, spacing: 10) {302                    Text("Engine self-test failed")303                        .font(.system(.largeTitle, design: .default, weight: .bold))304                        .foregroundStyle(QColor.textPrimary)305                        .accessibilityAddTraits(.isHeader)306                    Text("QYVORA cannot continue.")307                        .font(QFont.title)308                        .foregroundStyle(QColor.textSecondary)309                }310                Text("At start-up the cryptographic engine computes known answers for its hash functions, secp256k1, ML-KEM, ML-DSA, SLH-DSA and AES-256-GCM. At least one result was wrong. A binary that fails this check must not create keys, sign or decrypt anything, so every feature is blocked.")311                    .font(QFont.body)312                    .foregroundStyle(QColor.textPrimary)313                WarningBanner(.info, title: "Your funds are not affected by this screen",314                              message: "Keys and recovery phrases are not touched. Do not enter a recovery phrase into this installation.")315                VStack(alignment: .leading, spacing: 12) {316                    QEyebrow("What to do")317                    step(1, "Close QYVORA and open it again. A corrupted launch is the most likely cause.")318                    step(2, "If the failure persists, reinstall the application from the App Store or TestFlight.")319                    step(3, "If it still fails, report it with the details below. Your wallet can be restored from its recovery phrase in a working installation.")320                }321                QCard {322                    VStack(spacing: 10) {323                        QKeyValueRow("Engine", QyvoraEngine.version, mono: true)324                        QKeyValueRow("Application", AppInfo.versionAndBuild, mono: true)325                        QKeyValueRow("System", AppInfo.system, mono: true)326                        if let record = model.selfTest {327                            QKeyValueRow("Failed at", record.date.formatted(date: .abbreviated, time: .standard), mono: true)328                        }329                    }330                }331                Link(destination: AppInfo.supportURL) {332                    Label("Contact support", systemImage: "envelope")333                }334                .buttonStyle(.qSecondary)335            }336            .padding(.horizontal, 24)337            .padding(.bottom, 32)338            .frame(maxWidth: 560, alignment: .leading)339            .frame(maxWidth: .infinity)340        }341        .qScreen()342    }343344    func step(_ number: Int, _ text: String) -> some View {345        HStack(alignment: .firstTextBaseline, spacing: 12) {346            Text("\(number)")347                .font(Font.system(.callout, design: .monospaced).weight(.semibold))348                .foregroundStyle(QColor.textSecondary)349                .accessibilityHidden(true)350            Text(text).font(QFont.callout).foregroundStyle(QColor.textPrimary)351                .fixedSize(horizontal: false, vertical: true)352        }353        .accessibilityElement(children: .combine)354        .accessibilityLabel("Step \(number). \(text)")355    }356}357358/// Facts about this build, read from the bundle and the system.359enum AppInfo {360    static var version: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "–" }361    static var build: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "–" }362    static var versionAndBuild: String { "\(version) (\(build))" }363    static var system: String {364        let v = ProcessInfo.processInfo.operatingSystemVersion365        return "iOS \(v.majorVersion).\(v.minorVersion).\(v.patchVersion)"366    }367    static var buildConfiguration: String {368        #if DEBUG369        return "Debug"370        #else371        return "Release"372        #endif373    }374375    static let repositoryURL = URL(string: "https://git.spboucher.ai/qyvora")!376    static let privacyURL = URL(string: "https://qyvora.spboucher.ai/privacy.html")!377    static let supportURL = URL(string: "mailto:support@spboucher.ai?subject=QYVORA")!378    static let supportAddress = "support@spboucher.ai"379}380
Files main
Menu

Theme