Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP ID & Card Vault7// File : SPVault/Features/Onboarding/OnboardingView.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 SwiftUI42import UniformTypeIdentifiers4344/// Steps of the first-run flow, in order. Pure so the sequence is testable.45enum OnboardingStep: Int, CaseIterable, Sendable {46 case welcome, protection, biometry, recovery, notifications, restore4748 /// Steps shown for a new vault, or for a vault restored from a backup.49 static func sequence(restoring: Bool) -> [OnboardingStep] {50 restoring ? [.welcome, .protection, .biometry, .recovery, .notifications, .restore]51 : [.welcome, .protection, .biometry, .recovery, .notifications]52 }53}5455/// Secure Onboarding. Nothing is created until the last step: the vault, its56/// key and the optional recovery wrap are written in one go.57struct OnboardingView: View {58 @Environment(Vault.self) private var vault59 @Environment(AppEnvironment.self) private var environment60 @Environment(\.scenePhase) private var scenePhase61 @Environment(\.accessibilityReduceMotion) private var reduceMotion6263 @State private var step: OnboardingStep = .welcome64 @State private var restoring = false65 @State private var movingForward = true66 @State private var biometry: BiometryState = .unavailable67 @State private var passphrase = ""68 @State private var confirmation = ""69 @State private var skipsRecovery = false70 @State private var showsSkipWarning = false71 @State private var isCreating = false72 @State private var error: String?73 @State private var showsImporter = false74 @State private var picked: PickedBackup?75 @State private var verifiedBackup: (data: Data, passphrase: String)?7677 private var steps: [OnboardingStep] { OnboardingStep.sequence(restoring: restoring) }78 private var index: Int { steps.firstIndex(of: step) ?? 0 }79 private var isLast: Bool { step == steps.last }8081 var body: some View {82 ZStack {83 VaultBackground()84 VStack(spacing: 0) {85 header86 ScrollView {87 page88 .padding(.horizontal, SP.Space.page)89 .padding(.top, SP.Space.l)90 .padding(.bottom, SP.Space.xl)91 .frame(maxWidth: 560)92 .frame(maxWidth: .infinity)93 .id(step)94 .transition(reduceMotion ? .opacity : .asymmetric(95 insertion: .move(edge: movingForward ? .trailing : .leading).combined(with: .opacity),96 removal: .opacity))97 }98 .scrollBounceBehavior(.basedOnSize)99 .scrollDismissesKeyboard(.interactively)100 footer101 }102 }103 .onAppear { biometry = vault.biometry }104 .onChange(of: scenePhase) { _, phase in if phase == .active { biometry = vault.biometry } }105 .alert("Continue without a recovery passphrase?", isPresented: $showsSkipWarning) {106 Button("Set a passphrase", role: .cancel) {}107 Button("Continue without", role: .destructive) { skipsRecovery = true; advance() }108 } message: {109 Text("If Face ID is ever reset or a face is added, iOS destroys the vault key. Without a recovery passphrase, only a .spvault backup could bring your cards back.")110 }111 .fileImporter(isPresented: $showsImporter, allowedContentTypes: [.spVaultBackup, .data]) { result in112 guard case .success(let url) = result else { return }113 do { picked = try PickedBackup(url: url); error = nil }114 catch { self.error = BackupMessages.describe(BackupError.notABackup) }115 }116 .sheet(item: $picked) { backup in117 BackupUnlockSheet(backup: backup, asksMode: false) { passphrase, _ in118 // Verify the whole file with this passphrase before any vault exists.119 let data = backup.data120 do {121 _ = try await Task.detached(priority: .userInitiated) { try BackupArchive.decode(data, passphrase: passphrase) }.value122 verifiedBackup = (data, passphrase)123 return nil124 } catch {125 return BackupMessages.describe(error)126 }127 }128 }129 }130131 // MARK: Chrome132133 private var header: some View {134 HStack(spacing: SP.Space.s) {135 if index > 0 {136 GlassIconButton(symbol: "chevron.left", label: "Back", size: 40) { go(to: steps[index - 1], forward: false) }137 .disabled(isCreating)138 .accessibilityIdentifier("onboarding.back")139 } else {140 Color.clear.frame(width: 40, height: 40)141 }142 Spacer()143 HStack(spacing: 6) {144 ForEach(Array(steps.enumerated()), id: \.offset) { position, _ in145 Capsule().fill(position <= index ? SP.Palette.electric : SP.Palette.hairlineStrong)146 .frame(width: position == index ? 22 : 8, height: 4)147 }148 }149 .animation(SP.Motion.quick, value: index)150 .accessibilityElement(children: .ignore)151 .accessibilityLabel("Step \(index + 1) of \(steps.count)")152 Spacer()153 Color.clear.frame(width: 40, height: 40)154 }155 .padding(.horizontal, SP.Space.page)156 .padding(.top, SP.Space.xs)157 }158159 private var footer: some View {160 VStack(spacing: SP.Space.xs) {161 if let error {162 NoticeView(tone: .critical, symbol: "exclamationmark.triangle.fill", title: nil, message: error)163 .accessibilityIdentifier("onboarding.error")164 }165 Button {166 primaryAction()167 } label: {168 HStack(spacing: SP.Space.xs) {169 if isCreating { ProgressView().tint(.white) }170 Text(primaryTitle)171 }172 }173 .buttonStyle(.spPrimary)174 .disabled(!canContinue || isCreating)175 .accessibilityIdentifier("onboarding.primary")176177 switch step {178 case .welcome:179 Button("Restore from a backup") { restoring = true; advance() }180 .buttonStyle(.spQuiet).accessibilityIdentifier("onboarding.restore")181 case .recovery:182 Button("Continue without recovery") { showsSkipWarning = true }183 .buttonStyle(.spQuiet).accessibilityIdentifier("onboarding.skipRecovery")184 case .notifications:185 Button(isLast ? "Not now — create my vault" : "Not now") { isLast ? create() : advance() }186 .buttonStyle(.spQuiet).disabled(isCreating).accessibilityIdentifier("onboarding.skipNotifications")187 default:188 EmptyView()189 }190 }191 .padding(.horizontal, SP.Space.page)192 .padding(.top, SP.Space.s)193 .padding(.bottom, SP.Space.s)194 .frame(maxWidth: 560)195 }196197 private var primaryTitle: String {198 if isCreating { return restoring ? "Creating and restoring…" : "Creating your vault…" }199 switch step {200 case .welcome: return "Set up my vault"201 case .protection: return "Continue"202 case .biometry: return biometry.isAvailable ? "Continue" : "\(biometry.name) is required"203 case .recovery: return "Continue"204 case .notifications: return isLast ? "Allow reminders and create vault" : "Allow reminders"205 case .restore: return verifiedBackup == nil ? "Choose a backup file…" : "Create vault and restore"206 }207 }208209 private var canContinue: Bool {210 switch step {211 case .biometry: biometry.isAvailable212 case .recovery: PassphraseFields.isValid(passphrase, confirmation)213 default: true214 }215 }216217 private func go(to next: OnboardingStep, forward: Bool) {218 movingForward = forward219 error = nil220 Haptics.shared.play(.select)221 withAnimation(reduceMotion ? SP.Motion.reduced : SP.Motion.card) { step = next }222 }223224 private func advance() {225 guard index + 1 < steps.count else { return create() }226 go(to: steps[index + 1], forward: true)227 }228229 private func primaryAction() {230 switch step {231 case .recovery:232 skipsRecovery = false233 advance()234 case .notifications:235 Task {236 await environment.reminders.requestAuthorization()237 isLast ? create() : advance()238 }239 case .restore:240 verifiedBackup == nil ? (showsImporter = true) : create()241 default:242 advance()243 }244 }245246 private func create() {247 guard !isCreating else { return }248 isCreating = true249 error = nil250 let recovery = skipsRecovery ? nil : passphrase251 let backup = restoring ? verifiedBackup : nil252 let vault = vault253 Task {254 do {255 try await vault.createVault(recoveryPassphrase: recovery)256 Haptics.shared.play(.unlock)257 // The root view now shows the wallet; the restore finishes behind it.258 if let backup { _ = try? await vault.restoreBackup(backup.data, passphrase: backup.passphrase, mode: .replace) }259 } catch {260 isCreating = false261 Haptics.shared.play(.error)262 self.error = Self.describe(error)263 }264 }265 }266267 static func describe(_ error: any Error) -> String {268 switch error {269 case VaultError.weakPassphrase: "The recovery passphrase is too weak."270 case VaultError.biometryRequired: "Face ID must be set up before the vault can be created."271 case KeyProtectorError.passcodeNotSet: "This iPhone has no passcode. Set one in Settings, then come back."272 case let error as CocoaError where error.code == .fileWriteOutOfSpace: "There is not enough free space on this iPhone."273 default: "The vault could not be created. Nothing was saved."274 }275 }276277 // MARK: Pages278279 @ViewBuilder280 private var page: some View {281 switch step {282 case .welcome: welcomePage283 case .protection: protectionPage284 case .biometry: biometryPage285 case .recovery: recoveryPage286 case .notifications: notificationsPage287 case .restore: restorePage288 }289 }290291 private func pageTitle(_ eyebrow: String, _ title: String, _ lead: String) -> some View {292 VStack(alignment: .leading, spacing: SP.Space.xs) {293 Text(eyebrow).spEyebrow(SP.Palette.electric)294 Text(title).font(.spDisplay).foregroundStyle(SP.Palette.textPrimary)295 .fixedSize(horizontal: false, vertical: true).minimumScaleFactor(0.7)296 Text(lead).font(.spBody).foregroundStyle(SP.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)297 .padding(.top, 2)298 }299 .frame(maxWidth: .infinity, alignment: .leading)300 .accessibilityElement(children: .combine)301 .accessibilityAddTraits(.isHeader)302 }303304 private var welcomePage: some View {305 VStack(spacing: SP.Space.xl) {306 VaultMark(size: 156)307 .shadow(color: SP.Palette.electric.opacity(0.18), radius: 30)308 .padding(.top, SP.Space.xl)309 VStack(spacing: SP.Space.xs) {310 Text("SP Vault").font(.spDisplay).foregroundStyle(SP.Palette.textPrimary)311 Text("ID & Card Vault").spEyebrow()312 }313 VStack(spacing: 0) {314 mottoLine("Private", "by design.")315 Hairline()316 mottoLine("Beautiful", "by engineering.")317 Hairline()318 mottoLine("Personal", "by purpose.")319 }320 .padding(.horizontal, SP.Space.m)321 .spPanel(padding: 0)322 Text("Photograph your identity, bank and membership cards. They stay on this iPhone, encrypted, behind Face ID.")323 .font(.spCallout).foregroundStyle(SP.Palette.textSecondary).multilineTextAlignment(.center)324 .fixedSize(horizontal: false, vertical: true)325 }326 }327328 private func mottoLine(_ lead: String, _ rest: String) -> some View {329 HStack(alignment: .firstTextBaseline, spacing: 6) {330 Text(lead).font(.spHeadline.width(.expanded)).foregroundStyle(SP.Palette.textPrimary)331 Text(rest).font(.spCallout).foregroundStyle(SP.Palette.textSecondary)332 Spacer()333 }334 .padding(.vertical, 14)335 .accessibilityElement(children: .combine)336 }337338 private var protectionPage: some View {339 VStack(alignment: .leading, spacing: SP.Space.l) {340 pageTitle("How it protects", "Built like a vault", "Four facts about where your cards live and who can read them.")341 VStack(spacing: 0) {342 fact("iphone", SP.Palette.silver, "On this iPhone only", "No account, no server, no iCloud. The app works without any network.")343 fact("lock.fill", SP.Palette.electric, "AES-256-GCM", "Each card has its own random key. Photographs never touch the disk unencrypted.")344 fact("faceid", SP.Palette.positive, "Key bound to Face ID", "The master key sits in the Keychain and is released only by your current Face ID.")345 fact("eye.slash.fill", SP.Palette.warning, "Nothing to leak", "No analytics, no logs of card data, and no card security code is ever kept.", last: true)346 }347 .spPanel(padding: 0)348 }349 }350351 private func fact(_ symbol: String, _ tint: Color, _ title: String, _ detail: String, last: Bool = false) -> some View {352 SettingRow(symbol: symbol, tint: tint, title: title, caption: detail, showsDivider: !last) { EmptyView() }353 .accessibilityElement(children: .combine)354 }355356 private var biometryPage: some View {357 VStack(alignment: .leading, spacing: SP.Space.l) {358 pageTitle("Biometrics", "\(biometry.name) is the key", "The vault opens only after \(biometry.name) matches. There is no PIN to guess and no fallback password inside the app.")359 HStack(spacing: SP.Space.m) {360 IconBadge(symbol: "faceid", tint: biometryTone.color, size: 56)361 VStack(alignment: .leading, spacing: 4) {362 Text(biometryTitle).font(.spHeadline).foregroundStyle(SP.Palette.textPrimary)363 Text(biometryDetail).font(.spCaption).foregroundStyle(SP.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)364 }365 Spacer(minLength: 0)366 }367 .spPanel()368 .accessibilityElement(children: .combine)369 .accessibilityIdentifier("onboarding.biometry.status")370 if !biometry.isAvailable {371 Button("Check again") { biometry = vault.biometry; Haptics.shared.play(.select) }372 .buttonStyle(.spSecondary).accessibilityIdentifier("onboarding.biometry.recheck")373 }374 NoticeView(tone: .neutral, symbol: "info.circle.fill", title: "If Face ID changes",375 message: "Adding a face or resetting Face ID makes iOS destroy the vault key. That is deliberate: a new face cannot open your cards. The next step gives you a way back in.")376 }377 }378379 private var biometryTone: StatusTone {380 switch biometry {381 case .available: .positive382 case .lockedOut: .warning383 case .notEnrolled, .unavailable: .critical384 }385 }386387 private var biometryTitle: String {388 switch biometry {389 case .available(let kind): "\(kind.rawValue) is ready"390 case .notEnrolled: "Face ID is not set up"391 case .lockedOut: "Face ID is locked"392 case .unavailable: "Face ID is unavailable"393 }394 }395396 private var biometryDetail: String {397 switch biometry {398 case .available: "It will be asked every time the vault opens and before sensitive details are revealed."399 case .notEnrolled: "Set up Face ID in Settings ▸ Face ID & Passcode, then come back and check again."400 case .lockedOut: "Too many failed attempts. Lock the iPhone and unlock it with its passcode, then check again."401 case .unavailable: "Allow Face ID for SP Vault in Settings, and make sure this iPhone has a passcode."402 }403 }404405 private var recoveryPage: some View {406 VStack(alignment: .leading, spacing: SP.Space.l) {407 pageTitle("Recovery", "A way back in", "If Face ID is reset or re-enrolled, this passphrase is the only thing on this iPhone that can reopen your vault.")408 PassphraseFields(title: "Recovery passphrase", passphrase: $passphrase, confirmation: $confirmation, identifierPrefix: "onboarding")409 NoticeView(tone: .neutral, symbol: "pencil.and.list.clipboard", title: "Write it down",410 message: "It is never stored in clear and cannot be shown again. A wrapped copy of the vault key is protected with it (PBKDF2-HMAC-SHA256, \(KDFParameters.defaultIterations.formatted()) iterations).")411 }412 }413414 private var notificationsPage: some View {415 VStack(alignment: .leading, spacing: SP.Space.l) {416 pageTitle("Reminders", "Before a card expires", "SP Vault can remind you 180, 90, 60, 30 or 7 days before a document expires, and on the day.")417 VStack(alignment: .leading, spacing: SP.Space.s) {418 Text("What a reminder looks like").spEyebrow()419 HStack(alignment: .top, spacing: SP.Space.s) {420 VaultMark(size: 38)421 VStack(alignment: .leading, spacing: 2) {422 HStack {423 Text("SP Vault").font(.spCallout.weight(.semibold)).foregroundStyle(SP.Palette.textPrimary)424 Spacer()425 Text("9:00").font(.spCaption).monospacedDigit().foregroundStyle(SP.Palette.textTertiary)426 }427 Text("A document in your vault expires in 30 days.").font(.spCallout).foregroundStyle(SP.Palette.textSecondary)428 .fixedSize(horizontal: false, vertical: true)429 }430 }431 .padding(SP.Space.s)432 .background(SP.Palette.surface, in: RoundedRectangle(cornerRadius: SP.Radius.m, style: .continuous))433 .overlay(RoundedRectangle(cornerRadius: SP.Radius.m, style: .continuous).strokeBorder(SP.Palette.hairlineStrong, lineWidth: 0.75))434 .accessibilityElement(children: .combine)435 }436 .spPanel()437 NoticeView(tone: .neutral, symbol: "eye.slash.fill", title: "Generic on purpose",438 message: "A reminder never names the card, its issuer or its number. Reminders are scheduled on this iPhone; nothing is sent anywhere.")439 }440 }441442 private var restorePage: some View {443 VStack(alignment: .leading, spacing: SP.Space.l) {444 pageTitle("Restore", "Bring your cards back", "Pick the .spvault file from Files and enter its passphrase. A new vault is created for this iPhone and the backup is re-encrypted into it.")445 if verifiedBackup != nil {446 HStack(spacing: SP.Space.m) {447 IconBadge(symbol: "checkmark.seal.fill", tint: SP.Palette.positive, size: 48)448 VStack(alignment: .leading, spacing: 4) {449 Text("Backup verified").font(.spHeadline).foregroundStyle(SP.Palette.textPrimary)450 Text("Every record authenticated with your passphrase.").font(.spCaption).foregroundStyle(SP.Palette.textSecondary)451 }452 Spacer(minLength: 0)453 }454 .spPanel()455 .accessibilityElement(children: .combine)456 .accessibilityIdentifier("onboarding.restore.verified")457 Button("Choose another file") { verifiedBackup = nil; showsImporter = true }.buttonStyle(.spQuiet)458 } else {459 VStack(spacing: 0) {460 fact("doc.badge.arrow.up.fill", SP.Palette.silver, "1 · Choose the file", "A .spvault backup exported from SP Vault.")461 fact("key.fill", SP.Palette.electric, "2 · Enter its passphrase", "The file is verified in full before anything is created.")462 fact("faceid", SP.Palette.positive, "3 · New key for this iPhone", "The restored cards are bound to the Face ID on this device.", last: true)463 }464 .spPanel(padding: 0)465 }466 }467 }468}469