Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : App/Sources/Security/SecuritySupport.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 UniformTypeIdentifiers43import QyvoraCore44import QyvoraCrypto45import QyvoraVault46import QyvoraIdentity47import QyvoraRecovery48import QyvoraWallet49import QyvoraUI5051// MARK: - Routes5253/// Every security screen that can be pushed on a navigation stack.54enum SecurityRoute: Hashable, Sendable {55 case vault56 case identity57 case identitySign58 case identityVerify59 case identityContact60 case recovery61 case revealPhrase62 case verifyPhrase63 case recoverySheet64 case backupCreate65 case backupInspect66 case restoreBackup67 case transferSend(receiver: String?)68 case transferReceive69 case coldMode70 case watchOnlyExport71 case migrationPlan72 /// The unified cold-signing flow (every chain).73 case coldSign74 /// Networks settings: mode, chains, test networks, endpoints.75 case networks76}7778extension SecurityRoute {79 /// The screen of the route.80 @MainActor @ViewBuilder var destination: some View {81 switch self {82 case .vault: VaultView()83 case .identity: IdentityView()84 case .identitySign: IdentitySignView()85 case .identityVerify: IdentityVerifyView()86 case .identityContact: IdentityContactView()87 case .recovery: RecoveryView()88 case .revealPhrase: RevealPhraseView()89 case .verifyPhrase: VerifyPhraseView()90 case .recoverySheet: RecoverySheetView()91 case .backupCreate: BackupCreateView()92 case .backupInspect: BackupInspectView()93 case .restoreBackup: RestoreBackupView()94 case .transferSend(let receiver): TransferSendView(receiver: receiver)95 case .transferReceive: TransferReceiveView()96 case .coldMode: ColdModeView()97 case .watchOnlyExport: WatchOnlyExportView()98 case .migrationPlan: ShieldMigrationPlanView()99 case .coldSign: SecColdSignView()100 case .networks: SecNetworksSettingsView()101 }102 }103}104105extension View {106 /// Registers the security screens on the enclosing navigation stack (Shield tab and Settings tab).107 func securityDestinations() -> some View {108 navigationDestination(for: SecurityRoute.self) { $0.destination }109 }110}111112// MARK: - Layout113114extension View {115 /// DEBUG builds: lets `-QYSecTour` scroll the enclosed list or scroll view (screenshots). Release: unchanged.116 @ViewBuilder func securityDebugTour() -> some View {117 #if DEBUG118 SecurityDebugTour { self }119 #else120 self121 #endif122 }123}124125/// Scrolling column used by the security flows: same margins and maximum width as the engine screens.126struct SecurityScroll<Content: View>: View {127 @ViewBuilder let content: Content128129 var body: some View {130 ScrollView {131 VStack(alignment: .leading, spacing: QSpace.xl) { content }132 .padding(.horizontal, QMetric.screenPadding)133 .padding(.top, QSpace.m)134 .padding(.bottom, QSpace.xxl)135 .frame(maxWidth: 640, alignment: .leading)136 .frame(maxWidth: .infinity)137 .background(alignment: .top) { Color.clear.frame(height: 1).id("top") }138 }139 .scrollDismissesKeyboard(.interactively)140 .securityDebugTour()141 .qScreen()142 }143}144145/// An error of the wallet service shown next to the action that caused it. Renders nothing for nil.146struct SecInlineError: View {147 let text: String?148149 init(_ text: String?) { self.text = text }150151 var body: some View {152 if let text {153 WarningBanner(.critical, message: text)154 .transition(.opacity)155 }156 }157}158159/// A row saying that a value is being read.160struct LoadingRow: View {161 let text: String162163 init(_ text: String) { self.text = text }164165 var body: some View {166 HStack(spacing: 10) {167 ProgressView().controlSize(.small)168 Text(text).font(QFont.callout).foregroundStyle(QColor.textSecondary)169 }170 .frame(maxWidth: .infinity, alignment: .leading)171 .accessibilityElement(children: .combine)172 }173}174175/// Body text of an explanation.176struct Explanation: View {177 let text: String178179 init(_ text: String) { self.text = text }180181 var body: some View {182 Text(text)183 .font(QFont.callout)184 .foregroundStyle(QColor.textSecondary)185 .fixedSize(horizontal: false, vertical: true)186 }187}188189/// A numbered or bulleted line of a list of facts.190struct BulletLine: View {191 let marker: String192 let text: String193194 init(_ text: String, marker: String = "•") {195 self.text = text196 self.marker = marker197 }198199 var body: some View {200 HStack(alignment: .firstTextBaseline, spacing: 10) {201 Text(marker)202 .font(Font.system(.callout, design: .monospaced).weight(.semibold))203 .foregroundStyle(QColor.textSecondary)204 .accessibilityHidden(true)205 Text(SecurityFormat.breakingLongTokens(text)).font(QFont.callout).foregroundStyle(QColor.textPrimary)206 .fixedSize(horizontal: false, vertical: true)207 .accessibilityLabel(text)208 }209 .accessibilityElement(children: .combine)210 }211}212213/// A long public value (extended key, descriptor, identity text) shown in full, monospaced, with a copy control.214struct MonoValue: View {215 let label: String216 let value: String217 var sensitive = false218219 var body: some View {220 VStack(alignment: .leading, spacing: 4) {221 HStack(alignment: .center) {222 QEyebrow(label)223 Spacer(minLength: 8)224 CopyButton(value, title: "Copy \(label.lowercased())", sensitive: sensitive)225 }226 AddressText(value, head: .max, copyable: false, kind: label)227 }228 }229}230231/// An address shown in full for a review, wrapped without any hyphen, with an optional copy control: the design232/// system's `AddressText` in its full form.233struct FullAddress: View {234 let address: String235 var kind = "Address"236 var copyable = false237238 var body: some View {239 AddressText(address, head: .max, copyable: copyable, kind: kind)240 }241}242243/// The fingerprint of a post-quantum identity: sixteen groups of four hexadecimal digits, four per line.244struct FingerprintView: View {245 let text: String246 var copyable = true247248 var lines: [String] {249 let groups = text.split(whereSeparator: { $0 == " " || $0 == "-" || $0 == ":" }).map(String.init)250 return stride(from: 0, to: groups.count, by: 4).map { groups[$0..<min($0 + 4, groups.count)].joined(separator: " ") }251 }252253 var body: some View {254 HStack(alignment: .top, spacing: 8) {255 VStack(alignment: .leading, spacing: 4) {256 ForEach(lines, id: \.self) { line in257 Text(line).font(Font.system(.body, design: .monospaced).weight(.medium)).foregroundStyle(QColor.textPrimary)258 }259 }260 .accessibilityElement(children: .ignore)261 .accessibilityLabel("Fingerprint: \(text)")262 Spacer(minLength: 8)263 if copyable { CopyButton(text, title: "Copy fingerprint") }264 }265 }266}267268/// A payload shown as QR frames (one, or an animated sequence) with its text form to copy or share.269struct QRExportCard: View {270 let frames: [String]271 /// Text form of the payload; nil when the payload is binary.272 let text: String?273 let label: String274275 var body: some View {276 QCard {277 VStack(spacing: 14) {278 if frames.isEmpty {279 UnavailableDataView(reason: "The payload is too large for QR codes.", title: "No QR code", compact: true)280 } else {281 AnimatedQRCodeView(frames: frames, label: label)282 .frame(maxWidth: 320)283 .frame(maxWidth: .infinity)284 Text(frames.count == 1 ? "One QR code" : "\(frames.count) QR frames, shown in a loop")285 .font(QFont.caption)286 .foregroundStyle(QColor.textSecondary)287 }288 if let text {289 HStack(spacing: 12) {290 CopyButton(text, title: "Copy text", style: .labelled)291 ShareLink(item: text) {292 Label("Share text", systemImage: "square.and.arrow.up")293 .font(.callout.weight(.medium))294 .frame(minHeight: 44)295 }296 .tint(QColor.violet)297 }298 }299 }300 .frame(maxWidth: .infinity)301 }302 }303}304305// MARK: - Scanning306307/// Collects the frames of a scanned payload: either one plain text, or a complete set of `qyv1:` frames.308@MainActor309final class SecFrameCollector {310 private var assembler = QRAssembler()311 private(set) var frames: [String] = []312313 func reset() {314 assembler = QRAssembler()315 frames = []316 }317318 /// Reducer for `QRScannerView(collect:onComplete:)`.319 func add(_ code: String) -> QRScanProgress {320 let trimmed = code.trimmingCharacters(in: .whitespacesAndNewlines)321 guard trimmed.hasPrefix(QRChunker.prefix + ":") else {322 // A plain payload. Several pasted frames separated by whitespace are split first.323 guard frames.isEmpty else { return QRScanProgress(collected: frames.count, total: assembler.total, note: "This code is not part of the sequence.") }324 frames = [trimmed]325 return QRScanProgress(collected: 1, total: 1, isComplete: !trimmed.isEmpty)326 }327 var note: String?328 for part in trimmed.split(whereSeparator: \.isWhitespace).map(String.init) {329 do {330 if try assembler.add(part) { frames.append(part) }331 } catch {332 switch error {333 case .mixedSet, .conflictingDuplicate: note = "This frame belongs to another payload."334 default: note = "Not a QYVORA frame."335 }336 }337 }338 return QRScanProgress(collected: assembler.receivedCount, total: assembler.total, isComplete: assembler.isComplete, note: note)339 }340}341342/// Sheet that scans one code or a multi-frame sequence (or takes pasted text) and returns the frames.343struct PayloadScannerSheet: View {344 let title: String345 let prompt: String346 let onPayload: ([String]) -> Void347 @Environment(\.dismiss) private var dismiss348 @State private var collector = SecFrameCollector()349350 var body: some View {351 VStack(alignment: .leading, spacing: 16) {352 SheetHeader(title, subtitle: prompt) { dismiss() }353 QRScannerView(prompt: prompt, collect: { collector.add($0) }, onComplete: {354 let frames = collector.frames355 dismiss()356 onPayload(frames)357 })358 }359 .padding(20)360 .qScreen()361 }362}363364enum PayloadText {365 /// The text carried by scanned or pasted input: the single plain text, or the reassembled UTF-8 of `qyv1:` frames.366 static func text(from frames: [String]) -> String? {367 guard let first = frames.first else { return nil }368 if frames.count == 1, !first.hasPrefix(QRChunker.prefix + ":") { return first.trimmingCharacters(in: .whitespacesAndNewlines) }369 guard let bytes = try? QRAssembler.assemble(frames) else { return nil }370 return String(validating: bytes, as: UTF8.self)371 }372373 /// Splits pasted text into frames when it holds `qyv1:` frames, else returns it as one payload.374 static func frames(fromPasted text: String) -> [String] {375 let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)376 guard !trimmed.isEmpty else { return [] }377 if trimmed.hasPrefix(QRChunker.prefix + ":") { return trimmed.split(whereSeparator: \.isWhitespace).map(String.init) }378 return [trimmed]379 }380}381382// MARK: - Files383384/// A binary file handed to `.fileExporter`.385struct BinaryDocument: FileDocument {386 static let readableContentTypes: [UTType] = [.data]387 static var writableContentTypes: [UTType] { [.data, SecurityFiles.backupType] }388 var data: Data389 var contentType: UTType = .data390391 init(data: Data, contentType: UTType = .data) {392 self.data = data393 self.contentType = contentType394 }395396 init(configuration: ReadConfiguration) throws {397 data = configuration.file.regularFileContents ?? Data()398 }399400 func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {401 FileWrapper(regularFileWithContents: data)402 }403}404405/// A text document rendered to PDF in memory when the share sheet asks for it; nothing is written to disk by the app.406struct SharedPDF: Transferable {407 let title: String408 let text: String409410 static var transferRepresentation: some TransferRepresentation {411 DataRepresentation(exportedContentType: .pdf) { TextPDF.render(title: $0.title, body: $0.text) }412 }413}414415/// An opaque binary package (already encrypted) handed to `ShareLink`.416struct SharedPackage: Transferable {417 let data: Data418419 static var transferRepresentation: some TransferRepresentation {420 DataRepresentation(exportedContentType: .data) { $0.data }421 }422}423424enum SecurityFiles {425 static let backupType = UTType(filenameExtension: BackupFile.fileExtension, conformingTo: .data) ?? .data426427 /// Copies a file picked with `.fileImporter` into the temporary directory while its security scope is open.428 static func importedCopy(of url: URL) throws -> URL {429 let scoped = url.startAccessingSecurityScopedResource()430 defer { if scoped { url.stopAccessingSecurityScopedResource() } }431 let target = FileManager.default.temporaryDirectory.appendingPathComponent("import-\(UUID().uuidString).\(url.pathExtension)")432 try FileManager.default.copyItem(at: url, to: target)433 return target434 }435436 static func temporaryURL(extension ext: String) -> URL {437 FileManager.default.temporaryDirectory.appendingPathComponent("\(UUID().uuidString).\(ext)")438 }439440 static func remove(_ url: URL?) {441 if let url { try? FileManager.default.removeItem(at: url) }442 }443}444445// MARK: - Formatting446447enum SecurityFormat {448 /// "0.00012345 BTC" from satoshis (exact, integer arithmetic).449 static func bitcoin(_ satoshis: UInt64) -> String {450 BaseUnits.format(UInt256(satoshis), decimals: 8) + " BTC"451 }452453 static func ether(_ wei: UInt256) -> String {454 BaseUnits.format(wei, decimals: 18) + " ETH"455 }456457 /// Prose in which every long unbroken token (an address, a hash, call data) wraps at any character without a458 /// hyphen (`UnbrokenValue` of the design system). For display only.459 static func breakingLongTokens(_ text: String, longerThan limit: Int = 20) -> String {460 UnbrokenValue.wrappingLongTokens(text, longerThan: limit)461 }462463 static func date(_ date: Date) -> String {464 date.formatted(date: .abbreviated, time: .shortened)465 }466467 static func hex(_ bytes: Bytes) -> String {468 bytes.map { String(format: "%02x", $0) }.joined()469 }470471 /// Standard base64 of binary output (signatures, certificates).472 static func base64(_ bytes: Bytes) -> String {473 Data(bytes).base64EncodedString()474 }475476 /// Decodes base64, base64url or hexadecimal text; nil when it is none of them.477 static func bytes(fromEncoded text: String) -> Bytes? {478 let compact = text.filter { !$0.isWhitespace }479 guard !compact.isEmpty else { return nil }480 if compact.count % 2 == 0, compact.allSatisfy(\.isHexDigit) {481 var out = Bytes()482 var index = compact.startIndex483 while index < compact.endIndex {484 let next = compact.index(index, offsetBy: 2)485 guard let byte = UInt8(compact[index..<next], radix: 16) else { return nil }486 out.append(byte)487 index = next488 }489 return out490 }491 var standard = compact.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")492 while standard.count % 4 != 0 { standard.append("=") }493 return Data(base64Encoded: standard).map { Bytes($0) }494 }495496 static func kdf(_ p: KDFParameters) -> String {497 "Argon2id \(p.argon2MemoryKiB / 1024) MiB × \(p.argon2Iterations) passes × \(p.argon2Parallelism) lanes, then PBKDF2 \(p.pbkdf2Iterations) iterations"498 }499}500501extension PasswordStrength {502 /// Meter value for a candidate password, from the vault's own estimator.503 init(_ estimate: PasswordQuality.Estimate) {504 self.init(level: estimate.level.rawValue, entropyBits: estimate.entropyBits, advice: estimate.warnings.first.map(Self.advice))505 }506507 static func advice(_ warning: PasswordQuality.Warning) -> String {508 switch warning {509 case .tooShort: return "Too short: use several unrelated words."510 case .singleCharacterClass: return "Only one kind of character: mix words, digits or symbols."511 case .commonPassword: return "This is a commonly used password."512 case .repeatedCharacters: return "Repeated characters add little."513 case .sequentialCharacters: return "Sequences such as abc or 123 are guessed first."514 case .keyboardPattern: return "Keyboard patterns are guessed first."515 case .yearOrDate: return "Years and dates are guessed first."516 case .mostlyDigits: return "Mostly digits: add words."517 }518 }519}520521// MARK: - Errors522523/// Inline text for an error of the wallet service.524@MainActor525enum SecurityError {526 /// The sentence shown by the security screens: the same single implementation as the wallet screens527 /// (`WalletMessages` in the service).528 static func text(_ error: any Error) -> String {529 WalletMessages.text(for: error)530 }531}532533// MARK: - Mainnet wording534535/// The truthful sentences about mainnet for this build, in one place.536enum MainnetWording {537 /// One short status, for badges and trailing labels.538 static var short: String {539 if MainnetPolicy.auditCompleted { return "Enabled" }540 if MainnetPolicy.mainnetEnabled { return "On for internal testing" }541 return MainnetPolicy.mainnetAvailable ? "Off by default" : "Test networks only"542 }543544 /// The full statement.545 static var statement: String {546 if MainnetPolicy.auditCompleted { return "Mainnet is enabled." }547 if MainnetPolicy.mainnetEnabled {548 return "Main networks are switched on for internal testing, with per-transaction limits on every chain. The cryptographic engine has not been audited by a third party: keep only small amounts in this wallet."549 }550 if MainnetPolicy.mainnetAvailable {551 return "Main networks are off by default. They can be enabled in the settings for internal testing, with per-transaction limits. The cryptographic engine has not been audited by a third party."552 }553 return "Test networks only. This build does not operate on any main network: the cryptographic engine has not been independently audited."554 }555556 /// The statement as worded on the settings screen itself, next to the switch.557 static var settingsStatement: String {558 statement.replacingOccurrences(of: "They can be enabled in the settings for internal testing", with: "The choice above enables them for internal testing")559 }560561 /// Note for a mainnet endpoint list while mainnet is not in use.562 static var endpointNote: String {563 MainnetPolicy.mainnetAvailable564 ? "Main networks are off by default; they can be enabled in the settings for internal testing, with limits. Not audited. This list is used once they are switched on."565 : "This build operates on test networks only. This list is kept for later."566 }567}568