Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : App/Sources/Security/ShieldTab.swift8// Module : Security9// 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 QyvoraCore43import QyvoraQuantumShield44import QyvoraMigration45import QyvoraWallet46import QyvoraUI4748extension ShieldSeverity {49 var tone: QTone {50 switch self {51 case .info: return .info52 case .good: return .positive53 case .warning: return .warning54 case .critical: return .critical55 }56 }5758 var spoken: String {59 switch self {60 case .info: return "Information"61 case .good: return "In good order"62 case .warning: return "Warning"63 case .critical: return "Critical"64 }65 }66}6768extension ShieldLevel {69 var title: String {70 switch self {71 case .good: return "In good order"72 case .attention: return "Needs attention"73 case .critical: return "Critical"74 case .unknown: return "Not assessed"75 }76 }7778 var tone: QTone {79 switch self {80 case .good: return .positive81 case .attention: return .warning82 case .critical: return .critical83 case .unknown: return .neutral84 }85 }86}8788/// Lookups the Shield screens share: the registry entry behind a network name of the report, and the wording of a89/// measurement state. Nothing here decides anything about exposure: that is the report's.90enum SecShield {91 /// Leading inset of the hairlines of a card whose rows start with a 22-point severity glyph.92 static let findingInset: CGFloat = QMetric.padding + 22 + QSpace.m9394 /// The registry descriptor of a network named by the report (`ChainDescriptor.displayName`).95 static func descriptor(named name: String) -> ChainDescriptor? {96 ChainRegistry.all.first { $0.displayName == name }97 }9899 static func network(named name: String) -> QNetwork? {100 descriptor(named: name)?.qNetwork101 }102103 /// The UTXO network behind a registry descriptor.104 static func bitcoinNetwork(_ descriptor: ChainDescriptor) -> BitcoinNetwork? {105 descriptor.utxoNetwork106 }107108 /// The snapshot of a UTXO network among the active chains.109 static func chain(_ network: BitcoinNetwork, in snapshot: WalletSnapshot) -> ChainSnapshot? {110 snapshot.chains.first { $0.chain.utxoNetwork == network }111 }112113 /// True when the collapsed parts of the Shield start open (a DEBUG launch argument; always false in Release).114 static var startsExpanded: Bool {115 #if DEBUG116 return SecurityDebug.shieldExpanded117 #else118 return false119 #endif120 }121122 /// Why a chain has no data at all, when the service says so.123 static func failure<T>(_ state: Availability<T>) -> String? {124 if case .unavailable(let reason) = state { return reason }125 return nil126 }127128 /// "5 Dec 2026 at 02:10", "Synchronizing", "Not measured"…129 static func measured(_ date: Date?, running: Bool, failed: Bool) -> String {130 if running { return "Synchronizing" }131 if let date { return SecurityFormat.date(date) }132 return failed ? "Not measured (failed)" : "Not measured"133 }134135 /// "12 of 40 · Scanning receive addresses", from the real counts reported by the service.136 static func progress(_ progress: ChainSyncProgress) -> String {137 if let total = progress.total, total > 0 { return "\(progress.stage) · \(progress.completed) of \(total)" }138 return progress.completed > 0 ? "\(progress.stage) · \(progress.completed)" : progress.stage139 }140}141142/// One finding of the report: severity glyph, statement, and what to do when something can be done.143struct ShieldFindingRow: View {144 let finding: ShieldFinding145146 var body: some View {147 HStack(alignment: .firstTextBaseline, spacing: QSpace.m) {148 Image(systemName: finding.severity.tone.systemImage)149 .foregroundStyle(finding.severity.tone.color)150 .frame(width: 22)151 .accessibilityHidden(true)152 VStack(alignment: .leading, spacing: 4) {153 Text(finding.title).font(QFont.headline).foregroundStyle(QColor.textPrimary)154 Text(SecurityFormat.breakingLongTokens(finding.detail)).font(QFont.callout).foregroundStyle(QColor.textSecondary)155 if let recommendation = finding.recommendation {156 Text("What to do: \(recommendation)").font(QFont.callout).foregroundStyle(QColor.textPrimary)157 }158 }159 .fixedSize(horizontal: false, vertical: true)160 }161 .frame(maxWidth: .infinity, alignment: .leading)162 .padding(.vertical, QSpace.m)163 .accessibilityElement(children: .combine)164 .accessibilityLabel("\(finding.severity.spoken). \(finding.title). \(finding.detail) \(finding.recommendation.map { "What to do: \($0)" } ?? "")")165 }166}167168/// A card listing findings, separated by hairlines. Renders nothing for an empty list.169struct ShieldFindingsCard: View {170 var title: String?171 let findings: [ShieldFinding]172173 init(_ title: String? = nil, findings: [ShieldFinding]) {174 self.title = title175 self.findings = findings176 }177178 var body: some View {179 if !findings.isEmpty {180 QListSection(title, separatorInset: SecShield.findingInset) {181 ForEach(findings) { ShieldFindingRow(finding: $0) }182 }183 }184 }185}186187/// Numbered title of one of the three sections, with the level of that section only.188struct ShieldSectionTitle: View {189 let number: Int190 let title: String191 let subtitle: String192 let level: ShieldLevel?193194 var body: some View {195 VStack(alignment: .leading, spacing: QSpace.s) {196 HStack(alignment: .firstTextBaseline, spacing: QSpace.s) {197 Text("\(number)")198 .font(Font.system(.title3, design: .monospaced).weight(.semibold))199 .foregroundStyle(QColor.violet)200 .accessibilityHidden(true)201 Text(title).font(QFont.title).foregroundStyle(QColor.textPrimary)202 .fixedSize(horizontal: false, vertical: true)203 .accessibilityAddTraits(.isHeader)204 .accessibilityLabel("Section \(number): \(title)")205 }206 Text(subtitle).font(QFont.callout).foregroundStyle(QColor.textSecondary)207 .fixedSize(horizontal: false, vertical: true)208 if let level {209 StatusDot(level.tone, label: "This section: \(level.title)")210 }211 }212 .frame(maxWidth: .infinity, alignment: .leading)213 .padding(.top, QSpace.m)214 }215}216217/// The state of a measurement, as a shape and a word: never colour alone, and "not measured" has its own mark.218struct SecShieldState: View {219 enum Kind: Equatable {220 /// `note`: a measured fact that is neither good nor bad for the key (a Solana account not on chain yet).221 case exposed, hidden, note, notMeasured222223 var tone: QTone {224 switch self {225 case .exposed: return .warning226 case .hidden: return .positive227 case .note: return .info228 case .notMeasured: return .neutral229 }230 }231 }232233 let kind: Kind234 let label: String235236 init(_ exposed: Bool?, exposedLabel: String = "Key public", hiddenLabel: String = "Key not on chain", hiddenIsNeutral: Bool = false) {237 switch exposed {238 case .some(true):239 kind = .exposed240 label = exposedLabel241 case .some(false):242 kind = hiddenIsNeutral ? .note : .hidden243 label = hiddenLabel244 case .none:245 kind = .notMeasured246 label = "Not measured"247 }248 }249250 var body: some View {251 StatusDot(kind.tone, label: label)252 }253}254255/// Quantum Shield: three separate sections (local vault, exposure of this wallet's public keys, what the networks256/// offer). They are never merged into one score: a strong vault does not compensate for exposed keys, and neither257/// changes what the networks validate.258struct ShieldTab: View {259 /// A section another screen asked to see (the account of any chain, `ShieldSection`): scrolled to once the report is displayed.260 @Binding var focus: ShieldSection?261 @Environment(WalletStore.self) private var store262 @Environment(\.accessibilityReduceMotion) private var reduceMotion263 @State private var shield: WalletShieldReport?264 @State private var synchronizing = false265 @State private var syncCount = 0266 #if DEBUG267 @State private var debugRoute: SecurityRoute?268 #endif269270 init(focus: Binding<ShieldSection?> = .constant(nil)) {271 _focus = focus272 }273274 var body: some View {275 ScrollViewReader { proxy in276 ScrollView {277 VStack(alignment: .leading, spacing: QSpace.xl) {278 disclaimers279 content280 }281 .padding(.horizontal, QMetric.screenPadding)282 .padding(.top, QSpace.m)283 .padding(.bottom, QSpace.xxl)284 .frame(maxWidth: 640, alignment: .leading)285 .frame(maxWidth: .infinity)286 .background(alignment: .top) { Color.clear.frame(height: 1).id("top") }287 }288 // a link from an asset or a transaction: show the section it names, once the report is on screen289 .task(id: FocusRequest(section: focus, ready: shield != nil)) {290 guard let section = focus, shield != nil else { return }291 try? await Task.sleep(for: .milliseconds(350))292 guard !Task.isCancelled else { return }293 withAnimation(QMotion.resolved(QMotion.standard, reduceMotion: reduceMotion)) { proxy.scrollTo(section.rawValue, anchor: .top) }294 focus = nil295 }296 }297 .debugScroll()298 .securityDebugTour()299 .qScreen()300 .navigationTitle("Quantum Shield")301 .refreshable { await synchronize() }302 .task(id: store.snapshot) { await load() }303 .qHaptic(.selection, trigger: syncCount)304 .engineDestinations()305 .securityDestinations()306 #if DEBUG307 .navigationDestination(item: $debugRoute) { SecurityDebug.destination($0) }308 .task {309 await SecurityDebug.prepare(store)310 if SecurityDebug.host == .shield { debugRoute = SecurityDebug.route }311 }312 #endif313 }314315 struct FocusRequest: Equatable {316 let section: ShieldSection?317 let ready: Bool318 }319320 /// The statements that go with the report wherever it is shown: what local post-quantum cryptography covers, and321 /// the same for the other chains when the wallet uses them.322 @ViewBuilder var disclaimers: some View {323 WarningBanner(.info, title: "What post-quantum cryptography covers", message: shield?.disclaimer ?? QuantumShield.localCryptographyDisclaimer)324 if let additional = shield?.additionalDisclaimer {325 WarningBanner(.info, title: "Every other chain of this wallet", message: additional)326 .id("disclaimer-chains")327 }328 }329330 @ViewBuilder var content: some View {331 if let error = store.startupError {332 UnavailableDataView(reason: error, title: "Wallet storage unavailable")333 } else if let snapshot = store.snapshot {334 if !snapshot.hasWallet {335 EmptyStateView(systemImage: "shield.lefthalf.filled", title: "No wallet on this device",336 message: "The Quantum Shield reports on a wallet: its vault, the exposure of its public keys and the networks it uses. Create or restore a wallet first.")337 engineLinks338 } else if let shield {339 report(shield, snapshot)340 } else {341 loading342 }343 } else {344 loading345 }346 }347348 /// The shape of the report while it is being built.349 @ViewBuilder var loading: some View {350 SecSkeletonSection(title: "Measurements", rows: 2)351 SecSkeletonSection(title: "Local vault security", rows: 3)352 SecSkeletonSection(title: "Public-key exposure", rows: 3)353 }354355 @ViewBuilder func report(_ shield: WalletShieldReport, _ snapshot: WalletSnapshot) -> some View {356 let r = shield.report357 SecShieldMeasurementsCard(shield: shield, snapshot: snapshot, synchronizing: synchronizing) {358 Task { await synchronize() }359 }360 .id("measurements")361362 // 1 — the vault363 ShieldSectionTitle(number: 1, title: "Local vault security",364 subtitle: "How the secrets are protected on this device. This section says nothing about the blockchains.",365 level: r.vaultSecurity.level)366 .id("vault")367 ShieldFindingsCard(findings: r.vaultSecurity.findings)368 if !r.vaultSecurity.algorithms.isEmpty {369 QListSection("Algorithms in use", separatorInset: QMetric.padding) {370 ForEach(r.vaultSecurity.algorithms, id: \.self) { SecTextRow(text: $0, systemImage: "function", tone: .info) }371 }372 }373 QListSection {374 SecLinkRow(title: "Quantum Vault", subtitle: "Password, PIN, biometrics, integrity check", systemImage: "lock.shield", value: SecurityRoute.vault)375 }376377 // 2 — the keys378 ShieldSectionTitle(number: 2, title: "Public-key exposure",379 subtitle: "Which public keys of this wallet are already visible on chain, per coin and per account. A statement about this wallet's history, not about the vault.",380 level: r.keyExposure.level)381 .id("exposure")382 if r.keyExposure.isPartlyUnmeasured {383 WarningBanner(.neutral, title: "Partly not measured",384 message: "Part of this section has not been measured. What was not measured is not counted as safe: the level above cannot be better than \u{201C}not assessed\u{201D} for it.")385 }386 SecShieldExposureSection(shield: shield, snapshot: snapshot, synchronizing: synchronizing) {387 Task { await synchronize() }388 }389390 // 3 — the networks391 ShieldSectionTitle(number: 3, title: "Network quantum resistance",392 subtitle: "What the networks themselves validate today. Independent of this wallet and of this device.",393 level: nil)394 .id("networks")395 ShieldNetworkSection(resistance: r.networkResistance)396397 QListSection("Migration") {398 SecLinkRow(title: "Migration plan",399 subtitle: "\(shield.migrationPlan.actionable.count) step(s) you can take now · \(shield.migrationPlan.blocked.count) blocked by a protocol",400 systemImage: "list.bullet.clipboard", value: SecurityRoute.migrationPlan)401 }402 .id("plan")403 engineLinks404 Text("Report generated \(SecurityFormat.date(r.generatedAt)). There is deliberately no overall score: the three sections answer three different questions.")405 .font(QFont.caption)406 .foregroundStyle(QColor.textTertiary)407 .fixedSize(horizontal: false, vertical: true)408 }409410 var engineLinks: some View {411 QListSection("Reference") {412 SecLinkRow(title: "Quantum Migration Engine", subtitle: "What each network offers today", systemImage: "arrow.triangle.branch", value: EngineRoute.migration)413 SecLinkRow(title: "Cryptographic information", subtitle: "Algorithms, self-test, audit status", systemImage: "function", value: EngineRoute.cryptography)414 }415 }416417 /// Reads the report from the service. No network: it is built from the latest snapshots.418 func load() async {419 guard let service = store.service, store.snapshot?.hasWallet == true else {420 shield = nil421 return422 }423 shield = await service.shieldReport()424 }425426 /// Synchronizes every active chain through the store, so that the progress and the results show on every screen.427 func synchronize() async {428 guard !synchronizing, store.snapshot?.hasWallet == true, store.snapshot?.profile.coldMode != true else { return }429 synchronizing = true430 await store.synchronize()431 await load()432 synchronizing = false433 syncCount += 1434 }435}436437/// When each active chain was read, and the control that reads them again. A chain that was never read says so.438struct SecShieldMeasurementsCard: View {439 let shield: WalletShieldReport440 let snapshot: WalletSnapshot441 let synchronizing: Bool442 let synchronize: () -> Void443 @Environment(\.dynamicTypeSize) private var typeSize444445 var anyRunning: Bool { synchronizing || snapshot.chains.contains(where: \.isSynchronizing) }446447 var body: some View {448 QListSection("Measured from", footnote: footnote, separatorInset: QMetric.padding + 28 + QSpace.m) {449 ForEach(snapshot.chains) { chain in450 row(chain)451 }452 if snapshot.profile.coldMode {453 SecTextRow(text: "Cold mode is on: this device makes no network request, so on-chain exposure cannot be measured here.", systemImage: "snowflake")454 } else {455 LoadingButton("Synchronize every chain", loadingTitle: "Synchronizing", systemImage: "arrow.triangle.2.circlepath",456 state: anyRunning ? .loading : .idle, prominence: .secondary, action: synchronize)457 .padding(.vertical, QSpace.m)458 }459 }460 }461462 var footnote: String? {463 shield.isFromPreviousSession464 ? "Part of this report was measured in a previous session: it shows the last known state at the dates above, not a fresh measurement."465 : nil466 }467468 func row(_ chain: ChainSnapshot) -> some View {469 let network = chain.chain.qNetwork470 let date = shield.measuredAt[chain.id]471 let failed = chain.syncError != nil || SecShield.failure(chain.data) != nil472 let text = SecShield.measured(date, running: chain.isSynchronizing, failed: failed)473 let detail = chain.isSynchronizing ? chain.progress.map(SecShield.progress) : (date != nil ? chain.syncError.map { _ in "Last attempt failed" } : nil)474 return Group {475 if typeSize.isAccessibilitySize {476 VStack(alignment: .leading, spacing: 4) {477 HStack(spacing: QSpace.m) {478 ChainGlyph(network, size: .small)479 Text(network.fullName).font(QFont.subheadline).foregroundStyle(QColor.textPrimary)480 }481 stateText(text, measured: date != nil, detail: detail)482 }483 .frame(maxWidth: .infinity, alignment: .leading)484 } else {485 HStack(spacing: QSpace.m) {486 ChainGlyph(network, size: .small)487 Text(network.fullName).font(QFont.subheadline).foregroundStyle(QColor.textPrimary)488 .fixedSize(horizontal: false, vertical: true)489 Spacer(minLength: QSpace.s)490 stateText(text, measured: date != nil, detail: detail)491 }492 }493 }494 .padding(.vertical, QSpace.s + 2)495 .accessibilityElement(children: .combine)496 .accessibilityLabel("\(network.spokenName): \(text)\(detail.map { ", \($0)" } ?? "")")497 }498499 func stateText(_ text: String, measured: Bool, detail: String?) -> some View {500 VStack(alignment: typeSize.isAccessibilitySize ? .leading : .trailing, spacing: 2) {501 HStack(spacing: 6) {502 if !measured { StatusDot(.neutral, label: text, showsLabel: false) }503 Text(text).font(QFont.figure).foregroundStyle(measured ? QColor.textPrimary : QColor.textSecondary)504 }505 if let detail {506 Text(detail).font(QFont.caption.monospacedDigit()).foregroundStyle(QColor.textSecondary)507 }508 }509 .fixedSize(horizontal: false, vertical: true)510 }511}512