Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : App/Sources/Security/RotateMasterKeySheet.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 QyvoraVault43import QyvoraWallet44import QyvoraUI4546/// Replaces the vault master key: explains the consequences, takes the master password (and the PIN when the PIN47/// slot must be kept) and shows the result reported by the vault.48struct RotateMasterKeySheet: View {49 let pinEnabled: Bool5051 @Environment(WalletStore.self) private var store52 @Environment(\.dismiss) private var dismiss53 @State private var password = ""54 @State private var pin = ""55 @State private var keepPIN = true56 @State private var result: KeyRotationResult?57 @State private var error: String?58 @State private var busy = false5960 /// The PIN typed here is the current one: it follows the same rule as everywhere (exactly six digits).61 var pinIsUsable: Bool { !keepPIN || WalletService.pinRejection(pin) == nil }6263 var body: some View {64 ScrollView {65 VStack(alignment: .leading, spacing: 18) {66 SheetHeader("Rotate master key", subtitle: "A new master key replaces the current one.") { dismiss() }67 if let result {68 WarningBanner(.positive, title: "Master key rotated", message: "Nothing on this device remains readable with the previous key.")69 QListSection(separatorInset: QMetric.padding) {70 SecFactRow(label: "New key epoch", value: "\(result.newKeyEpoch)")71 SecFactRow(label: "Records re-encrypted", value: "\(result.recordsReencrypted)")72 SecFactRow(label: "PIN slot", value: pinEnabled ? (result.pinSlotKept ? "Kept" : "Removed") : "Not enabled")73 }74 if pinEnabled, !result.pinSlotKept {75 WarningBanner(.info, message: "PIN unlock was removed because the PIN was not supplied. Enable it again from the vault screen.")76 }77 Button("Done") { dismiss() }.buttonStyle(.qPrimary)78 } else {79 QListSection("What happens", separatorInset: QMetric.padding) {80 VStack(alignment: .leading, spacing: QSpace.s) {81 BulletLine("A new master key is generated and the key epoch increases by one.")82 BulletLine("Every record is re-encrypted and every unlock slot is wrapped again.")83 BulletLine("The previous copy of the vault file is overwritten.")84 BulletLine("Biometric unlock, when enabled, receives a new device key.")85 BulletLine("Encrypted backups made earlier are not affected: they keep their own password and key.")86 BulletLine("The recovery phrase, the addresses of every chain and the identity do not change.")87 }88 .padding(.vertical, QSpace.m)89 }90 PasswordField("Master password", text: $password)91 if pinEnabled {92 QListSection { SecToggleRow(title: "Keep PIN unlock", systemImage: "circle.grid.3x3", isOn: $keepPIN) }93 if keepPIN {94 SecureField("Current PIN", text: $pin)95 .keyboardType(.numberPad)96 .textContentType(.oneTimeCode)97 .font(QFont.body)98 .padding(12)99 .background(QColor.surface, in: RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous))100 .overlay(RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous).strokeBorder(QColor.stroke, lineWidth: 1))101 .accessibilityLabel("Current PIN")102 if !pin.isEmpty, let rejection = WalletService.pinRejection(pin), pin.count >= WalletService.pinLength || !pin.allSatisfy(\.isNumber) {103 Label(rejection, systemImage: QTone.warning.systemImage).font(QFont.caption).foregroundStyle(QColor.warning)104 }105 Explanation("The PIN slot can only be wrapped again with the PIN. Without it, PIN unlock is removed.")106 }107 }108 SecInlineError(error)109 LoadingButton("Rotate master key", loadingTitle: "Re-encrypting the vault", systemImage: "arrow.triangle.2.circlepath",110 state: busy ? .loading : .idle) { rotate() }111 .disabled(password.isEmpty || (pinEnabled && !pinIsUsable))112 Explanation("Make an encrypted backup first if the last one is old.")113 }114 }115 .padding(20)116 .frame(maxWidth: 560, alignment: .leading)117 .frame(maxWidth: .infinity)118 }119 .scrollDismissesKeyboard(.interactively)120 .qScreen()121 .privacySensitive()122 .interactiveDismissDisabled(busy)123 .sensoryFeedback(.success, trigger: result)124 #if DEBUG125 .task {126 if SecurityDebug.action == "go" {127 password = SecurityDebug.throwawayPassword128 rotate()129 }130 }131 #endif132 .onDisappear {133 password = ""134 pin = ""135 }136 }137138 func rotate() {139 guard !busy, !password.isEmpty else { return }140 busy = true141 error = nil142 let secret = password143 let code: String? = pinEnabled && keepPIN ? pin : nil144 Task {145 do {146 result = try await store.run { try await $0.rotateMasterKey(password: secret, pin: code) }147 password = ""148 pin = ""149 } catch {150 self.error = SecurityError.text(error)151 }152 busy = false153 }154 }155}156