Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP ID & Card Vault7// File : SPVault/Features/Lock/LockScreenView.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/// What the lock screen tells the owner after an attempt. Pure, so the wording44/// for every `KeyProtectorError` is tested.45struct LockMessage: Equatable, Sendable {46 var title: String47 var detail: String48 var tone: StatusTone49 var symbol: String50 /// Whether "Unlock with Face ID" can do anything in this situation.51 var canRetry: Bool5253 static func forError(_ error: any Error, biometryName: String = "Face ID") -> LockMessage {54 switch error {55 case KeyProtectorError.cancelled:56 LockMessage(title: "Unlock cancelled", detail: "The vault stays locked until \(biometryName) confirms it is you.",57 tone: .neutral, symbol: "hand.raised.fill", canRetry: true)58 case KeyProtectorError.authenticationFailed:59 LockMessage(title: "\(biometryName) did not recognise you", detail: "Nothing was decrypted. Try again.",60 tone: .critical, symbol: "faceid", canRetry: true)61 case KeyProtectorError.biometryLockedOut:62 LockMessage(title: "\(biometryName) is locked", detail: "Too many failed attempts. Lock your iPhone, then unlock your iPhone with its passcode to re-enable \(biometryName).",63 tone: .warning, symbol: "lock.trianglebadge.exclamationmark.fill", canRetry: true)64 case KeyProtectorError.biometryNotEnrolled:65 LockMessage(title: "\(biometryName) is not set up", detail: "Set it up in Settings ▸ Face ID & Passcode. If your face was re-enrolled, the vault will then ask for your recovery passphrase.",66 tone: .warning, symbol: "faceid", canRetry: true)67 case KeyProtectorError.biometryUnavailable:68 LockMessage(title: "\(biometryName) is unavailable", detail: "Allow \(biometryName) for SP Vault in Settings and make sure a passcode is set.",69 tone: .warning, symbol: "faceid", canRetry: true)70 case KeyProtectorError.passcodeNotSet:71 LockMessage(title: "No passcode on this iPhone", detail: "The vault key requires a device passcode. Set one in Settings.",72 tone: .warning, symbol: "lock.slash.fill", canRetry: true)73 case KeyProtectorError.keyInvalidated:74 LockMessage(title: "Face ID was changed", detail: "The key bound to the previous Face ID is gone. Use your recovery passphrase.",75 tone: .warning, symbol: "key.slash.fill", canRetry: false)76 case VaultCryptoError.authenticationFailed, VaultCryptoError.malformed:77 LockMessage(title: "The vault could not be opened", detail: "The key did not match the vault files. Restore from a backup if this persists.",78 tone: .critical, symbol: "exclamationmark.shield.fill", canRetry: true)79 case KeyProtectorError.keychain(let status):80 LockMessage(title: "Keychain error", detail: "iOS refused access to the vault key (code \(status)). Try again.",81 tone: .critical, symbol: "exclamationmark.triangle.fill", canRetry: true)82 default:83 LockMessage(title: "Unlock failed", detail: "The vault stays locked. Try again.", tone: .critical,84 symbol: "exclamationmark.triangle.fill", canRetry: true)85 }86 }8788 static func forRecoveryError(_ error: any Error) -> LockMessage {89 switch error {90 case VaultStorageError.wrongPassphrase:91 LockMessage(title: "Wrong passphrase", detail: "That passphrase does not open this vault. Check spelling, spaces and capitals.",92 tone: .critical, symbol: "key.slash.fill", canRetry: true)93 case VaultStorageError.noRecoveryConfigured:94 LockMessage(title: "No recovery passphrase", detail: "This vault was created without one.", tone: .critical, symbol: "key.slash.fill", canRetry: false)95 case VaultError.biometryRequired:96 LockMessage(title: "Face ID is required", detail: "Set up Face ID first: the recovered key is bound to it again.",97 tone: .warning, symbol: "faceid", canRetry: true)98 default:99 LockMessage(title: "Recovery failed", detail: "The vault files could not be opened with that passphrase.", tone: .critical,100 symbol: "exclamationmark.triangle.fill", canRetry: true)101 }102 }103}104105/// Face ID Lock Screen. The only ways past it are a successful Keychain read106/// behind Face ID, or the recovery passphrase when that key no longer exists.107struct LockScreenView: View {108 @Environment(Vault.self) private var vault109 @Environment(\.scenePhase) private var scenePhase110 @Environment(\.accessibilityReduceMotion) private var reduceMotion111112 @State private var isWorking = false113 @State private var message: LockMessage?114 /// Automatic prompts stop after a failed or cancelled attempt, until the app115 /// has been to the background again. Prevents a prompt loop.116 @State private var autoPromptAllowed = true117 @State private var openness = 0.0118 @State private var breathing = false119 @State private var recoveryPassphrase = ""120 @State private var showsErase = false121122 private var biometryName: String { vault.biometry.name }123124 var body: some View {125 ZStack {126 VaultBackground()127 GeometryReader { proxy in128 ScrollView {129 VStack(spacing: SP.Space.xl) {130 mark131 VStack(spacing: SP.Space.xs) {132 Text("SP Vault").font(.spDisplay).foregroundStyle(SP.Palette.textPrimary)133 StatusPill(text: vault.state == .keyInvalidated ? "Recovery required" : "Locked",134 tone: vault.state == .keyInvalidated ? .warning : .neutral,135 symbol: vault.state == .keyInvalidated ? "key.fill" : "lock.fill")136 .accessibilityIdentifier("lock.status")137 }138 if vault.state == .keyInvalidated { recoveryPanel } else { unlockPanel }139 }140 .padding(.horizontal, SP.Space.page)141 .padding(.vertical, SP.Space.xl)142 .frame(maxWidth: 520)143 .frame(maxWidth: .infinity, minHeight: proxy.size.height)144 }145 .scrollBounceBehavior(.basedOnSize)146 .scrollDismissesKeyboard(.interactively)147 }148 }149 .onAppear {150 vault.refreshLockState()151 if !reduceMotion { withAnimation(.easeInOut(duration: 2.6).repeatForever(autoreverses: true)) { breathing = true } }152 if scenePhase == .active { autoPrompt() }153 }154 .onChange(of: scenePhase) { _, phase in155 switch phase {156 case .background: autoPromptAllowed = true; message = nil157 case .active: vault.refreshLockState(); autoPrompt()158 default: break159 }160 }161 .sheet(isPresented: $showsErase) {162 TypedConfirmationSheet(title: "Erase this vault",163 message: "Every card stored on this iPhone is deleted, with its keys. This cannot be undone. A .spvault backup can be restored afterwards.",164 word: "ERASE", actionTitle: "Erase and start over") {165 Haptics.shared.play(.warning)166 vault.eraseEverything()167 }168 }169 }170171 private var mark: some View {172 // The recovery form is tall: a smaller mark keeps it on one screen.173 VaultMark(size: vault.state == .keyInvalidated ? 96 : 148, openness: openness)174 .scaleEffect(breathing ? 1.015 : 1)175 .shadow(color: SP.Palette.electric.opacity(isWorking ? 0.35 : 0.12), radius: isWorking ? 34 : 22)176 .animation(SP.Motion.gentle, value: isWorking)177 .padding(.bottom, SP.Space.xs)178 }179180 // MARK: Face ID181182 private var unlockPanel: some View {183 VStack(spacing: SP.Space.m) {184 if let message {185 NoticeView(tone: message.tone, symbol: message.symbol, title: message.title, message: message.detail)186 .accessibilityIdentifier("lock.message")187 .transition(.opacity)188 } else {189 Text("Your cards are encrypted on this iPhone. \(biometryName) releases the key.")190 .font(.spCallout).foregroundStyle(SP.Palette.textSecondary).multilineTextAlignment(.center)191 .fixedSize(horizontal: false, vertical: true)192 .padding(.horizontal, SP.Space.m)193 }194 Button {195 Task { await attemptUnlock() }196 } label: {197 HStack(spacing: SP.Space.xs) {198 if isWorking { ProgressView().tint(.white) } else { Image(systemName: "faceid") }199 Text(isWorking ? "Waiting for \(biometryName)…" : "Unlock with \(biometryName)")200 }201 }202 .buttonStyle(.spPrimary)203 .disabled(isWorking)204 .accessibilityIdentifier("lock.unlock")205 }206 .animation(SP.Motion.quick, value: message)207 }208209 private func autoPrompt() {210 guard autoPromptAllowed, vault.state == .locked, !isWorking else { return }211 Task { await attemptUnlock() }212 }213214 private func attemptUnlock() async {215 guard !isWorking, vault.state == .locked else { return }216 // Checked first so a lockout or missing enrolment is explained instead217 // of producing a silent failure.218 switch vault.biometry {219 case .lockedOut: return fail(KeyProtectorError.biometryLockedOut)220 case .notEnrolled: return fail(KeyProtectorError.biometryNotEnrolled)221 case .unavailable: return fail(KeyProtectorError.biometryUnavailable)222 case .available: break223 }224 isWorking = true225 defer { isWorking = false }226 do {227 try await vault.unlock(reason: "Unlock your vault")228 succeed()229 } catch {230 fail(error)231 }232 }233234 private func succeed() {235 message = nil236 Haptics.shared.play(.unlock)237 withAnimation(reduceMotion ? SP.Motion.reduced : .spring(response: 0.55, dampingFraction: 0.7)) { openness = 1 }238 }239240 private func fail(_ error: any Error) {241 autoPromptAllowed = false242 if case KeyProtectorError.keyInvalidated = error { message = nil; Haptics.shared.play(.warning); return }243 message = LockMessage.forError(error, biometryName: biometryName)244 if case KeyProtectorError.cancelled = error { return }245 Haptics.shared.play(.error)246 }247248 // MARK: Recovery249250 @ViewBuilder251 private var recoveryPanel: some View {252 VStack(alignment: .leading, spacing: SP.Space.m) {253 NoticeView(tone: .warning, symbol: "faceid", title: "Face ID was changed or reset",254 message: "The vault key was bound to the previous Face ID and iOS has destroyed it. Your cards are still encrypted on this iPhone.")255 if vault.recoveryConfigured {256 SPTextField(title: "Recovery passphrase", text: $recoveryPassphrase, prompt: "The passphrase chosen at setup", secure: true, capitalization: .never)257 .submitLabel(.go)258 .onSubmit { Task { await recover() } }259 .accessibilityIdentifier("lock.recovery.passphrase")260 if let message {261 NoticeView(tone: message.tone, symbol: message.symbol, title: message.title, message: message.detail)262 .accessibilityIdentifier("lock.message")263 }264 Button {265 Task { await recover() }266 } label: {267 HStack(spacing: SP.Space.xs) {268 if isWorking { ProgressView().tint(.white) } else { Image(systemName: "key.fill") }269 Text(isWorking ? "Deriving key…" : "Recover my vault")270 }271 }272 .buttonStyle(.spPrimary)273 .disabled(isWorking || recoveryPassphrase.isEmpty)274 .accessibilityIdentifier("lock.recovery.submit")275 Text("The recovered key is bound to the Face ID now on this iPhone.")276 .font(.spCaption).foregroundStyle(SP.Palette.textTertiary)277 } else {278 NoticeView(tone: .critical, symbol: "key.slash.fill", title: "No recovery passphrase was set",279 message: "Nothing on this iPhone can decrypt the vault any more. Only a .spvault backup can bring your cards back: erase this vault, create a new one, then restore the backup.")280 .accessibilityIdentifier("lock.norecovery")281 }282 Button("Erase and start over") { showsErase = true }283 .buttonStyle(vault.recoveryConfigured ? SPButtonStyle(kind: .quiet) : SPButtonStyle(kind: .destructive))284 .accessibilityIdentifier("lock.erase")285 }286 .animation(SP.Motion.quick, value: message)287 }288289 private func recover() async {290 guard !isWorking, !recoveryPassphrase.isEmpty else { return }291 isWorking = true292 defer { isWorking = false }293 do {294 try await vault.recover(passphrase: recoveryPassphrase)295 recoveryPassphrase = ""296 succeed()297 } catch {298 message = LockMessage.forRecoveryError(error)299 Haptics.shared.play(.error)300 }301 }302}303