SPB Git

Repository Public

BackupCreateView.swift 9.5 KB 205 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Security/BackupCreateView.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/// Creates an encrypted backup of every vault record (`createBackup`), protected by its own password and optionally48/// signed by the wallet identity, then hands the file to the system exporter so that the user chooses where it goes.49struct BackupCreateView: View {50    @Environment(WalletStore.self) private var store51    @State private var password = ""52    @State private var confirmation = ""53    @State private var sign = false54    @State private var hasIdentity: Bool?55    @State private var header: BackupHeader?56    @State private var document: BinaryDocument?57    @State private var exporting = false58    @State private var saved: Bool?59    @State private var error: String?60    @State private var busy = false61    @State private var reauthenticate = false6263    var estimate: PasswordQuality.Estimate? { password.isEmpty ? nil : store.service?.passwordQuality(password) }64    var canCreate: Bool { !password.isEmpty && password == confirmation }65    var profile: WalletProfile? { store.snapshot?.profile }6667    var body: some View {68        SecurityScroll {69            QListSection(footnote: "The backup holds every record of the vault: the recovery phrase (the keys of every chain), the passphrase when one is used, and the identity keys. It is encrypted with a key derived from the password below, not from the vault password.") {70                SecFactRow(label: "Last backup", value: profile?.lastBackupDate.map(SecurityFormat.date) ?? "None made on this device")71                if profile?.lastBackupDate != nil {72                    SecFactRow(label: "Signed", value: profile?.lastBackupSigned.map { $0 ? "Yes" : "No" } ?? "Not recorded")73                }74            }75            if let header {76                result(header)77            } else {78                form79            }80        }81        .navigationTitle("Encrypted backup")82        .navigationBarTitleDisplayMode(.inline)83        .privacySensitive()84        .task {85            guard hasIdentity == nil, let service = store.service else { return }86            hasIdentity = (try? await service.identity()) != nil87        }88        .requiresReauthentication(isPresented: $reauthenticate, reason: "Create an encrypted backup of the vault") { create() }89        .fileExporter(isPresented: $exporting, document: document, contentTypes: [SecurityFiles.backupType], defaultFilename: Self.fileName(),90                      onCompletion: { outcome in91                          switch outcome {92                          case .success:93                              saved = true94                              recordSaved()95                          case .failure(let failure):96                              saved = false97                              error = failure.localizedDescription98                          }99                      }, onCancellation: { saved = false })100        .onDisappear {101            password = ""102            confirmation = ""103            document = nil104        }105        .sensoryFeedback(.success, trigger: saved == true)106        #if DEBUG107        .task {108            if SecurityDebug.action == "go" {109                password = "debug backup passphrase 0000 throwaway"110                confirmation = password111                reauthenticate = true112            }113        }114        #endif115    }116117    @ViewBuilder var form: some View {118        PasswordField("Backup password", text: $password, strength: estimate.map(PasswordStrength.init), isNewPassword: true)119        PasswordField("Repeat the backup password", text: $confirmation, isNewPassword: true)120        if !confirmation.isEmpty, confirmation != password {121            Label("The two entries differ.", systemImage: QTone.warning.systemImage).font(QFont.caption).foregroundStyle(QColor.warning)122        }123        if !password.isEmpty, let reason = WalletService.passwordRejection(password) {124            WarningBanner(.warning, title: "Backup password not accepted",125                          message: reason + " A backup file leaves this device: it must resist offline guessing for as long as it exists.")126        }127        QListSection(footnote: hasIdentity == true128            ? "The signature lets a restoring device check that the file was made by this identity and was not modified."129            : hasIdentity == false ? "No identity has been created. Create one in Quantum Identity to sign backups."130            : "Checking whether an identity exists.") {131            SecToggleRow(title: "Sign with the wallet identity", systemImage: "signature", isOn: $sign).disabled(hasIdentity != true)132        }133        QListSection("Before you create it") {134            SecTextRow(text: "There is no way to recover a forgotten backup password.", systemImage: "key.slash")135            SecTextRow(text: "Where the file is kept matters. A cloud drive keeps copies you do not control, for as long as the provider chooses: there the file is exactly as strong as its password. A storage you hold yourself is safer.", systemImage: "externaldrive")136        }137        SecInlineError(error)138        LoadingButton("Create backup", loadingTitle: "Encrypting (slow key derivation)", systemImage: "externaldrive.badge.plus", state: busy ? .loading : .idle) {139            reauthenticate = true140        }141        .disabled(!canCreate)142    }143144    @ViewBuilder func result(_ header: BackupHeader) -> some View {145        switch saved {146        case .some(true):147            ResultView(status: .sent, title: "Backup saved", message: "Keep the file away from this iPhone, and the backup password away from the file.")148        case .some(false):149            WarningBanner(.warning, title: "The file has not been saved",150                          message: "The backup was encrypted but no copy was stored, so it is not recorded as the last backup. Save it now.")151        case nil:152            WarningBanner(.info, message: "The backup is encrypted. Choose where to save it.")153        }154        BackupHeaderCard(header: header)155        SecInlineError(error)156        if saved != true {157            Button { exporting = true } label: { Label("Save the backup file", systemImage: "square.and.arrow.down") }158                .buttonStyle(.qPrimary)159                .disabled(document == nil)160        }161    }162163    /// The exporter stored the file: only now does the wallet record the date of its last backup.164    func recordSaved() {165        guard let signed = header?.isSigned else { return }166        Task {167            do {168                try await store.run { try await $0.recordBackupSaved(signed: signed) }169            } catch {170                self.error = "The file was saved, but the date of the backup could not be recorded: \(SecurityError.text(error))"171            }172        }173    }174175    static func fileName() -> String {176        let formatter = DateFormatter()177        formatter.locale = Locale(identifier: "en_US_POSIX")178        formatter.dateFormat = "yyyy-MM-dd"179        return "qyvora-backup-\(formatter.string(from: Date())).\(BackupFile.fileExtension)"180    }181182    func create() {183        guard canCreate, !busy else { return }184        busy = true185        error = nil186        let secret = password, sign = sign && hasIdentity == true187        let target = SecurityFiles.temporaryURL(extension: BackupFile.fileExtension)188        Task {189            do {190                // The service writes the encrypted file; it is read back and removed so that only the user's copy remains.191                let made = try await store.run { try await $0.createBackup(to: target, password: secret, sign: sign) }192                document = BinaryDocument(data: try Data(contentsOf: target), contentType: SecurityFiles.backupType)193                header = made194                password = ""195                confirmation = ""196                exporting = true197            } catch {198                self.error = SecurityError.text(error)199            }200            SecurityFiles.remove(target)201            busy = false202        }203    }204}205
Files main
Menu

Theme