SPB Git

Repository Public

TransferReceiveView.swift 12.5 KB 270 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Security/TransferReceiveView.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/// New iPhone side of a device-to-device transfer, on a device without wallet.48///49/// Entry point for onboarding: push or present `TransferReceiveView(onRestored:)`. It shows the temporary receiving50/// identity (`beginTransferReception`) as animated QR frames, scans the package shown by the old iPhone51/// (`assembleTransferPackage`), opens its envelope and verifies its signature without restoring anything52/// (`inspectTransferPackage`), has the user compare the sender's fingerprint with the old iPhone, and only then53/// asks for the passwords and restores the wallet (`completeTransferReception`, pinned to the confirmed sender).54struct TransferReceiveView: View {55    var onRestored: (() -> Void)?5657    @Environment(WalletStore.self) private var store58    @State private var identity: IdentitySummary?59    @State private var export: QRExport?60    @State private var package: [UInt8]?61    @State private var transferPassword = ""62    @State private var newPassword = ""63    @State private var confirmation = ""64    /// What the package says about its sender, verified, before anything is restored.65    @State private var inspection: TransferPackageInspection?66    /// The user compared the sender's fingerprint with the old iPhone and confirmed that they match.67    @State private var senderConfirmed = false68    @State private var senderFingerprint: String?69    @State private var error: String?70    @State private var busy = false71    @State private var scanning = false72    @State private var picking = false7374    init(onRestored: (() -> Void)? = nil) {75        self.onRestored = onRestored76    }7778    var estimate: PasswordQuality.Estimate? { newPassword.isEmpty ? nil : store.service?.passwordQuality(newPassword) }79    var canRestore: Bool {80        package != nil && inspection != nil && senderConfirmed && !transferPassword.isEmpty && !newPassword.isEmpty && newPassword == confirmation81    }8283    var body: some View {84        SecurityScroll {85            if let senderFingerprint {86                done(senderFingerprint)87            } else if store.snapshot?.hasWallet == true {88                EmptyStateView(systemImage: "iphone.and.arrow.forward", title: "A wallet already exists on this device",89                               message: "A transfer is received on a device without wallet. On the iPhone that holds the wallet, use Quantum Recovery, then Transfer to a new iPhone.")90            } else if let identity, let export {91                if package == nil {92                    showIdentity(identity, export)93                } else if let inspection {94                    if senderConfirmed {95                        passwords96                    } else {97                        compareSender(inspection)98                    }99                } else if error == nil {100                    SecSkeletonSection(title: "Verifying the signature of the package", rows: 2)101                } else {102                    Button("Scan again") { discardPackage() }.buttonStyle(.qSecondary)103                }104            } else if error == nil {105                LoadingRow("Generating a temporary receiving identity")106            }107            if senderFingerprint == nil { SecInlineError(error) }108        }109        .navigationTitle("Receive from another iPhone")110        .navigationBarTitleDisplayMode(.inline)111        .privacySensitive()112        .task { await begin() }113        .sheet(isPresented: $scanning) {114            PayloadScannerSheet(title: "Scan the old iPhone", prompt: "Keep the animated code of the old iPhone in the frame") { assemble($0) }115        }116        .fileImporter(isPresented: $picking, allowedContentTypes: [.data]) { result in117            switch result {118            case .success(let url): readFile(url)119            case .failure(let failure): error = failure.localizedDescription120            }121        }122        .onDisappear {123            transferPassword = ""124            newPassword = ""125            confirmation = ""126            package = nil127            inspection = nil128            senderConfirmed = false129        }130        .sensoryFeedback(.success, trigger: senderFingerprint)131    }132133    @ViewBuilder func showIdentity(_ identity: IdentitySummary, _ export: QRExport) -> some View {134        SectionHeader("1 · Show this to the old iPhone", subtitle: "On the old iPhone: Settings, Quantum Recovery, Transfer to a new iPhone.")135        QRExportCard(frames: export.frames, text: nil, label: "Receiving identity of this iPhone")136        QListSection("Fingerprint of this iPhone", footnote: "The old iPhone shows this fingerprint after scanning. Check that both are the same before going on. The identity is temporary and kept in memory only.") {137            FingerprintView(text: identity.fingerprintText, copyable: false).padding(.vertical, QSpace.m)138        }139        SectionHeader("2 · Scan the package", subtitle: "The old iPhone then shows its own animated code.")140            .padding(.top, 8)141        Button { scanning = true } label: { Label("Scan the old iPhone", systemImage: "qrcode.viewfinder") }.buttonStyle(.qPrimary)142        Button { picking = true } label: { Label("Open a package file instead", systemImage: "doc") }.buttonStyle(.qSecondary)143    }144145    /// Step 3: nothing has been restored yet. The user compares the verified sender with the old iPhone first.146    @ViewBuilder func compareSender(_ inspection: TransferPackageInspection) -> some View {147        WarningBanner(.info, title: "Package received, nothing restored yet",148                      message: "The package (\(package?.count ?? 0) bytes) was opened with this iPhone's temporary identity and its signature verifies. No wallet has been created on this iPhone.")149        SectionHeader("3 · Compare the sender", subtitle: "The old iPhone shows the fingerprint of its identity under the package.")150        QListSection("Fingerprint of the sender", footnote: "Read the sixteen groups on both iPhones. If one group differs, the package did not come from the old iPhone.") {151            FingerprintView(text: inspection.sender.fingerprintText, copyable: false).padding(.vertical, QSpace.m)152        }153        QListSection("Backup inside the package") {154            SecFactRow(label: "Created", value: SecurityFormat.date(inspection.backup.createdAt))155            SecFactRow(label: "Records", value: "\(inspection.backup.recordCount)")156            SecFactRow(label: "Signed by the sender", value: inspection.backup.isSigned ? "Yes" : "No")157        }158        Button("The fingerprints match") { senderConfirmed = true }.buttonStyle(.qPrimary)159        Button("They differ: discard the package") { discardPackage() }.buttonStyle(.qSecondary)160    }161162    @ViewBuilder var passwords: some View {163        WarningBanner(.positive, message: "Sender confirmed. The wallet is restored only from a package signed by that identity.")164        SectionHeader("4 · Passwords")165        PasswordField("Transfer password (chosen on the old iPhone)", text: $transferPassword)166        PasswordField("New vault password for this iPhone", text: $newPassword, strength: estimate.map(PasswordStrength.init), isNewPassword: true)167        PasswordField("Repeat the new vault password", text: $confirmation, isNewPassword: true)168        if !confirmation.isEmpty, confirmation != newPassword {169            Label("The two entries differ.", systemImage: QTone.warning.systemImage).font(QFont.caption).foregroundStyle(QColor.warning)170        }171        LoadingButton("Restore the wallet", loadingTitle: "Verifying and creating the vault", systemImage: "arrow.counterclockwise", state: busy ? .loading : .idle) { complete() }172            .disabled(!canRestore)173        Button("Scan again") { discardPackage() }.buttonStyle(.qSecondary).disabled(busy)174    }175176    @ViewBuilder func done(_ fingerprint: String) -> some View {177        ResultView(status: .sent, title: "Wallet received",178                   message: "The package was signed by the identity you confirmed and its signature verified. The vault is unlocked with the new password.")179        QListSection("Fingerprint of the sender") {180            FingerprintView(text: fingerprint, copyable: false).padding(.vertical, QSpace.m)181        }182        if let onRestored {183            Button("Continue") { onRestored() }.buttonStyle(.qPrimary)184        }185    }186187    func discardPackage() {188        package = nil189        inspection = nil190        senderConfirmed = false191        error = nil192    }193194    /// Opens the envelope and verifies its signature. Restores nothing.195    func inspect(_ bytes: [UInt8]) {196        inspection = nil197        senderConfirmed = false198        Task {199            do {200                inspection = try await store.run { try await $0.inspectTransferPackage(package: bytes) }201            } catch {202                self.error = "This package cannot be used: it was not made for this iPhone, it was modified, or it is not a transfer package. "203                    + SecurityError.text(error)204            }205        }206    }207208    func begin() async {209        guard identity == nil, store.snapshot?.hasWallet != true else { return }210        do {211            let started = try await store.run { try await $0.beginTransferReception() }212            identity = started.identity213            export = started.export214        } catch {215            self.error = SecurityError.text(error)216        }217    }218219    func assemble(_ frames: [String]) {220        guard let service = store.service else { return }221        error = nil222        do {223            let bytes = try service.assembleTransferPackage(frames: frames)224            package = bytes225            inspect(bytes)226        } catch {227            self.error = SecurityError.text(error)228        }229    }230231    func readFile(_ url: URL) {232        error = nil233        do {234            let local = try SecurityFiles.importedCopy(of: url)235            defer { SecurityFiles.remove(local) }236            let bytes = Array(try Data(contentsOf: local))237            package = bytes238            inspect(bytes)239        } catch {240            self.error = "The package file cannot be read."241        }242    }243244    func complete() {245        guard canRestore, !busy, let bytes = package, let sender = inspection?.sender.text else { return }246        busy = true247        error = nil248        let transfer = transferPassword, fresh = newPassword249        Task {250            do {251                let fingerprint = try await store.run {252                    try await $0.completeTransferReception(package: bytes, backupPassword: transfer, newPassword: fresh, expectedSender: sender)253                }254                transferPassword = ""255                newPassword = ""256                confirmation = ""257                package = nil258                inspection = nil259                await store.refresh()260                senderFingerprint = fingerprint261            } catch WalletError.wrongPassword {262                self.error = "The transfer password is wrong, or the package was modified."263            } catch {264                self.error = SecurityError.text(error)265            }266            busy = false267        }268    }269}270
Files main
Menu

Theme