Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP ID & Card Vault7// File : SPVault/Features/SecurityCenter/SecurityCenterView.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 SwiftUI4243/// Security Center. Every figure on this screen is read from44/// `Vault.securityReport()` or from live state when the screen appears or is45/// pulled to refresh; nothing is a constant.46struct SecurityCenterView: View {47 @Environment(Vault.self) private var vault48 @Environment(AppEnvironment.self) private var environment49 @Environment(AppSettings.self) private var settings50 @Environment(AppRouter.self) private var router5152 @State private var report: SecurityReport?53 @State private var checkedAt = Date()54 @State private var showsRecoverySheet = false55 @State private var notice: (tone: StatusTone, symbol: String, text: String)?5657 private static var fileProtectionEnforced: Bool {58 #if targetEnvironment(simulator)59 false60 #else61 true62 #endif63 }6465 var body: some View {66 NavigationStack {67 ScreenScaffold(eyebrow: "SP Vault Security Engine", title: "Security") {68 GlassIconButton(symbol: "arrow.clockwise", label: "Run checks again", size: 40) {69 Haptics.shared.play(.select)70 reload()71 }72 .accessibilityIdentifier("security.refresh")73 } content: {74 if let report {75 let assessment = SecurityAssessment(report: report, now: checkedAt, fileProtectionEnforced: Self.fileProtectionEnforced)76 hero(assessment)77 if let notice {78 NoticeView(tone: notice.tone, symbol: notice.symbol, title: nil, message: notice.text)79 .accessibilityIdentifier("security.notice")80 }81 metrics(report)82 accessSection(report, assessment)83 encryptionSection(report, assessment)84 storageSection(report, assessment)85 backupSection(report, assessment)86 privacySection87 recoverySection(report, assessment)88 Text("Checked \(checkedAt.formatted(date: .omitted, time: .standard)) on this device.")89 .font(.spCaption).monospacedDigit().foregroundStyle(SP.Palette.textTertiary)90 .frame(maxWidth: .infinity, alignment: .center)91 } else {92 ProgressView().frame(maxWidth: .infinity).padding(.top, SP.Space.xxxl)93 }94 }95 .onRefresh { await refresh() }96 }97 .onAppear { reload() }98 .onChange(of: vault.cards.count) { reload() }99 .onChange(of: vault.lastBackupAt) { reload() }100 .sheet(isPresented: $showsRecoverySheet) {101 RecoveryPassphraseSheet { notice = (.positive, "checkmark.circle.fill", "Recovery passphrase updated."); reload() }102 }103 }104105 private func reload() {106 report = vault.securityReport()107 checkedAt = Date()108 }109110 private func refresh() async {111 try? await Task.sleep(for: .milliseconds(350))112 reload()113 }114115 // MARK: Hero116117 private func hero(_ assessment: SecurityAssessment) -> some View {118 let tone = assessment.level.tone119 return HStack(spacing: SP.Space.m) {120 ZStack {121 Circle().stroke(SP.Palette.hairlineStrong, lineWidth: 5)122 Circle().trim(from: 0, to: CGFloat(assessment.findings.count - assessment.issues.count) / CGFloat(max(1, assessment.findings.count)))123 .stroke(tone.color, style: StrokeStyle(lineWidth: 5, lineCap: .round)).rotationEffect(.degrees(-90))124 Image(systemName: assessment.level == .good ? "checkmark.shield.fill" : "exclamationmark.shield.fill")125 .font(.system(size: 26, weight: .semibold)).foregroundStyle(tone.color)126 }127 .frame(width: 72, height: 72)128 .accessibilityHidden(true)129 VStack(alignment: .leading, spacing: 4) {130 Text(assessment.headline).font(.spTitle).foregroundStyle(SP.Palette.textPrimary)131 .fixedSize(horizontal: false, vertical: true)132 .accessibilityIdentifier("security.headline")133 Text(assessment.summary).font(.spCaption).foregroundStyle(SP.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)134 Text("\(assessment.findings.count - assessment.issues.count) of \(assessment.findings.count) checks passed")135 .font(.spCaption.weight(.semibold)).monospacedDigit().foregroundStyle(tone.color).padding(.top, 2)136 }137 Spacer(minLength: 0)138 }139 .spPanel(padding: SP.Space.l)140 .accessibilityElement(children: .combine)141 }142143 private func metrics(_ report: SecurityReport) -> some View {144 HStack(alignment: .top, spacing: SP.Space.s) {145 metric("\(report.cardCount)", "Cards protected", "rectangle.stack.fill")146 metric(ByteCountFormatter.string(fromByteCount: report.storage.totalBytes, countStyle: .file), "Encrypted", "internaldrive.fill")147 metric("\(report.storage.fileCount)", "Sealed files", "doc.fill")148 }149 }150151 private func metric(_ value: String, _ label: String, _ symbol: String) -> some View {152 VStack(alignment: .leading, spacing: SP.Space.xs) {153 Image(systemName: symbol).font(.system(size: 14, weight: .semibold)).foregroundStyle(SP.Palette.titanium).frame(height: 18)154 Text(value).font(.spMetric(24)).foregroundStyle(SP.Palette.textPrimary).lineLimit(1).minimumScaleFactor(0.5).frame(height: 30)155 Text(label).font(.system(size: 12, weight: .medium)).foregroundStyle(SP.Palette.textSecondary).lineLimit(1).minimumScaleFactor(0.8)156 }157 .frame(maxWidth: .infinity, alignment: .leading)158 .spPanel(radius: SP.Radius.m, padding: SP.Space.s)159 .accessibilityElement(children: .ignore)160 .accessibilityLabel("\(label): \(value)")161 }162163 // MARK: Sections164165 private func check(_ finding: SecurityAssessment.Finding?, symbol: String, last: Bool = false) -> some View {166 Group {167 if let finding {168 SettingRow(symbol: symbol, tint: finding.level.tone.color, title: finding.title, caption: finding.detail, showsDivider: !last) {169 Image(systemName: finding.level == .good ? "checkmark.circle.fill" : "exclamationmark.circle.fill")170 .font(.system(size: 18, weight: .semibold)).foregroundStyle(finding.level.tone.color)171 .accessibilityLabel(finding.level == .good ? "Passed" : "Needs attention")172 }173 .accessibilityElement(children: .combine)174 .accessibilityIdentifier("security.check.\(finding.topic.rawValue)")175 }176 }177 }178179 private func info(_ symbol: String, _ title: String, _ caption: String, last: Bool = false) -> some View {180 SettingRow(symbol: symbol, title: title, caption: caption, showsDivider: !last) { EmptyView() }181 .accessibilityElement(children: .combine)182 }183184 private func accessSection(_ report: SecurityReport, _ assessment: SecurityAssessment) -> some View {185 PanelSection("Access") {186 check(assessment.finding(.biometry), symbol: "faceid")187 check(assessment.finding(.key), symbol: "key.fill")188 info("lock.rotation", "Locks in the background", "Immediately. The key and every decrypted image are dropped from memory.")189 info("hand.raised.fill", "Face ID again for sensitive actions", "Revealing a number, exporting, changing recovery and erasing all ask again.", last: true)190 }191 }192193 private func encryptionSection(_ report: SecurityReport, _ assessment: SecurityAssessment) -> some View {194 PanelSection("Encryption") {195 check(assessment.finding(.encryption), symbol: "lock.shield.fill")196 check(assessment.finding(.integrity), symbol: "checkmark.seal.fill")197 info("square.stack.3d.up.fill", "AES-256-GCM, one key per card",198 "\(report.cardCount) card key\(report.cardCount == 1 ? "" : "s") wrapped by the master key. Format version \(report.formatVersion.map(String.init) ?? "unknown").", last: true)199 }200 }201202 private func storageSection(_ report: SecurityReport, _ assessment: SecurityAssessment) -> some View {203 PanelSection("Local storage") {204 check(assessment.finding(.fileProtection), symbol: "lock.doc.fill")205 check(assessment.finding(.backupExclusion), symbol: "icloud.slash.fill")206 info("internaldrive.fill", "\(ByteCountFormatter.string(fromByteCount: report.storage.totalBytes, countStyle: .file)) in \(report.storage.fileCount) files",207 (report.storage.freeBytes.map { "\(ByteCountFormatter.string(fromByteCount: $0, countStyle: .file)) free on this iPhone." } ?? "Free space not reported.")208 + (report.vaultCreatedAt.map { " Vault created \($0.spShort)." } ?? ""), last: true)209 }210 }211212 private func backupSection(_ report: SecurityReport, _ assessment: SecurityAssessment) -> some View {213 PanelSection("Backup") {214 check(assessment.finding(.backup), symbol: "externaldrive.fill")215 ActionRow(symbol: "lock.doc.fill", tint: SP.Palette.electric, title: "Backup & Restore",216 caption: report.lastBackupAt.map { "Last: \($0.spShort)" } ?? "Create an encrypted .spvault file", showsDivider: false,217 identifier: "security.openBackup") { router.show(.backup) }218 }219 }220221 private var privacySection: some View {222 let privacy = environment.privacy223 @Bindable var settings = settings224 return PanelSection("Privacy Shield") {225 info("rectangle.on.rectangle.slash.fill", "Hidden in the app switcher", "An opaque curtain covers the app whenever it is not active.")226 SettingRow(symbol: "record.circle", tint: privacy.isCaptured ? SP.Palette.warning : SP.Palette.titanium,227 title: privacy.isCaptured ? "Screen is being recorded" : "No recording detected",228 caption: "Cards are hidden while iOS reports recording or mirroring.") {229 StatusPill(text: privacy.isCaptured ? "Recording" : "Clear", tone: privacy.isCaptured ? .warning : .positive)230 }231 .accessibilityElement(children: .combine)232 SettingRow(symbol: "camera.viewfinder", tint: privacy.screenshotCount > 0 ? SP.Palette.warning : SP.Palette.titanium,233 title: privacy.screenshotCount == 0 ? "No screenshot this session"234 : privacy.screenshotCount == 1 ? "1 screenshot this session" : "\(privacy.screenshotCount) screenshots this session",235 caption: privacy.lastScreenshotAt.map { "Last at \($0.formatted(date: .omitted, time: .shortened)). iOS cannot block screenshots; SP Vault reports them." }236 ?? "iOS cannot block screenshots; SP Vault reports them.") { EmptyView() }237 .accessibilityElement(children: .combine)238 .accessibilityIdentifier("security.screenshots")239 ToggleRow(symbol: "eye.slash.fill", title: "Privacy Mode", caption: "Veil card faces in lists until a card is opened.",240 showsDivider: false, identifier: "security.privacyMode", isOn: $settings.privacyMode)241 }242 }243244 private func recoverySection(_ report: SecurityReport, _ assessment: SecurityAssessment) -> some View {245 PanelSection("Recovery") {246 check(assessment.finding(.recovery), symbol: "key.horizontal.fill")247 ActionRow(symbol: "pencil", tint: SP.Palette.electric, title: report.recoveryConfigured ? "Change recovery passphrase" : "Set a recovery passphrase",248 caption: "Asks for Face ID first.", showsDivider: report.recoveryConfigured, identifier: "security.recovery.change") {249 Task {250 if await vault.reauthenticate(reason: "Confirm it is you before changing recovery") { notice = nil; showsRecoverySheet = true }251 else { notice = (.warning, "faceid", "Face ID did not confirm. Recovery was not changed.") }252 }253 }254 if report.recoveryConfigured {255 ActionRow(symbol: "trash", tint: SP.Palette.critical, title: "Remove recovery passphrase",256 caption: "Only a backup could then bring the cards back after a Face ID reset.", showsDivider: false,257 identifier: "security.recovery.remove") {258 Task {259 guard await vault.reauthenticate(reason: "Confirm it is you before removing recovery") else {260 notice = (.warning, "faceid", "Face ID did not confirm. Recovery was not changed.")261 return262 }263 do {264 try await vault.setRecoveryPassphrase(nil)265 notice = (.warning, "key.slash.fill", "Recovery passphrase removed.")266 } catch {267 notice = (.critical, "exclamationmark.triangle.fill", "The recovery passphrase could not be removed.")268 }269 reload()270 }271 }272 }273 }274 }275}276277/// New recovery passphrase (the caller has already re-authenticated).278private struct RecoveryPassphraseSheet: View {279 var onSaved: () -> Void280281 @Environment(Vault.self) private var vault282 @Environment(\.dismiss) private var dismiss283 @State private var passphrase = ""284 @State private var confirmation = ""285 @State private var isWorking = false286 @State private var error: String?287288 var body: some View {289 SheetScaffold(eyebrow: "Recovery", title: "New recovery passphrase") {290 Text("It replaces any previous one at once. It is the only way back into this vault if Face ID is reset.")291 .font(.spCallout).foregroundStyle(SP.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)292 PassphraseFields(title: "Recovery passphrase", passphrase: $passphrase, confirmation: $confirmation, identifierPrefix: "recovery")293 if let error { NoticeView(tone: .critical, symbol: "exclamationmark.triangle.fill", title: nil, message: error) }294 Button {295 Task {296 isWorking = true297 defer { isWorking = false }298 do {299 try await vault.setRecoveryPassphrase(passphrase)300 passphrase = ""; confirmation = ""301 Haptics.shared.play(.success)302 dismiss()303 onSaved()304 } catch {305 self.error = "The passphrase could not be saved. The previous setting is unchanged."306 Haptics.shared.play(.error)307 }308 }309 } label: {310 HStack(spacing: SP.Space.xs) {311 if isWorking { ProgressView().tint(.white) }312 Text(isWorking ? "Deriving key…" : "Save passphrase")313 }314 }315 .buttonStyle(.spPrimary)316 .disabled(!PassphraseFields.isValid(passphrase, confirmation) || isWorking)317 .accessibilityIdentifier("recovery.submit")318 }319 .interactiveDismissDisabled(isWorking)320 .presentationDetents([.large])321 }322}323