Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : App/Sources/Security/VaultView.swift8// Module : Security9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0513//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 QyvoraStorage43import QyvoraVault44import QyvoraWallet45import QyvoraUI4647/// Choices offered for the auto-lock policy.48enum AutoLockChoice: Hashable, CaseIterable {49 case immediately, seconds30, minute1, minutes5, minutes155051 var policy: AutoLockPolicy {52 switch self {53 case .immediately: return .immediately54 case .seconds30: return .after(seconds: 30)55 case .minute1: return .after(seconds: 60)56 case .minutes5: return .after(seconds: 300)57 case .minutes15: return .after(seconds: 900)58 }59 }6061 var title: String {62 switch self {63 case .immediately: return "When leaving the app"64 case .seconds30: return "After 30 seconds"65 case .minute1: return "After 1 minute"66 case .minutes5: return "After 5 minutes"67 case .minutes15: return "After 15 minutes"68 }69 }7071 static func delay(_ policy: AutoLockPolicy) -> TimeInterval {72 switch policy {73 case .immediately: return 074 case .after(let seconds): return seconds75 case .never: return .infinity76 }77 }7879 static func title(for policy: AutoLockPolicy) -> String {80 if let known = allCases.first(where: { $0.policy == policy }) { return known.title }81 if case .after(let seconds) = policy { return "After \(Int(seconds)) seconds" }82 return "Custom"83 }84}8586/// Quantum Vault: what protects the secrets on this device (report), the unlock methods, the auto-lock policy,87/// integrity check, master-key rotation, and the removal of the wallet from the device.88struct VaultView: View {89 enum Pending { case enableBiometrics(secureEnclave: Bool), disableBiometrics, setPIN, disablePIN, setAutoLock(AutoLockChoice) }90 enum Sheet: String, Identifiable {91 case changePassword, pinSetup, rotate, delete92 var id: String { rawValue }93 }9495 @Environment(WalletStore.self) private var store96 @State private var report: VaultReport?97 @State private var reportError: String?98 @State private var integrity: IntegrityReport?99 @State private var error: String?100 @State private var busy: String?101 @State private var sheet: Sheet?102 @State private var pending: Pending?103 @State private var reauthenticate = false104 @State private var chooseBiometrics = false105 @State private var changeCount = 0106107 var snapshot: WalletSnapshot? { store.snapshot }108 var status: VaultStatus? { snapshot?.vault }109 static var secureEnclaveAvailable: Bool { SystemSecureEnclaveKey(keychain: SystemKeychainStore()).isAvailable }110111 var body: some View {112 SecurityScroll {113 if let snapshot, !snapshot.vault.exists {114 EmptyStateView(systemImage: "lock.shield", title: "No vault on this device",115 message: snapshot.profile.kind == .watchOnly116 ? "This is a watch-only wallet: it holds public keys only, so there is no secret to protect and no vault."117 : "No wallet has been created on this device yet.")118 if snapshot.hasWallet { dangerSection }119 } else if snapshot == nil {120 SecSkeletonSection(rows: 1)121 SecSkeletonSection(title: "Unlock methods", rows: 3)122 } else {123 SecInlineError(error)124 stateSection125 unlockSection126 autoLockSection127 maintenanceSection128 reportSection129 dangerSection130 }131 }132 .navigationTitle("Quantum Vault")133 .navigationBarTitleDisplayMode(.inline)134 .task(id: store.snapshot?.vault) { await loadReport() }135 .sheet(item: $sheet, onDismiss: { Task { await loadReport() } }) { item in136 switch item {137 case .changePassword: ChangePasswordSheet()138 case .pinSetup: PINSetupSheet()139 case .rotate: RotateMasterKeySheet(pinEnabled: status?.pinEnabled ?? false)140 case .delete: DeleteWalletSheet()141 }142 }143 .requiresReauthentication(isPresented: $reauthenticate, reason: reauthenticationReason) { runPending() }144 .confirmationDialog("Where should the device key be kept?", isPresented: $chooseBiometrics, titleVisibility: .visible) {145 if Self.secureEnclaveAvailable {146 Button("Secure Enclave (recommended)") { ask(.enableBiometrics(secureEnclave: true)) }147 }148 Button("Keychain, behind \(ReauthenticationSheet.biometry.name)") { ask(.enableBiometrics(secureEnclave: false)) }149 Button("Cancel", role: .cancel) {}150 } message: {151 Text(Self.secureEnclaveAvailable152 ? "With the Secure Enclave the device key is wrapped by a key that never leaves the chip. Both options release it only after \(ReauthenticationSheet.biometry.name)."153 : "This device has no Secure Enclave: the device key is kept in the Keychain and released only after \(ReauthenticationSheet.biometry.name).")154 }155 .sensoryFeedback(.success, trigger: changeCount)156 #if DEBUG157 .task {158 if let name = SecurityDebug.sheet, let item = Sheet(rawValue: name) { sheet = item }159 if SecurityDebug.sheet == "reauth" { reauthenticate = true }160 if SecurityDebug.action == "integrity" { verifyIntegrity() }161 }162 #endif163 }164165 // MARK: Sections166167 var stateSection: some View {168 let unlocked = status?.isUnlocked == true169 return QListSection(footnote: "Locking removes the master key from memory. Balances stay visible; signing, backups and the identity need the vault open.",170 separatorInset: QMetric.padding) {171 HStack(spacing: QSpace.m) {172 QIconTile(unlocked ? "lock.open" : "lock", tint: unlocked ? QColor.positive : QColor.textSecondary).frame(minWidth: 40)173 VStack(alignment: .leading, spacing: 3) {174 Text(unlocked ? "Unlocked" : "Locked").font(QFont.headline).foregroundStyle(QColor.textPrimary)175 Text(unlocked ? "The master key is in memory" : "The master key is not in memory").font(QFont.caption).foregroundStyle(QColor.textSecondary)176 }177 .fixedSize(horizontal: false, vertical: true)178 Spacer(minLength: QSpace.s)179 Button("Lock now") { Task { await store.lock() } }180 .font(.callout.weight(.semibold))181 .foregroundStyle(QColor.violet)182 .frame(minHeight: QMetric.minTap)183 .buttonStyle(.qPressable)184 .disabled(!unlocked)185 }186 .padding(.vertical, QSpace.s)187 .frame(minHeight: QMetric.rowMinHeight)188 }189 .qAnimation(value: unlocked)190 .id("state")191 }192193 var unlockSection: some View {194 QListSection("Unlock methods", footnote: "Each method is an independent slot wrapping the same master key. The PIN and \(ReauthenticationSheet.biometry.name) work on this device only; the master password is always required to rotate the key.") {195 actionRow("Master password", "Opens the vault and protects it at rest", "key", trailing: "Change") { sheet = .changePassword }196 if status?.biometricEnabled == true {197 actionRow(ReauthenticationSheet.biometry.name, report?.deviceSlotUsesSecureEnclave == true ? "Enabled · Secure Enclave" : "Enabled · Keychain",198 ReauthenticationSheet.biometry.systemImage, trailing: "Disable") { ask(.disableBiometrics) }199 } else {200 actionRow(ReauthenticationSheet.biometry.name, "Off", ReauthenticationSheet.biometry.systemImage, trailing: "Enable") { chooseBiometrics = true }201 }202 if status?.pinEnabled == true {203 actionRow("PIN", pinSubtitle, "circle.grid.3x3", trailing: "Change") { ask(.setPIN) }204 SecActionRow(title: "Disable PIN", systemImage: "minus.circle", tint: QColor.negative, chevron: false) { ask(.disablePIN) }205 } else {206 actionRow("PIN", "Off", "circle.grid.3x3", trailing: "Enable") { ask(.setPIN) }207 }208 }209 .disabled(status?.isUnlocked != true || busy != nil)210 .id("unlock")211 }212213 var pinSubtitle: String {214 guard let report else { return "Enabled" }215 if let wipe = report.pinWipeAfterFailedAttempts { return "Enabled · vault erased after \(wipe) wrong PINs" }216 return "Enabled · wrong PINs are delayed"217 }218219 var autoLockSection: some View {220 let current = snapshot?.profile.autoLock221 let known = AutoLockChoice.allCases.first { $0.policy == current }222 return QListSection(footnote: "The vault locks by itself after this time without activity, and when the app comes back from the background after it. Fifteen minutes is the longest delay, and lengthening the delay asks you to confirm it is you.") {223 Menu {224 ForEach(AutoLockChoice.allCases, id: \.self) { choice in225 Button { setAutoLock(choice) } label: {226 if choice == known { Label(choice.title, systemImage: "checkmark") } else { Text(choice.title) }227 }228 }229 } label: {230 HStack(spacing: QSpace.s) {231 SecRowLabel(title: "Auto-lock", systemImage: "timer", trailing: current.map(AutoLockChoice.title(for:)))232 Image(systemName: "chevron.up.chevron.down").font(.footnote.weight(.semibold)).foregroundStyle(QColor.violet).accessibilityHidden(true)233 }234 .contentShape(Rectangle())235 }236 .buttonStyle(.qRow)237 .accessibilityLabel("Auto-lock")238 .accessibilityValue(current.map(AutoLockChoice.title(for:)) ?? "")239 }240 .disabled(busy != nil)241 .id("autolock")242 }243244 var maintenanceSection: some View {245 QListSection("Maintenance") {246 Button { verifyIntegrity() } label: {247 HStack(spacing: QSpace.s) {248 SecRowLabel(title: "Verify integrity", subtitle: "Re-reads the file and opens every record", systemImage: "checkmark.seal")249 if busy == "integrity" { ProgressView().controlSize(.small) }250 }251 }252 .buttonStyle(.qRow)253 if let integrity {254 SecTextRow(text: "\(integrity.recordsVerified) record(s) verified · file generation \(integrity.generation)", systemImage: QTone.positive.systemImage, tone: .positive)255 .transition(.opacity)256 }257 SecActionRow(title: "Rotate master key", subtitle: "New key, every record re-encrypted", systemImage: "arrow.triangle.2.circlepath") { sheet = .rotate }258 }259 .qAnimation(value: integrity != nil)260 .id("maintenance")261 .disabled(status?.isUnlocked != true || busy != nil)262 }263264 @ViewBuilder var reportSection: some View {265 if let report {266 QListSection("Vault report", separatorInset: QMetric.padding) {267 SecFactRow(label: "Format version", value: "\(report.formatVersion)")268 SecFactRow(label: "Vault identifier", value: MiddleTruncation.grouped(report.vaultID), mono: true)269 SecFactRow(label: "Created", value: SecurityFormat.date(report.createdAt))270 SecFactRow(label: "Key epoch", value: "\(report.keyEpoch)")271 SecFactRow(label: "File generation", value: "\(report.generation)")272 SecFactRow(label: "Self-test", value: report.selfTestPassed ? "Passed" : "FAILED", tone: report.selfTestPassed ? .positive : .critical)273 if report.recoveredFromPreviousCopy {274 SecTextRow(text: "This session runs on the previous copy of the vault file: the current one was damaged.", systemImage: QTone.warning.systemImage, tone: .warning)275 }276 }277 .id("report")278279 QListSection("Algorithms", footnote: "These protect the vault on this device. They say nothing about the blockchains, whose transactions are signed with the schemes the networks validate.",280 separatorInset: QMetric.padding) {281 SecFactRow(label: "Record encryption", value: report.recordEncryption)282 SecFactRow(label: "Sealing backend", value: report.sealingBackend)283 SecFactRow(label: "Master key", value: "\(report.masterKeyBits) bits")284 SecFactRow(label: "Nonce", value: "\(report.nonceBits) bits")285 SecFactRow(label: "Subkey derivation", value: report.subkeyDerivation)286 SecFactRow(label: "File authentication", value: report.fileAuthentication)287 }288 .id("algorithms")289290 QListSection("Slots and key derivation", separatorInset: QMetric.padding) {291 if let slot = report.passwordSlot {292 slotRow("Password slot", slot)293 } else {294 SecFactRow(label: "Password slot", value: "Absent")295 }296 if let slot = report.pinSlot {297 slotRow("PIN slot", slot)298 SecFactRow(label: "Consecutive wrong PINs", value: report.pinFailedAttempts.map { "\($0)" } ?? "Not recorded")299 SecFactRow(label: "Erase after wrong PINs", value: report.pinWipeAfterFailedAttempts.map { "\($0)" } ?? "Never")300 } else {301 SecFactRow(label: "PIN slot", value: "Not enabled")302 }303 SecFactRow(label: "Device slot", value: report.deviceSlotEnabled ? (report.deviceSlotUsesSecureEnclave ? "Enabled · Secure Enclave" : "Enabled · Keychain") : "Not enabled")304 }305 .id("slots")306307 QListSection("Records", footnote: "Counts only: the report holds no secret and is available while the vault is locked.", separatorInset: QMetric.padding) {308 ForEach(report.recordCounts.sorted { $0.key < $1.key }, id: \.key) { name, count in309 SecFactRow(label: Self.recordTitle(name), value: "\(count)")310 }311 SecFactRow(label: "Total", value: "\(report.totalRecords)")312 }313 .id("records")314 } else if let reportError {315 UnavailableDataView(reason: reportError, title: "Vault report unavailable", compact: true) { Task { await loadReport() } }316 } else {317 SecSkeletonSection(title: "Vault report", rows: 4)318 }319 }320321 var dangerSection: some View {322 QListSection(footnote: "Only the recovery phrase restores the funds afterwards.") {323 SecActionRow(title: "Delete wallet from this device", systemImage: "trash", tint: QColor.negative, chevron: false) { sheet = .delete }324 }325 .id("danger")326 }327328 func slotRow(_ title: String, _ slot: VaultReport.KDF) -> some View {329 VStack(alignment: .leading, spacing: 4) {330 Text(title).font(QFont.callout).foregroundStyle(QColor.textSecondary)331 Text(slot.construction).font(QFont.callout.weight(.medium)).foregroundStyle(QColor.textPrimary)332 Text(SecurityFormat.kdf(slot.parameters)).font(QFont.caption).foregroundStyle(QColor.textSecondary)333 }334 .fixedSize(horizontal: false, vertical: true)335 .frame(maxWidth: .infinity, alignment: .leading)336 .padding(.vertical, QSpace.m)337 .accessibilityElement(children: .combine)338 }339340 func actionRow(_ title: String, _ subtitle: String, _ systemImage: String, trailing: String?, action: @escaping () -> Void) -> some View {341 Button(action: action) {342 HStack(spacing: QSpace.s) {343 SecRowLabel(title: title, subtitle: subtitle, systemImage: systemImage, chevron: trailing == nil)344 if let trailing {345 Text(trailing).font(.callout.weight(.semibold)).foregroundStyle(QColor.violet)346 }347 }348 }349 .buttonStyle(.qRow)350 }351352 static func recordTitle(_ name: String) -> String {353 switch name {354 case "recoveryPhrase": return "Recovery phrase"355 case "bip39Passphrase": return "BIP-39 passphrase"356 case "identityKeys": return "Identity keys"357 case "watchOnlyAccount": return "Account public keys"358 case "setting": return "Setting"359 case "custom": return "Other (rotation chain…)"360 default: return name361 }362 }363364 // MARK: Actions365366 var reauthenticationReason: String {367 switch pending {368 case .enableBiometrics: return "Enable \(ReauthenticationSheet.biometry.name) unlock"369 case .disableBiometrics: return "Disable \(ReauthenticationSheet.biometry.name) unlock"370 case .setPIN: return "Set the PIN"371 case .setAutoLock: return "Lengthen the auto-lock delay"372 case .disablePIN: return "Disable the PIN"373 case nil: return "Change the vault settings"374 }375 }376377 func ask(_ action: Pending) {378 error = nil379 pending = action380 reauthenticate = true381 }382383 func runPending() {384 guard let action = pending else { return }385 pending = nil386 switch action {387 case .setPIN:388 sheet = .pinSetup389 case .enableBiometrics(let secureEnclave):390 perform("biometrics") { try await $0.enableBiometrics(useSecureEnclave: secureEnclave) }391 case .disableBiometrics:392 perform("biometrics") { try await $0.disableBiometrics() }393 case .disablePIN:394 perform("pin") { try await $0.disablePIN() }395 case .setAutoLock(let choice):396 let policy = choice.policy397 perform("autolock") { try await $0.setAutoLockPolicy(policy) }398 }399 }400401 func perform(_ tag: String, _ operation: @escaping @Sendable (WalletService) async throws -> Void) {402 guard busy == nil else { return }403 busy = tag404 error = nil405 Task {406 do {407 try await store.run(operation)408 changeCount += 1409 } catch {410 self.error = SecurityError.text(error)411 }412 busy = nil413 await store.refresh()414 await loadReport()415 }416 }417418 /// A shorter delay applies at once; a longer one weakens the protection and is confirmed first (QYV-APP-004).419 func setAutoLock(_ choice: AutoLockChoice) {420 let policy = choice.policy421 if let current = snapshot?.profile.autoLock, AutoLockChoice.delay(policy) > AutoLockChoice.delay(current) {422 ask(.setAutoLock(choice))423 } else {424 perform("autolock") { try await $0.setAutoLockPolicy(policy) }425 }426 }427428 func verifyIntegrity() {429 guard busy == nil else { return }430 busy = "integrity"431 error = nil432 integrity = nil433 Task {434 do {435 integrity = try await store.run { try await $0.verifyVaultIntegrity() }436 changeCount += 1437 } catch {438 self.error = "Integrity check: " + SecurityError.text(error)439 }440 busy = nil441 }442 }443444 func loadReport() async {445 guard let service = store.service, store.snapshot?.vault.exists == true else { return }446 do {447 report = try await service.vaultReport()448 reportError = nil449 } catch {450 reportError = SecurityError.text(error)451 }452 }453}454