SPB Git

Repository Public

ProtectStep.swift 9.0 KB 220 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Onboarding/ProtectStep.swift8// Module           : Onboarding9// 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 QyvoraWallet43import QyvoraUI4445/// Optional quick unlock after the vault exists: biometrics and a 6-digit PIN. Both are shortcuts to the46/// master password, which always keeps working. Needs the unlocked vault left by creation or import.47struct ProtectStep: View {48    let step: Int49    let stepCount: Int50    let onContinue: () -> Void5152    @Environment(WalletStore.self) private var wallet53    @State private var biometricState: LoadingButtonState = .idle54    @State private var biometricError: String?55    @State private var settingPIN: Bool56    @State private var firstPIN: String?57    @State private var pin = ""58    @State private var pinErrors = 059    @State private var pinMessage: String?60    @State private var pinBusy = false61    /// The service asks for a credential again when too long has passed since the password was typed (QYV-APP-002).62    @State private var reauthenticate = false63    @State private var afterAuthentication: (@MainActor () -> Void)?6465    init(step: Int, stepCount: Int, startWithPIN: Bool = false, onContinue: @escaping () -> Void) {66        self.step = step67        self.stepCount = stepCount68        self.onContinue = onContinue69        _settingPIN = State(initialValue: startWithPIN)70    }7172    var vault: VaultStatus? { wallet.snapshot?.vault }7374    var body: some View {75        OnboardingScaffold(title: settingPIN ? "Choose a PIN" : "Quick unlock", step: step, stepCount: stepCount, onClose: nil) {76            if settingPIN {77                pinEntry78            } else {79                Text("Both are optional shortcuts. The master password always works and is required again after too many wrong PINs.")80                    .font(QFont.callout).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)81                biometricCard82                pinCard83            }84        } footer: {85            if settingPIN {86                Button("Cancel") { resetPIN(); settingPIN = false }.buttonStyle(.qSecondary)87            } else {88                Button(vault?.biometricEnabled == true || vault?.pinEnabled == true ? "Continue" : "Continue without quick unlock", action: onContinue)89                    .buttonStyle(.qPrimary)90            }91        }92        .onDisappear { resetPIN() }93        .requiresReauthentication(isPresented: $reauthenticate, reason: "Set up quick unlock") {94            let action = afterAuthentication95            afterAuthentication = nil96            action?()97        }98    }99100    var biometricCard: some View {101        QCard {102            VStack(alignment: .leading, spacing: 12) {103                Label(DeviceBiometry.name, systemImage: DeviceBiometry.systemImage).font(QFont.headline).foregroundStyle(QColor.textPrimary)104                if vault?.biometricEnabled == true {105                    StatusDot(.positive, label: "\(DeviceBiometry.name) unlock is on")106                } else if DeviceBiometry.kind == nil {107                    Text("No biometric sensor is set up on this device. You can enable it later in the vault settings.")108                        .font(QFont.callout).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)109                } else {110                    Text("A device key held by the Secure Enclave unlocks the vault after a successful \(DeviceBiometry.name) check. Changing the enrolled biometrics disables it.")111                        .font(QFont.callout).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)112                    InlineError(message: biometricError)113                    LoadingButton("Enable \(DeviceBiometry.name)", systemImage: DeviceBiometry.systemImage, state: biometricState, prominence: .secondary) {114                        enableBiometrics()115                    }116                }117            }118        }119    }120121    var pinCard: some View {122        QCard {123            VStack(alignment: .leading, spacing: 12) {124                Label("PIN", systemImage: "circle.grid.3x3").font(QFont.headline).foregroundStyle(QColor.textPrimary)125                if vault?.pinEnabled == true {126                    StatusDot(.positive, label: "PIN unlock is on")127                } else {128                    Text("Exactly \(WalletService.pinLength) digits. Wrong entries are counted on the device: after three, waiting times apply and grow up to 24 hours.")129                        .font(QFont.callout).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)130                    Button { settingPIN = true } label: { Label("Set a PIN", systemImage: "circle.grid.3x3") }131                        .buttonStyle(.qSecondary)132                }133            }134        }135    }136137    var pinEntry: some View {138        PINPad(pin: $pin, length: WalletService.pinLength, title: firstPIN == nil ? "Enter a \(WalletService.pinLength)-digit PIN" : "Repeat the PIN",139               message: pinMessage, errorCount: pinErrors) { entered in140            if let rejection = WalletService.pinRejection(entered) {141                pin = ""142                pinErrors += 1143                pinMessage = rejection144            } else if let first = firstPIN {145                if first == entered {146                    enablePIN(entered)147                } else {148                    firstPIN = nil149                    pin = ""150                    pinErrors += 1151                    pinMessage = "The two entries differ. Start again."152                }153            } else if Self.isTrivial(entered) {154                pin = ""155                pinErrors += 1156                pinMessage = "Too easy to guess. Choose another PIN."157            } else {158                firstPIN = entered159                pin = ""160                pinMessage = nil161            }162        }163        .disabled(pinBusy)164        .frame(maxWidth: .infinity)165    }166167    /// One repeated digit or a straight run (123456, 654321).168    static func isTrivial(_ pin: String) -> Bool {169        let digits = pin.compactMap(\.wholeNumberValue)170        guard digits.count == pin.count, digits.count > 1 else { return true }171        let steps = Set(zip(digits, digits.dropFirst()).map { $1 - $0 })172        return steps == [0] || steps == [1] || steps == [-1]173    }174175    func resetPIN() {176        pin = ""177        firstPIN = nil178        pinMessage = nil179    }180181    func enableBiometrics() {182        biometricState = .loading183        biometricError = nil184        Task {185            do {186                try await wallet.run { try await $0.enableBiometrics() }187                await wallet.refresh()188                biometricState = .success189            } catch WalletError.authenticationRequired {190                biometricState = .idle191                afterAuthentication = { enableBiometrics() }192                reauthenticate = true193            } catch {194                biometricState = .failure195                biometricError = WalletStore.message(for: error)196            }197        }198    }199200    func enablePIN(_ value: String) {201        pinBusy = true202        Task {203            defer { pinBusy = false }204            do {205                try await wallet.run { try await $0.enablePIN(value) }206                await wallet.refresh()207                resetPIN()208                settingPIN = false209            } catch WalletError.authenticationRequired {210                afterAuthentication = { enablePIN(value) }211                reauthenticate = true212            } catch {213                resetPIN()214                pinErrors += 1215                pinMessage = WalletStore.message(for: error)216            }217        }218    }219}220
Files main
Menu

Theme