SPB Git

Repository Public

UnlockPanel.swift 7.6 KB 204 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Lock/UnlockPanel.swift8// Module           : Lock9// 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/// The three ways to open the vault on the lock screen: biometrics, PIN, master password. (Confirmations46/// before a signature use the security area's `requiresReauthentication`.) A successful unlock calls47/// `onUnlocked`; the secret typed never leaves this view's state and is cleared when the view goes away.48struct UnlockPanel: View {49    enum Mode: Equatable { case pin, password }5051    let vault: VaultStatus52    /// Reason shown by the system biometric sheet.53    let biometricPrompt: String54    /// Starts the biometric check when the panel appears.55    let autoBiometrics: Bool56    let onUnlocked: () -> Void5758    @Environment(WalletStore.self) private var wallet59    @State private var mode: Mode60    @State private var pin = ""61    @State private var password = ""62    @State private var errorCount = 063    @State private var message: String?64    @State private var lockedUntil: Date?65    @State private var busy = false66    @State private var triedBiometrics = false67    @State private var successFeedback = 06869    init(vault: VaultStatus, biometricPrompt: String, autoBiometrics: Bool = true, onUnlocked: @escaping () -> Void) {70        self.vault = vault71        self.biometricPrompt = biometricPrompt72        self.autoBiometrics = autoBiometrics73        self.onUnlocked = onUnlocked74        _mode = State(initialValue: vault.pinEnabled ? .pin : .password)75    }7677    var body: some View {78        VStack(spacing: 20) {79            switch mode {80            case .pin:81                PINPad(pin: $pin, length: WalletService.pinLength, message: message, errorCount: errorCount, lockedUntil: lockedUntil,82                       biometry: vault.biometricEnabled ? (DeviceBiometry.kind ?? .faceID) : nil,83                       onBiometry: vault.biometricEnabled ? { biometrics() } : nil) { entered in84                    submit(pin: entered)85                }86                .disabled(busy)87                Button("Use the master password") { switchMode(.password) }88                    .font(.callout.weight(.medium))89                    .frame(minHeight: 44)90            case .password:91                VStack(alignment: .leading, spacing: 14) {92                    PasswordField("Master password", text: $password) { submitPassword() }93                    InlineError(message: message)94                    LoadingButton("Unlock", loadingTitle: "Deriving the key", systemImage: "lock.open", state: busy ? .loading : .idle) {95                        submitPassword()96                    }97                    .disabled(password.isEmpty || busy)98                    if busy {99                        Text("The password is stretched on purpose; this takes a few seconds.")100                            .font(QFont.caption).foregroundStyle(QColor.textSecondary)101                    }102                }103                HStack(spacing: 20) {104                    if vault.pinEnabled {105                        Button("Use the PIN") { switchMode(.pin) }106                    }107                    if vault.biometricEnabled {108                        Button { biometrics() } label: { Label("Use \(DeviceBiometry.name)", systemImage: DeviceBiometry.systemImage) }109                    }110                }111                .font(.callout.weight(.medium))112                .frame(minHeight: 44)113                .disabled(busy)114            }115        }116        .sensoryFeedback(.success, trigger: successFeedback)117        .sensoryFeedback(.error, trigger: errorCount)118        .task {119            #if DEBUG120            // `-QYUnlockWith pin | wrong-pin | password | wrong-password`: the same calls as the pad and the field.121            switch DebugLaunch.defaults.string(forKey: "QYUnlockWith") {122            case "pin": submit(pin: DebugLaunch.throwawayPIN)123            case "wrong-pin": submit(pin: "000000")124            case "password": mode = .password; password = DebugLaunch.throwawayPassword; submitPassword()125            case "wrong-password": mode = .password; password = "not the password"; submitPassword()126            default: break127            }128            #endif129            guard autoBiometrics, vault.biometricEnabled, !triedBiometrics else { return }130            biometrics()131        }132        .onDisappear {133            pin = ""134            password = ""135        }136    }137138    func switchMode(_ new: Mode) {139        pin = ""140        password = ""141        message = nil142        mode = new143    }144145    func succeed() {146        pin = ""147        password = ""148        message = nil149        successFeedback += 1150        onUnlocked()151    }152153    func biometrics() {154        guard !busy else { return }155        triedBiometrics = true156        let prompt = biometricPrompt157        attempt { try await $0.unlockWithBiometrics(prompt: prompt) }158    }159160    func submit(pin entered: String) {161        attempt { try await $0.unlock(pin: entered) }162    }163164    func submitPassword() {165        guard !password.isEmpty, !busy else { return }166        let entered = password167        attempt { try await $0.unlock(password: entered) }168    }169170    func attempt(_ operation: @escaping @Sendable (WalletService) async throws -> Void) {171        busy = true172        Task {173            defer { busy = false }174            do {175                try await wallet.run(operation)176                succeed()177            } catch {178                pin = ""179                handle(error)180            }181        }182    }183184    func handle(_ error: Error) {185        switch error as? WalletError {186        case .wrongPIN(let retryAllowedAt):187            errorCount += 1188            lockedUntil = retryAllowedAt.flatMap { $0 > Date() ? $0 : nil }189            message = "Wrong PIN."190        case .pinLocked(let until, _):191            lockedUntil = until192            message = "Too many wrong PINs. The master password still works."193        case .wrongPassword:194            errorCount += 1195            password = ""196            message = "Wrong password."197        case .biometricUnavailable(let reason):198            message = reason199        default:200            message = WalletStore.message(for: error)201        }202    }203}204
Files main
Menu

Theme