SPB Git

Repository Public

RestoreBackupView.swift 8.4 KB 194 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Security/RestoreBackupView.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 QyvoraRecovery43import QyvoraVault44import QyvoraWallet45import QyvoraUI4647/// Restores a wallet from an encrypted backup file on a device that has none (`restoreBackup`).48///49/// Entry point for onboarding: push or present `RestoreBackupView(onRestored:)`. The view picks the file, shows its50/// header, takes the backup password and the new vault password, and calls `onRestored` once the vault exists and51/// is unlocked.52struct RestoreBackupView: View {53    var onRestored: (() -> Void)?5455    @Environment(WalletStore.self) private var store56    @State private var picking = false57    @State private var fileURL: URL?58    @State private var fileName: String?59    @State private var header: BackupHeader?60    @State private var backupPassword = ""61    @State private var newPassword = ""62    @State private var confirmation = ""63    @State private var pinSigner = true64    @State private var restored = false65    @State private var error: String?66    @State private var busy = false6768    init(onRestored: (() -> Void)? = nil) {69        self.onRestored = onRestored70    }7172    var estimate: PasswordQuality.Estimate? { newPassword.isEmpty ? nil : store.service?.passwordQuality(newPassword) }73    var canRestore: Bool { fileURL != nil && !backupPassword.isEmpty && !newPassword.isEmpty && newPassword == confirmation }7475    var body: some View {76        SecurityScroll {77            if restored {78                ResultView(status: .sent, title: "Wallet restored",79                           message: "The vault was created with the new password and every record of the backup was imported. Biometric and PIN unlock are set up again on this device, from the vault screen.")80                if let onRestored {81                    Button("Continue") { onRestored() }.buttonStyle(.qPrimary)82                }83            } else if store.snapshot?.hasWallet == true {84                EmptyStateView(systemImage: "externaldrive", title: "A wallet already exists on this device",85                               message: "A backup is restored on a device without wallet. To replace this wallet, delete it first from the vault screen, after checking its own recovery phrase.")86            } else {87                form88            }89        }90        .navigationTitle("Restore from backup")91        .navigationBarTitleDisplayMode(.inline)92        .privacySensitive()93        .fileImporter(isPresented: $picking, allowedContentTypes: [SecurityFiles.backupType, .data]) { result in94            switch result {95            case .success(let url): inspect(url)96            case .failure(let failure): error = failure.localizedDescription97            }98        }99        .onDisappear {100            backupPassword = ""101            newPassword = ""102            confirmation = ""103            SecurityFiles.remove(fileURL)104        }105        .sensoryFeedback(.success, trigger: restored)106    }107108    @ViewBuilder var form: some View {109        Explanation("Choose the \u{201C}.\(BackupFile.fileExtension)\u{201D} file made by QYVORA. It is decrypted with its backup password; this device then protects the wallet with a new vault password.")110        Button { picking = true } label: { Label(header == nil ? "Choose the backup file" : "Choose another file", systemImage: "doc.viewfinder") }111            .buttonStyle(header == nil ? AnyButtonStyle(.qPrimary) : AnyButtonStyle(.qSecondary))112        if let header {113            if let fileName { Text(fileName).font(QFont.mono).foregroundStyle(QColor.textSecondary) }114            BackupHeaderCard(header: header)115            if header.isSigned, header.signerFingerprint != nil {116                QListSection(footnote: "Compare the fingerprint above with the one shown in Quantum Identity on the device that made the backup. When on, the restore is refused if the verified signer is anyone else.") {117                    SecToggleRow(title: "Accept only this signer", systemImage: "person.badge.shield.checkmark", isOn: $pinSigner)118                }119            } else if !header.isSigned {120                WarningBanner(.info, message: "This backup is not signed: its origin cannot be checked. Its integrity is still protected by the backup password.")121            }122            PasswordField("Backup password", text: $backupPassword)123            PasswordField("New vault password", text: $newPassword, strength: estimate.map(PasswordStrength.init), isNewPassword: true)124            PasswordField("Repeat the new vault password", text: $confirmation, isNewPassword: true)125            if !confirmation.isEmpty, confirmation != newPassword {126                Label("The two entries differ.", systemImage: QTone.warning.systemImage).font(QFont.caption).foregroundStyle(QColor.warning)127            }128        }129        SecInlineError(error)130        if header != nil {131            LoadingButton("Restore wallet", loadingTitle: "Decrypting and creating the vault", systemImage: "arrow.counterclockwise", state: busy ? .loading : .idle) { restore() }132                .disabled(!canRestore)133        }134    }135136    func inspect(_ url: URL) {137        guard !busy else { return }138        busy = true139        error = nil140        header = nil141        SecurityFiles.remove(fileURL)142        fileURL = nil143        fileName = url.lastPathComponent144        Task {145            do {146                let local = try SecurityFiles.importedCopy(of: url)147                fileURL = local148                header = try await store.run { try await $0.inspectBackup(at: local) }149            } catch {150                self.error = SecurityError.text(error)151            }152            busy = false153        }154    }155156    func restore() {157        guard canRestore, !busy, let url = fileURL else { return }158        busy = true159        error = nil160        let backup = backupPassword, fresh = newPassword161        let expected = pinSigner ? header?.signerFingerprint : nil162        Task {163            do {164                try await store.run { try await $0.restoreBackup(from: url, backupPassword: backup, newPassword: fresh, expectedSignerFingerprint: expected) }165                backupPassword = ""166                newPassword = ""167                confirmation = ""168                SecurityFiles.remove(url)169                fileURL = nil170                await store.refresh()171                restored = true172            } catch WalletError.wrongPassword {173                self.error = "The backup password is wrong, or the file was modified."174            } catch {175                self.error = SecurityError.text(error)176            }177            busy = false178        }179    }180}181182/// Type-erased button style, to choose between the primary and the secondary style at run time.183struct AnyButtonStyle: ButtonStyle {184    private let make: (Configuration) -> AnyView185186    init<S: ButtonStyle>(_ style: S) {187        make = { AnyView(style.makeBody(configuration: $0)) }188    }189190    func makeBody(configuration: Configuration) -> some View {191        make(configuration)192    }193}194
Files main
Menu

Theme