Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : App/Sources/Security/ReauthenticationSheet.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 LocalAuthentication43import QyvoraUI44import QyvoraWallet4546/// Asks the user to prove who they are before a sensitive action (reveal the phrase, export, sign, rotate, change47/// the password), although the vault is already unlocked.48///49/// The check is a real unlock call on the vault, through the wallet service: Face ID / Touch ID when the device slot50/// is enabled, else the PIN, else the master password. A wrong PIN counts against the PIN policy exactly as on the51/// lock screen. The secret typed here lives in this view's state only and is cleared as soon as it has been used.52///53/// Use `View.requiresReauthentication(isPresented:reason:onSuccess:)` rather than presenting this view directly.54struct ReauthenticationSheet: View {55 enum Method: Hashable { case biometrics, pin, password }5657 let reason: String58 /// Called once, when the vault accepted the credential. The caller dismisses the sheet.59 let onVerified: () -> Void6061 @Environment(WalletStore.self) private var store62 @Environment(\.dismiss) private var dismiss63 @State private var method: Method?64 @State private var password = ""65 @State private var pin = ""66 @State private var pinErrors = 067 @State private var lockedUntil: Date?68 @State private var message: String?69 @State private var busy = false70 @State private var successCount = 071 @State private var failureCount = 072 @State private var triedBiometrics = false7374 /// The one PIN rule of the application: exactly this many digits at setup, on the lock screen and here.75 static let pinLength = WalletService.pinLength7677 var vault: VaultStatus? { store.snapshot?.vault }7879 var methods: [Method] {80 guard let vault, vault.exists else { return [] }81 var list: [Method] = []82 if vault.biometricEnabled { list.append(.biometrics) }83 if vault.pinEnabled { list.append(.pin) }84 list.append(.password)85 return list86 }8788 var body: some View {89 ScrollView {90 VStack(alignment: .leading, spacing: 20) {91 SheetHeader("Confirm it is you", subtitle: reason) { dismiss() }92 if store.snapshot == nil {93 HStack(spacing: 10) {94 ProgressView().controlSize(.small)95 Text("Reading the vault state").font(QFont.callout).foregroundStyle(QColor.textSecondary)96 }97 } else if methods.isEmpty {98 WarningBanner(.info, title: "No vault on this device",99 message: "There is nothing to authenticate against: this device holds no private key.")100 } else {101 switch method ?? methods[0] {102 case .biometrics: biometricsForm103 case .pin: pinForm104 case .password: passwordForm105 }106 if let message, (method ?? methods[0]) != .pin {107 WarningBanner(.critical, message: message)108 }109 alternatives110 }111 }112 .padding(20)113 .frame(maxWidth: 520, alignment: .leading)114 .frame(maxWidth: .infinity)115 }116 .qScreen()117 .privacySensitive()118 .interactiveDismissDisabled(busy)119 .sensoryFeedback(.success, trigger: successCount)120 .sensoryFeedback(.error, trigger: failureCount)121 .task(id: store.snapshot?.vault) {122 guard method == nil, let first = methods.first else { return }123 #if DEBUG124 if SecurityDebug.autoAuthenticate {125 method = .password126 verify { try await $0.unlock(password: SecurityDebug.throwawayPassword) }127 return128 }129 #endif130 method = first131 if first == .biometrics, !triedBiometrics {132 triedBiometrics = true133 useBiometrics()134 }135 }136 .onDisappear {137 password = ""138 pin = ""139 }140 }141142 // MARK: Forms143144 var biometricsForm: some View {145 VStack(spacing: 16) {146 Image(systemName: Self.biometry.systemImage)147 .font(.system(size: 56, weight: .light))148 .foregroundStyle(QColor.violet)149 .frame(maxWidth: .infinity)150 .padding(.vertical, 12)151 .accessibilityHidden(true)152 LoadingButton("Use \(Self.biometry.name)", loadingTitle: "Waiting for \(Self.biometry.name)", systemImage: Self.biometry.systemImage,153 state: busy ? .loading : .idle) { useBiometrics() }154 }155 }156157 var pinForm: some View {158 PINPad(pin: $pin, length: Self.pinLength, title: "Enter your PIN", message: message, errorCount: pinErrors, lockedUntil: lockedUntil) { entered in159 verify { try await $0.unlock(pin: entered) }160 }161 .disabled(busy)162 .frame(maxWidth: .infinity)163 }164165 var passwordForm: some View {166 VStack(alignment: .leading, spacing: 14) {167 PasswordField("Master password", text: $password) { submitPassword() }168 LoadingButton("Confirm", loadingTitle: "Checking the password", systemImage: "lock.open",169 state: busy ? .loading : .idle) { submitPassword() }170 .disabled(password.isEmpty)171 Text("The password is checked by the vault with its slow key derivation: this takes a moment.")172 .font(QFont.caption)173 .foregroundStyle(QColor.textSecondary)174 .fixedSize(horizontal: false, vertical: true)175 }176 }177178 @ViewBuilder var alternatives: some View {179 let current = method ?? methods[0]180 let others = methods.filter { $0 != current }181 if !others.isEmpty {182 VStack(alignment: .leading, spacing: 4) {183 ForEach(others, id: \.self) { other in184 Button {185 message = nil186 pin = ""187 password = ""188 method = other189 } label: {190 Label(Self.title(other), systemImage: Self.icon(other))191 .font(.callout.weight(.medium))192 .foregroundStyle(QColor.violet)193 .frame(minHeight: 44)194 .contentShape(Rectangle())195 }196 .buttonStyle(.plain)197 .disabled(busy)198 }199 }200 }201 }202203 // MARK: Verification204205 func useBiometrics() {206 let prompt = reason207 verify { try await $0.unlockWithBiometrics(prompt: prompt) }208 }209210 func submitPassword() {211 guard !password.isEmpty else { return }212 let candidate = password213 verify { try await $0.unlock(password: candidate) }214 }215216 /// Runs one real unlock call. Success means the vault accepted the credential.217 func verify(_ operation: @escaping @Sendable (WalletService) async throws -> Void) {218 guard !busy else { return }219 busy = true220 message = nil221 Task {222 do {223 try await store.run(operation)224 password = ""225 pin = ""226 successCount += 1227 busy = false228 onVerified()229 } catch {230 password = ""231 pin = ""232 failureCount += 1233 busy = false234 handle(error)235 }236 }237 }238239 func handle(_ error: any Error) {240 switch error as? WalletError {241 case .wrongPIN(let retryAllowedAt):242 pinErrors += 1243 lockedUntil = retryAllowedAt244 message = retryAllowedAt == nil ? "Wrong PIN." : "Wrong PIN. A waiting time now applies."245 case .pinLocked(let until, _):246 lockedUntil = until247 message = "Too many wrong PINs. Use the master password or wait."248 case .vaultWiped:249 message = "The vault was erased from this device after too many wrong PINs. Restore the wallet from its recovery phrase."250 method = .password251 case .biometricUnavailable(let text):252 message = text253 if let fallback = methods.first(where: { $0 != .biometrics }) { method = fallback }254 default:255 message = SecurityError.text(error)256 }257 }258259 // MARK: Labels260261 struct Biometry {262 let name: String263 let systemImage: String264 }265266 /// Name and glyph of the biometric sensor of this device (used for labels only; the check itself is the vault's).267 static var biometry: Biometry {268 let context = LAContext()269 _ = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)270 switch context.biometryType {271 case .touchID: return Biometry(name: "Touch ID", systemImage: "touchid")272 case .opticID: return Biometry(name: "Optic ID", systemImage: "opticid")273 default: return Biometry(name: "Face ID", systemImage: "faceid")274 }275 }276277 static func title(_ method: Method) -> String {278 switch method {279 case .biometrics: return "Use \(biometry.name) instead"280 case .pin: return "Use the PIN instead"281 case .password: return "Use the master password instead"282 }283 }284285 static func icon(_ method: Method) -> String {286 switch method {287 case .biometrics: return biometry.systemImage288 case .pin: return "circle.grid.3x3"289 case .password: return "key"290 }291 }292}293294private struct ReauthenticationModifier: ViewModifier {295 @Binding var isPresented: Bool296 let reason: String297 let onSuccess: () -> Void298 @State private var verified = false299300 func body(content: Content) -> some View {301 content.sheet(isPresented: $isPresented, onDismiss: {302 // The action runs once the sheet is gone, so that it can present something itself.303 if verified {304 verified = false305 onSuccess()306 }307 }) {308 ReauthenticationSheet(reason: reason) {309 verified = true310 isPresented = false311 }312 }313 }314}315316extension View {317 /// Presents the re-authentication sheet while `isPresented` is true and calls `onSuccess` after the vault accepted318 /// Face ID / Touch ID, the PIN or the master password and the sheet has been dismissed. Nothing is called when319 /// the user cancels. `reason` is one sentence saying what is about to happen ("Reveal the recovery phrase").320 ///321 /// Requires a `WalletStore` in the environment. The credential is verified by the wallet service and never kept.322 func requiresReauthentication(isPresented: Binding<Bool>, reason: String, onSuccess: @escaping () -> Void) -> some View {323 modifier(ReauthenticationModifier(isPresented: isPresented, reason: reason, onSuccess: onSuccess))324 }325}326