SPB Git

Repository Public

IdentityView.swift 12.8 KB 291 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Security/IdentityView.swift8// Module           : Security9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0513//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/// Quantum Identity: the wallet's post-quantum identity (creation, fingerprint, public export, rotation) and the46/// entries to sign, verify and check a contact. The identity is separate from the keys of every blockchain account and47/// signs no blockchain transaction.48struct IdentityView: View {49    enum Phase: Equatable {50        case loading51        case unavailable(String)52        case none53        case ready(IdentitySummary)54    }5556    @Environment(WalletStore.self) private var store57    @State private var phase: Phase = .loading58    @State private var export: QRExport?59    @State private var chain: Bytes?60    @State private var rotation: IdentityRotationResult?61    @State private var error: String?62    @State private var busy: String?63    @State private var confirmRotation = false64    @State private var reauthenticate = false65    @State private var changeCount = 06667    typealias Bytes = [UInt8]6869    var body: some View {70        SecurityScroll {71            Explanation("A post-quantum identity signs backups, device-to-device transfers and messages. It is a separate set of keys: it is not derived from the recovery phrase, it is not the key of any blockchain account, and it signs no blockchain transaction.")72            SecInlineError(error)73            switch phase {74            case .loading:75                SecSkeletonSection(title: "Fingerprint", rows: 3)76            case .unavailable(let reason):77                UnavailableDataView(reason: reason, title: "Identity unavailable", compact: true) { Task { await load() } }78            case .none:79                creation80            case .ready(let identity):81                ready(identity)82            }83            algorithms84        }85        .navigationTitle("Quantum Identity")86        .navigationBarTitleDisplayMode(.inline)87        .task(id: store.snapshot?.vault) { await load() }88        .confirmationDialog("Rotate the identity?", isPresented: $confirmRotation, titleVisibility: .visible) {89            Button("Rotate identity") { reauthenticate = true }90            Button("Cancel", role: .cancel) {}91        } message: {92            Text("New keys replace the current ones and the old private keys are deleted. A rotation certificate, signed by both the old and the new identity, lets people who trusted the old fingerprint verify the new one. Rotating takes a while: both signatures include SLH-DSA.")93        }94        .requiresReauthentication(isPresented: $reauthenticate, reason: "Rotate the identity") { rotate() }95        .sensoryFeedback(.success, trigger: changeCount)96        #if DEBUG97        .task {98            await load()99            if SecurityDebug.action == "export" { loadExport() }100            if SecurityDebug.action == "rotate" { reauthenticate = true }101        }102        #endif103    }104105    // MARK: Sections106107    var creation: some View {108        QListSection {109            VStack(alignment: .leading, spacing: QSpace.m) {110                Label("No identity yet", systemImage: "person.text.rectangle").font(QFont.headline).foregroundStyle(QColor.textPrimary)111                Explanation("Creating one generates three key pairs on this device and stores them in the vault. Key generation takes a moment.")112                LoadingButton("Create identity", loadingTitle: "Generating keys", systemImage: "plus", state: busy == "create" ? .loading : .idle) { create() }113            }114            .padding(.vertical, QMetric.padding)115        }116    }117118    @ViewBuilder func ready(_ identity: IdentitySummary) -> some View {119        QListSection("Fingerprint", footnote: "Compare the fingerprint by eye or by voice before trusting an identity. It is public.", separatorInset: QMetric.padding) {120            FingerprintView(text: identity.fingerprintText)121                .padding(.vertical, QSpace.m)122            SecFactRow(label: "Created", value: SecurityFormat.date(identity.createdAt))123            SecFactRow(label: "Rotations", value: "\(identity.rotationCount)")124        }125        .id("fingerprint")126127        VStack(alignment: .leading, spacing: QSpace.s) {128            if let export {129                QEyebrow("Public identity").padding(.leading, 2)130                QRExportCard(frames: export.frames, text: export.text, label: "Public identity")131                    .transition(.opacity)132                Text("Public keys only. The other device scans the frames in any order.")133                    .font(QFont.caption).foregroundStyle(QColor.textSecondary).padding(.horizontal, 2)134            } else {135                QListSection("Public identity", footnote: "Public keys only. The other device scans the frames in any order.") {136                    Button { loadExport() } label: {137                        HStack(spacing: QSpace.s) {138                            SecRowLabel(title: "Show public identity", subtitle: "Animated QR code and text to share", systemImage: "qrcode", chevron: busy != "export")139                            if busy == "export" { ProgressView().controlSize(.small) }140                        }141                    }142                    .buttonStyle(.qRow)143                }144            }145        }146        .qAnimation(value: export != nil)147        .id("export")148149        QListSection("Use") {150            SecLinkRow(title: "Sign a message", subtitle: "ML-DSA-87, optionally with SLH-DSA", systemImage: "signature", value: SecurityRoute.identitySign)151            SecLinkRow(title: "Verify a signature", subtitle: "Against a pasted or scanned identity", systemImage: "checkmark.seal", value: SecurityRoute.identityVerify)152            SecLinkRow(title: "Check a contact's identity", subtitle: "Read a fingerprint before a transfer", systemImage: "person.crop.circle.badge.checkmark",153                       value: SecurityRoute.identityContact)154        }155        .id("use")156157        QListSection("Rotation", footnote: "Rotate when the device may have been compromised, or on a schedule of your own.") {158            Button { confirmRotation = true } label: {159                HStack(spacing: QSpace.s) {160                    SecRowLabel(title: "Rotate identity", subtitle: "New keys, linked by a signed certificate", systemImage: "arrow.triangle.2.circlepath", chevron: busy != "rotate")161                    if busy == "rotate" { ProgressView().controlSize(.small) }162                }163            }164            .buttonStyle(.qRow)165            .disabled(busy != nil)166            if let rotation {167                VStack(alignment: .leading, spacing: QSpace.s) {168                    Label("Identity rotated", systemImage: QTone.positive.systemImage).font(QFont.callout.weight(.semibold)).foregroundStyle(QColor.positive)169                    Explanation("Give this certificate to people who trusted the previous fingerprint.")170                    shareBinary("Rotation certificate", rotation.certificate)171                }172                .padding(.vertical, QSpace.m)173            }174            if let chain {175                VStack(alignment: .leading, spacing: QSpace.s) {176                    Explanation("The rotation chain holds every certificate since the first identity (\(identity.rotationCount)). A peer who knows the first fingerprint can verify the current one with it.")177                    shareBinary("Rotation chain", chain)178                }179                .padding(.vertical, QSpace.m)180            }181        }182        .id("rotation")183    }184185    var algorithms: some View {186        QListSection("The three algorithms", footnote: "These algorithms protect what the identity signs and what is sent to it. They do not change how any blockchain validates transactions.",187                     separatorInset: QMetric.padding) {188            algorithm("ML-DSA-87", "Lattice signature (FIPS 204). Signs every message, backup and certificate.")189            algorithm("SLH-DSA-SHAKE-256f", "Hash-based signature (FIPS 205). Optional second signature that does not rely on lattices; large and slow.")190            algorithm("ML-KEM-1024 with X25519", "Key encapsulation (FIPS 203) combined with a classical exchange. Encrypts a transfer for the receiving device.")191        }192        .id("algorithms")193    }194195    func algorithm(_ name: String, _ detail: String) -> some View {196        VStack(alignment: .leading, spacing: 3) {197            Text(name).font(QFont.headline).foregroundStyle(QColor.textPrimary)198            Text(detail).font(QFont.caption).foregroundStyle(QColor.textSecondary)199        }200        .fixedSize(horizontal: false, vertical: true)201        .frame(maxWidth: .infinity, alignment: .leading)202        .padding(.vertical, QSpace.m)203        .accessibilityElement(children: .combine)204    }205206    func shareBinary(_ label: String, _ bytes: Bytes) -> some View {207        let text = SecurityFormat.base64(bytes)208        return HStack(spacing: QSpace.m) {209            Text("\(label) · \(bytes.count) bytes").font(QFont.caption).foregroundStyle(QColor.textSecondary)210            Spacer(minLength: QSpace.s)211            CopyButton(text, title: "Copy \(label.lowercased())")212            ShareLink(item: text) { Image(systemName: "square.and.arrow.up").frame(minWidth: 44, minHeight: 44) }213                .tint(QColor.violet)214                .accessibilityLabel("Share \(label.lowercased())")215        }216    }217218    // MARK: Actions219220    func load() async {221        guard let snapshot = store.snapshot else { return }222        guard snapshot.hasWallet else {223            phase = .unavailable("No wallet on this device.")224            return225        }226        guard snapshot.vault.exists else {227            phase = .unavailable("A watch-only wallet has no vault, so it cannot hold identity keys.")228            return229        }230        guard let service = store.service else { return }231        do {232            if let identity = try await service.identity() {233                phase = .ready(identity)234                chain = identity.rotationCount > 0 ? try await service.identityRotationChain() : nil235            } else {236                phase = .none237            }238        } catch {239            phase = .unavailable(SecurityError.text(error))240        }241    }242243    func create() {244        guard busy == nil else { return }245        busy = "create"246        error = nil247        Task {248            do {249                phase = .ready(try await store.run { try await $0.createIdentity() })250                changeCount += 1251            } catch {252                self.error = SecurityError.text(error)253            }254            busy = nil255        }256    }257258    func loadExport() {259        guard busy == nil else { return }260        busy = "export"261        error = nil262        Task {263            do {264                export = try await store.run { try await $0.exportPublicIdentity() }265            } catch {266                self.error = SecurityError.text(error)267            }268            busy = nil269        }270    }271272    func rotate() {273        guard busy == nil else { return }274        busy = "rotate"275        error = nil276        Task {277            do {278                let result = try await store.run { try await $0.rotateIdentity(dual: true) }279                rotation = result280                export = nil281                phase = .ready(result.identity)282                chain = try? await store.service?.identityRotationChain()283                changeCount += 1284            } catch {285                self.error = SecurityError.text(error)286            }287            busy = nil288        }289    }290}291
Files main
Menu

Theme