SPB Git

Repository Public

BackupRestoreView.swift 18.6 KB 392 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP ID & Card Vault7// File             : SPVault/Features/Settings/BackupRestoreView.swift8// Module           : SPVault9// Repository       : https://git.spboucher.ai/sp-id-card-vault10// Project Website  : Not specified11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//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 UniformTypeIdentifiers4344extension UTType {45    /// `.spvault` — declared in Info.plist as an exported type.46    static let spVaultBackup = UTType(exportedAs: "ai.spboucher.spvault", conformingTo: .data)47}4849/// Wraps the already-encrypted backup bytes for the system exporter.50struct SPVaultBackupDocument: FileDocument {51    static let readableContentTypes: [UTType] = [.spVaultBackup]52    var data: Data5354    init(data: Data) { self.data = data }5556    init(configuration: ReadConfiguration) throws {57        guard let data = configuration.file.regularFileContents else { throw CocoaError(.fileReadCorruptFile) }58        self.data = data59    }6061    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {62        FileWrapper(regularFileWithContents: data)63    }64}6566enum BackupMessages {67    static func describe(_ error: any Error) -> String {68        switch error {69        case BackupError.wrongPassphrase: "Wrong passphrase. This backup cannot be opened with it."70        case BackupError.corrupted: "This backup is damaged or incomplete. Nothing was restored."71        case BackupError.notABackup: "This file is not an SP Vault backup."72        case BackupError.unsupportedVersion(let version): "This backup uses format version \(version), which this version of SP Vault cannot read."73        case BackupError.weakPassphrase, VaultError.weakPassphrase: "Choose a longer, less predictable passphrase."74        case VaultError.locked: "The vault locked before the operation finished. Unlock and try again."75        case let error as CocoaError where error.code == .fileWriteOutOfSpace: "There is not enough free space on this iPhone."76        default: "The operation failed. Nothing was changed."77        }78    }7980    /// Reads a user-picked file through its security scope.81    static func read(_ url: URL) throws -> Data {82        let scoped = url.startAccessingSecurityScopedResource()83        defer { if scoped { url.stopAccessingSecurityScopedResource() } }84        return try Data(contentsOf: url)85    }86}8788/// A picked backup file, checked to be a `.spvault` container.89struct PickedBackup: Identifiable, Equatable {90    let id = UUID()91    var name: String92    var data: Data93    var header: BackupArchive.Header9495    init(url: URL) throws {96        let data = try BackupMessages.read(url)97        header = try BackupArchive.readHeader(data)98        self.data = data99        name = url.lastPathComponent100    }101102    #if DEBUG103    init(name: String, data: Data) throws {104        header = try BackupArchive.readHeader(data)105        self.data = data106        self.name = name107    }108    #endif109110    static func == (a: PickedBackup, b: PickedBackup) -> Bool { a.id == b.id }111}112113/// Passphrase entry + verification for a picked backup. `onVerified` receives114/// the passphrase once the whole file has authenticated with it.115struct BackupUnlockSheet: View {116    var backup: PickedBackup117    /// Offer merge/replace (restore into an existing vault) or not (onboarding).118    var asksMode: Bool119    var onVerified: (String, RestoreMode) async -> String?120121    @State private var passphrase = ""122    @State private var mode: RestoreMode = .merge123    @State private var isWorking = false124    @State private var error: String?125    @Environment(\.dismiss) private var dismiss126127    var body: some View {128        SheetScaffold(eyebrow: "Restore", title: "Open this backup") {129            VStack(spacing: 0) {130                DetailRow("File", backup.name, symbol: "doc.fill")131                Hairline()132                DetailRow("Created", backup.header.createdAt.spShort, symbol: "calendar")133                Hairline()134                DetailRow("KDF", "PBKDF2 · \(backup.header.kdf.iterations.formatted()) iterations", symbol: "function")135            }136            .padding(.horizontal, SP.Space.m)137            .spPanel(padding: 0)138139            SPTextField(title: "Backup passphrase", text: $passphrase, prompt: "Chosen when the backup was made", secure: true, capitalization: .never)140                .accessibilityIdentifier("restore.passphrase")141142            if asksMode {143                VStack(alignment: .leading, spacing: SP.Space.xs) {144                    Text("Existing cards").spEyebrow()145                    ChoiceChips(options: [(RestoreMode.merge, "Merge", "arrow.triangle.merge"), (RestoreMode.replace, "Replace", "arrow.2.squarepath")],146                                selection: $mode, identifierPrefix: "restore.mode")147                    Text(mode == .merge ? "Cards in the backup are added; a card that already exists is replaced by its backup copy."148                                        : "Every card currently in the vault is deleted first, then the backup is restored.")149                        .font(.spCaption).foregroundStyle(mode == .replace ? SP.Palette.warning : SP.Palette.textSecondary)150                        .fixedSize(horizontal: false, vertical: true)151                }152            }153154            if let error {155                NoticeView(tone: .critical, symbol: "exclamationmark.triangle.fill", title: nil, message: error)156                    .accessibilityIdentifier("restore.error")157            }158159            Button {160                Task {161                    isWorking = true162                    error = await onVerified(passphrase, mode)163                    isWorking = false164                    if error == nil { dismiss() } else { Haptics.shared.play(.error) }165                }166            } label: {167                HStack(spacing: SP.Space.xs) {168                    if isWorking { ProgressView().tint(.white) }169                    Text(isWorking ? "Verifying and decrypting…" : "Restore")170                }171            }172            .buttonStyle(.spPrimary)173            .disabled(passphrase.isEmpty || isWorking)174            .accessibilityIdentifier("restore.submit")175        }176        .interactiveDismissDisabled(isWorking)177        .presentationDetents([.large])178    }179}180181extension RestoreMode: Hashable {}182183/// Backup & Restore. Backups are `.spvault` files that contain only ciphertext;184/// there is no unencrypted export.185struct BackupRestoreView: View {186    @Environment(Vault.self) private var vault187    @Environment(AppEnvironment.self) private var environment188189    @State private var showsExportSheet = false190    @State private var exportDocument: SPVaultBackupDocument?191    @State private var exportName = "SP Vault"192    @State private var showsExporter = false193    @State private var showsImporter = false194    @State private var picked: PickedBackup?195    @State private var notice: (tone: StatusTone, symbol: String, text: String)?196197    private var backupAge: (text: String, tone: StatusTone) {198        let level = SecurityAssessment.backupLevel(lastBackup: vault.lastBackupAt, cardCount: vault.cards.count, now: Date())199        guard let last = vault.lastBackupAt else { return (vault.cards.isEmpty ? "Nothing to back up yet" : "Never", level.tone) }200        return ("\(last.spShort) · \(last.spRelative)", level.tone)201    }202203    var body: some View {204        ScreenScaffold(eyebrow: "Encrypted · offline", title: "Backup", showsBack: true) {205            statusPanel206207            if let notice {208                NoticeView(tone: notice.tone, symbol: notice.symbol, title: nil, message: notice.text)209                    .accessibilityIdentifier("backup.notice")210            }211212            if exportDocument != nil {213                VStack(alignment: .leading, spacing: SP.Space.s) {214                    HStack(spacing: SP.Space.s) {215                        IconBadge(symbol: "checkmark.seal.fill", tint: SP.Palette.positive, size: 40)216                        VStack(alignment: .leading, spacing: 2) {217                            Text("Backup ready").font(.spHeadline).foregroundStyle(SP.Palette.textPrimary)218                            Text(exportName + ".spvault").font(.spCaption).foregroundStyle(SP.Palette.textSecondary).lineLimit(1).truncationMode(.middle)219                        }220                    }221                    Text("Choose where to keep it: Files, an external drive or another device. Until it is saved, it exists only in memory.")222                        .font(.spCaption).foregroundStyle(SP.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)223                    Button { showsExporter = true } label: { Label("Save to Files…", systemImage: "square.and.arrow.down") }224                        .buttonStyle(.spPrimary)225                        .accessibilityIdentifier("backup.save")226                    Button("Discard") { exportDocument = nil }.buttonStyle(.spQuiet)227                }228                .spPanel()229            }230231            VStack(alignment: .leading, spacing: SP.Space.s) {232                SectionHeader("Export")233                VStack(alignment: .leading, spacing: SP.Space.s) {234                    Text("Create a full backup").font(.spHeadline).foregroundStyle(SP.Palette.textPrimary)235                    Text("Every card, both photographs and your categories, sealed in one .spvault file protected by a passphrase of its own.")236                        .font(.spCallout).foregroundStyle(SP.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)237                    Button {238                        Task {239                            guard await vault.reauthenticate(reason: "Confirm it is you before exporting your vault") else {240                                notice = (.warning, "faceid", "Face ID did not confirm. Nothing was exported.")241                                return242                            }243                            notice = nil244                            showsExportSheet = true245                        }246                    } label: { Label("Export encrypted backup", systemImage: "lock.doc.fill") }247                        .buttonStyle(.spPrimary)248                        .disabled(vault.cards.isEmpty)249                        .accessibilityIdentifier("backup.export")250                    if vault.cards.isEmpty {251                        Text("Add a card first.").font(.spCaption).foregroundStyle(SP.Palette.textTertiary)252                    }253                }254                .spPanel()255            }256257            VStack(alignment: .leading, spacing: SP.Space.s) {258                SectionHeader("Restore")259                VStack(alignment: .leading, spacing: SP.Space.s) {260                    Text("Restore from a backup").font(.spHeadline).foregroundStyle(SP.Palette.textPrimary)261                    Text("Pick a .spvault file. It is verified in full before anything is written, and every card is re-encrypted with new keys for this iPhone.")262                        .font(.spCallout).foregroundStyle(SP.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)263                    Button { showsImporter = true } label: { Label("Choose a backup file…", systemImage: "folder") }264                        .buttonStyle(.spSecondary)265                        .accessibilityIdentifier("backup.import")266                }267                .spPanel()268            }269270            PanelSection("Format") {271                VStack(spacing: 0) {272                    DetailRow("Container", ".spvault · version \(BackupArchive.version)", symbol: "shippingbox.fill")273                    Hairline()274                    DetailRow("Cipher", "AES-256-GCM", symbol: "lock.fill")275                    Hairline()276                    DetailRow("KDF", "PBKDF2-HMAC-SHA256", symbol: "function")277                    Hairline()278                    DetailRow("Iterations", KDFParameters.defaultIterations.formatted(), symbol: "repeat")279                    Hairline()280                    DetailRow("Clear text in file", "None", symbol: "eye.slash.fill")281                }282                .padding(.horizontal, SP.Space.m)283            }284            Text("The passphrase is never stored. Without it a backup cannot be opened by anyone, including you.")285                .font(.spCaption).foregroundStyle(SP.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)286        }287        .sheet(isPresented: $showsExportSheet) {288            BackupExportSheet { url in289                // The temporary file holds ciphertext only; it is read into290                // memory and removed at once.291                defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }292                guard let data = try? Data(contentsOf: url) else {293                    notice = (.critical, "exclamationmark.triangle.fill", "The backup could not be prepared.")294                    return295                }296                exportName = url.deletingPathExtension().lastPathComponent297                exportDocument = SPVaultBackupDocument(data: data)298                Haptics.shared.play(.success)299            }300        }301        .fileExporter(isPresented: $showsExporter, document: exportDocument, contentType: .spVaultBackup, defaultFilename: exportName) { result in302            switch result {303            case .success:304                exportDocument = nil305                notice = (.positive, "checkmark.circle.fill", "Backup saved. Keep the passphrase somewhere safe: it cannot be recovered.")306            case .failure:307                notice = (.critical, "exclamationmark.triangle.fill", "The backup was not saved.")308            }309        }310        .fileImporter(isPresented: $showsImporter, allowedContentTypes: [.spVaultBackup, .data]) { result in311            guard case .success(let url) = result else { return }312            do { picked = try PickedBackup(url: url); notice = nil }313            catch { notice = (.critical, "exclamationmark.triangle.fill", BackupMessages.describe(error is BackupError ? error : BackupError.notABackup)) }314        }315        .sheet(item: $picked) { backup in316            BackupUnlockSheet(backup: backup, asksMode: !vault.cards.isEmpty) { passphrase, mode in317                do {318                    let count = try await vault.restoreBackup(backup.data, passphrase: passphrase, mode: mode)319                    notice = (.positive, "checkmark.circle.fill", count == 1 ? "1 card restored and re-encrypted for this iPhone." : "\(count) cards restored and re-encrypted for this iPhone.")320                    Haptics.shared.play(.success)321                    return nil322                } catch {323                    return BackupMessages.describe(error)324                }325            }326        }327    }328329    private var statusPanel: some View {330        HStack(spacing: SP.Space.m) {331            IconBadge(symbol: "externaldrive.fill.badge.checkmark", tint: backupAge.tone.color, size: 48)332            VStack(alignment: .leading, spacing: 4) {333                Text("Last backup").spEyebrow()334                Text(backupAge.text).font(.spHeadline).foregroundStyle(SP.Palette.textPrimary)335                    .fixedSize(horizontal: false, vertical: true)336                    .accessibilityIdentifier("backup.last")337                Text(vault.cards.count == 1 ? "1 card in the vault" : "\(vault.cards.count) cards in the vault")338                    .font(.spCaption).foregroundStyle(SP.Palette.textSecondary)339            }340            Spacer(minLength: 0)341        }342        .spPanel()343        .accessibilityElement(children: .combine)344    }345}346347/// Passphrase for a new backup, then the encryption itself.348private struct BackupExportSheet: View {349    var onExported: (URL) -> Void350351    @Environment(Vault.self) private var vault352    @Environment(\.dismiss) private var dismiss353    @State private var passphrase = ""354    @State private var confirmation = ""355    @State private var isWorking = false356    @State private var error: String?357358    var body: some View {359        SheetScaffold(eyebrow: "Export", title: "Protect this backup") {360            Text("Choose a passphrase for this backup. It is separate from Face ID and from your recovery passphrase, and it is the only thing that can open the file.")361                .font(.spCallout).foregroundStyle(SP.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)362            PassphraseFields(title: "Backup passphrase", passphrase: $passphrase, confirmation: $confirmation, identifierPrefix: "export")363            if let error { NoticeView(tone: .critical, symbol: "exclamationmark.triangle.fill", title: nil, message: error) }364            Button {365                Task {366                    isWorking = true367                    defer { isWorking = false }368                    do {369                        let url = try await vault.exportBackup(passphrase: passphrase)370                        passphrase = ""; confirmation = ""371                        dismiss()372                        onExported(url)373                    } catch {374                        self.error = BackupMessages.describe(error)375                        Haptics.shared.play(.error)376                    }377                }378            } label: {379                HStack(spacing: SP.Space.xs) {380                    if isWorking { ProgressView().tint(.white) }381                    Text(isWorking ? "Encrypting…" : "Encrypt backup")382                }383            }384            .buttonStyle(.spPrimary)385            .disabled(!PassphraseFields.isValid(passphrase, confirmation) || isWorking)386            .accessibilityIdentifier("export.submit")387        }388        .interactiveDismissDisabled(isWorking)389        .presentationDetents([.large])390    }391}392
Files main
Menu

Theme