Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Vault9// File : apple/App/Shared/Views/Onboarding.swift10// Module : apple11// Repository : https://git.spboucher.ai/sp-vault12// Project Website : https://vault.spboucher.ai13// Created : 2026-11-1914// Last Modified : 2026-11-1915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788// Signed-out and locked screens: welcome, join by invitation, pairing as a new device, recovery, recovery kit, locked.89import LocalAuthentication90import SharedVaultKit91import SwiftUI9293/// Brand, a centred card and the footer line — the frame of every signed-out screen.94struct AuthScreen<Content: View>: View {95 var wide = false96 @ViewBuilder var content: () -> Content97 var body: some View {98 ZStack {99 AuthBackdrop()100 ScrollView {101 VStack(spacing: 26) {102 BrandMark(size: 34).padding(.top, 36)103 content()104 .padding(24)105 .frame(maxWidth: wide ? 600 : 440, alignment: .leading)106 .background(Palette.s1, in: RoundedRectangle(cornerRadius: 18, style: .continuous))107 .overlay(RoundedRectangle(cornerRadius: 18, style: .continuous).strokeBorder(Palette.line, lineWidth: 1))108 .shadow(color: .black.opacity(0.22), radius: 30, y: 14)109 Label("End-to-end encrypted · keys never leave your devices", systemImage: "lock")110 .font(.caption).foregroundStyle(Palette.muted).padding(.bottom, 20)111 }112 .padding(.horizontal, 18)113 .frame(maxWidth: .infinity)114 }115 .scrollBounceBehavior(.basedOnSize)116 }117 #if os(macOS)118 .frame(minWidth: 560, minHeight: 620)119 #endif120 }121}122123private struct NoticeLine: View {124 @Environment(AppModel.self) private var model125 var body: some View {126 if let n = model.notice, !n.isEmpty {127 if n.uppercased().hasPrefix("SECURITY") { ErrorText(text: n) } else { Callout(kind: .info, text: n).accessibilityIdentifier("notice") }128 }129 }130}131132// ── welcome ──133134struct WelcomeView: View {135 @Environment(AppModel.self) private var model136 @State private var error: String?137 @State private var joining = false138 @State private var inviteText = ""139140 var body: some View {141 VStack(alignment: .leading, spacing: 14) {142 Text("Open your vault").font(.vaultLargeTitle).foregroundStyle(Palette.text)143 Text("Passwords, passkeys, cards and secrets — encrypted on this device before anything is sent. The server stores ciphertext it cannot read.")144 .font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)145 NoticeLine()146 ErrorText(text: error)147 Button { Task { error = await model.signInExisting() } } label: { Label("Sign in with passkey", systemImage: "person.badge.key") }148 .buttonStyle(.vaultPrimaryBlock).disabled(model.busy).accessibilityIdentifier("welcome-signin")149 Button { model.setPhase(.recover) } label: { Label("Recover with recovery key", systemImage: "key") }150 .buttonStyle(.vaultSecondaryBlock).disabled(model.busy).accessibilityIdentifier("welcome-recover")151 Divider().overlay(Palette.line)152 if joining {153 LabeledField(label: "Invitation link or code", hint: "Paste the link you received (https://vault.spboucher.ai/#/join/…) or the code alone.",154 error: !inviteText.isEmpty && AppModel.inviteToken(from: inviteText) == nil ? "This does not look like an invitation." : nil) {155 TextField("", text: $inviteText).textFieldStyle(.vaultMono).rawTextInput().accessibilityIdentifier("welcome-invite")156 .onSubmit(openInvite)157 }158 Button("Continue", action: openInvite).buttonStyle(.vaultPrimaryBlock).disabled(AppModel.inviteToken(from: inviteText) == nil)159 .accessibilityIdentifier("welcome-invite-continue")160 } else {161 Button { joining = true } label: { Label("I have an invitation", systemImage: "envelope.open") }162 .buttonStyle(.vaultGhostBlock).accessibilityIdentifier("welcome-join")163 }164 Text("New here? Accounts are created by invitation only. On a device that is already part of your account, open Devices to approve this one after signing in.")165 .font(.caption).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)166 }167 .containerID("welcome")168 }169170 private func openInvite() {171 if let token = AppModel.inviteToken(from: inviteText) { model.setPhase(.join(invite: token)) }172 }173}174175// ── join ──176177struct JoinView: View {178 @Environment(AppModel.self) private var model179 let invite: String180 @State private var handle = ""181 @State private var error: String?182183 private var valid: Bool { handle.wholeMatch(of: /[a-z0-9][a-z0-9._-]{1,31}/) != nil }184185 var body: some View {186 VStack(alignment: .leading, spacing: 14) {187 Eyebrow("Invitation accepted")188 Text("Create your vault").font(.vaultLargeTitle).foregroundStyle(Palette.text)189 Text("Choose a handle, then create a passkey. There is no master password: your passkey signs you in and your devices hold the keys.")190 .font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)191 LabeledField(label: "Handle", hint: "2–32 characters: lowercase letters, digits, dot, dash or underscore. Other members use it to share with you.",192 error: !handle.isEmpty && !valid ? "Use lowercase letters, digits, . _ - and start with a letter or digit." : nil) {193 TextField("", text: $handle).textFieldStyle(.vault).rawTextInput().accessibilityIdentifier("join-handle")194 .onChange(of: handle) { _, v in handle = String(v.lowercased().filter { !$0.isWhitespace }.prefix(32)) }195 .onSubmit(create)196 }197 ErrorText(text: error)198 Button(action: create) { Label(model.busy ? "Creating…" : "Create passkey and vault", systemImage: "person.badge.key") }199 .buttonStyle(.vaultPrimaryBlock).disabled(!valid || model.busy).accessibilityIdentifier("join-create")200 VStack(alignment: .leading, spacing: 6) {201 step(1, "Passkey", "this device asks to create one.")202 step(2, "Recovery key", "shown once; you print or write it down.")203 step(3, "Verification", "you type three groups back to prove the copy works.")204 }205 Button("Cancel") { model.setPhase(.welcome) }.buttonStyle(.vaultGhost).disabled(model.busy)206 }207 .containerID("join")208 }209210 private func step(_ n: Int, _ title: String, _ text: String) -> some View {211 HStack(alignment: .firstTextBaseline, spacing: 8) {212 Text("\(n)").font(.caption.monospaced().weight(.bold)).foregroundStyle(Palette.accent)213 (Text(title).fontWeight(.semibold).foregroundColor(Palette.text) + Text(" — \(text)").foregroundColor(Palette.muted)).font(.callout)214 }215 }216217 private func create() {218 guard valid, !model.busy else { return }219 Task { error = await model.register(invite: invite, handle: handle) }220 }221}222223// ── recovery kit ──224225struct RecoveryKitView: View {226 @Environment(AppModel.self) private var model227 let recoveryKey: String228 let reason: AppModel.KitReason229 @State private var verifying = false230 @State private var picks: [Int] = []231 @State private var answers: [String] = ["", "", ""]232 @FocusState private var focus: Int?233234 private var groups: [String] { Array(recoveryKey.split(separator: "-").map(String.init).dropFirst()) }235 private var correct: Bool { !picks.isEmpty && zip(picks, answers).allSatisfy { groups[$0] == $1.uppercased().trimmingCharacters(in: .whitespaces) } }236237 var body: some View {238 VStack(alignment: .leading, spacing: 14) {239 HStack(spacing: 8) {240 Pill(text: "1 · SAVE", tint: verifying ? Palette.muted : Palette.accent)241 Pill(text: "2 · VERIFY", tint: verifying ? Palette.accent : Palette.muted)242 }243 if !verifying { save } else { verify }244 }245 .containerID("recovery-kit")246 .interactiveDismissDisabled()247 }248249 @ViewBuilder private var save: some View {250 Text(reason == .new ? "Your recovery key" : "Your new recovery key").font(.vaultLargeTitle).foregroundStyle(Palette.text)251 Text(reason == .new ? "This key is shown once. Print it or write it down and keep it somewhere safe, away from this device."252 : "The previous recovery key no longer works. This one is shown once: print it or write it down and destroy the old copy.")253 .font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)254 RecoveryKeyGrid(key: recoveryKey)255 HStack(spacing: 8) {256 Button { RecoveryKitPrinter.print(recoveryKey: recoveryKey, handle: model.handle) } label: { Label("Print recovery kit", systemImage: "printer") }257 .buttonStyle(.vaultSecondary).accessibilityIdentifier("kit-print")258 Button { model.copy(recoveryKey, label: "Recovery key") } label: { Label("Copy", systemImage: "doc.on.doc") }259 .buttonStyle(.vaultSecondary).accessibilityIdentifier("kit-copy")260 }261 Callout(kind: .warn, title: "Nobody can recover this vault for you",262 text: "Without a trusted device or this key, the vault cannot be recovered by anyone — including the server operator. There is no reset by e-mail and no back door.")263 HStack {264 Spacer()265 Button("I saved it — continue") {266 picks = Array(groups.indices.shuffled().prefix(3)).sorted()267 answers = ["", "", ""]268 verifying = true269 focus = 0270 }271 .buttonStyle(.vaultPrimary).accessibilityIdentifier("kit-continue")272 }273 }274275 @ViewBuilder private var verify: some View {276 Text("Check your copy").font(.vaultLargeTitle).foregroundStyle(Palette.text)277 Text("Type these three groups from the copy you just made. This proves the copy is readable before you depend on it.")278 .font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)279 HStack(alignment: .top, spacing: 10) {280 ForEach(Array(picks.enumerated()), id: \.offset) { i, g in281 let entered = answers[i].uppercased().trimmingCharacters(in: .whitespaces)282 LabeledField(label: "Group \(g + 1)", error: entered.count >= groups[g].count && entered != groups[g] ? "Does not match" : nil) {283 TextField("", text: $answers[i]).textFieldStyle(.vaultMono).rawTextInput().focused($focus, equals: i)284 .accessibilityIdentifier("kit-verify-\(i)").accessibilityLabel("Group \(g + 1)")285 .onChange(of: answers[i]) { _, v in286 answers[i] = String(v.uppercased().prefix(groups[g].count))287 if answers[i] == groups[g], i < 2 { focus = i + 1 }288 }289 }290 }291 }292 Text("Groups asked: \(picks.map { String($0 + 1) }.joined(separator: ", "))").font(.caption).foregroundStyle(Palette.muted).accessibilityIdentifier("kit-asked")293 HStack {294 Button("Show the key again") { verifying = false }.buttonStyle(.vaultGhost).accessibilityIdentifier("kit-back")295 Spacer()296 Button("Open my vault") { model.finishRecoveryKit() }.buttonStyle(.vaultPrimary).disabled(!correct).accessibilityIdentifier("kit-done")297 }298 }299}300301// ── pairing (this device is the new one) ──302303struct PairingNewDeviceView: View {304 @Environment(AppModel.self) private var model305 @State private var offer: PairingOffer?306 @State private var expiresAt = Date()307 @State private var error: String?308 @State private var rejected = false309310 var body: some View {311 VStack(alignment: .leading, spacing: 14) {312 Eyebrow("New device")313 Text("Approve this device").font(.vaultLargeTitle).foregroundStyle(Palette.text)314 Text("Your passkey signed you in, but it cannot open the vault by itself. Open SP Vault on a device that is already part of your account, go to Devices → Add a device, and scan or paste this code.")315 .font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)316 ErrorText(text: error)317 if rejected {318 Callout(kind: .danger, title: "Request refused", text: "The other device refused this request. If that was not you, tell the vault owner.")319 Button("Try again") { Task { await begin() } }.buttonStyle(.vaultPrimary)320 } else if let offer {321 TimelineView(.periodic(from: .now, by: 1)) { ctx in322 let left = max(0, Int(expiresAt.timeIntervalSince(ctx.date)))323 if left == 0 {324 Callout(kind: .warn, title: "Code expired", text: "Pairing codes are valid for a few minutes.")325 Button("Show a new code") { Task { await begin() } }.buttonStyle(.vaultPrimary).accessibilityIdentifier("pairing-renew")326 } else {327 codeCard(offer, left: left)328 }329 }330 } else if error == nil {331 HStack { ProgressView(); Text("Preparing the device keys…").foregroundStyle(Palette.muted) }332 }333 HStack {334 Button("Use the recovery key instead") { cancel(to: .recover) }.buttonStyle(.vaultGhost).accessibilityIdentifier("pairing-recover")335 Spacer()336 Button("Cancel") { cancel(to: .welcome) }.buttonStyle(.vaultSecondary).accessibilityIdentifier("pairing-cancel")337 }338 }339 .containerID("pairing")340 .task { await begin() }341 .task(id: offer?.code) { await poll() }342 }343344 @ViewBuilder private func codeCard(_ offer: PairingOffer, left: Int) -> some View {345 ViewThatFits(in: .horizontal) {346 HStack(alignment: .top, spacing: 18) { QRCodeView(payload: offer.code, size: 170); codeDetails(offer, left: left) }347 VStack(alignment: .center, spacing: 14) { QRCodeView(payload: offer.code, size: 190); codeDetails(offer, left: left) }348 }349 }350351 @ViewBuilder private func codeDetails(_ offer: PairingOffer, left: Int) -> some View {352 VStack(alignment: .leading, spacing: 12) {353 VStack(alignment: .leading, spacing: 4) {354 Eyebrow("Fingerprint — must match on both devices")355 Text(TotpRow.spaced(offer.sas)).font(.system(size: 34, weight: .bold, design: .monospaced)).foregroundStyle(Palette.brass)356 .accessibilityLabel("Fingerprint").accessibilityValue(offer.sas.map(String.init).joined(separator: " ")).accessibilityIdentifier("pairing-sas")357 }358 VStack(alignment: .leading, spacing: 4) {359 Eyebrow("Code to paste on the other device")360 Text(offer.code).font(.system(.caption, design: .monospaced)).foregroundStyle(Palette.text).textSelection(.enabled).lineLimit(4)361 .accessibilityIdentifier("pairing-code")362 Button { model.copy(offer.code, label: "Pairing code", secret: true) } label: { Label("Copy code", systemImage: "doc.on.doc") }.buttonStyle(.vaultCompact)363 }364 Label("Waiting for approval · \(left / 60):\(String(format: "%02d", left % 60))", systemImage: "hourglass").font(.caption).foregroundStyle(Palette.muted)365 }366 }367368 private func begin() async {369 rejected = false; error = nil; offer = nil370 do {371 let o = try await model.engine.startPairing()372 expiresAt = Date().addingTimeInterval(TimeInterval(o.expiresInSec))373 offer = o374 #if SPV_DEV375 DevSupport.publishPairing(code: o.code, sas: o.sas)376 #endif377 } catch { self.error = model.errorText(error) }378 }379380 private func poll() async {381 guard offer != nil else { return }382 while !Task.isCancelled, Date() < expiresAt {383 try? await Task.sleep(for: .seconds(2))384 if Task.isCancelled { return }385 do {386 switch try await model.engine.checkPairing() {387 case .done: model.pairingCompleted(); return388 case .rejected: rejected = true; return389 case .pending: break390 }391 } catch let e as ApiError where e.isOffline { continue }392 catch { self.error = model.errorText(error); return }393 }394 }395396 private func cancel(to phase: AppModel.Phase) {397 Task {398 await model.engine.signOut()399 model.setPhase(phase)400 }401 }402}403404// ── recovery ──405406struct RecoverView: View {407 @Environment(AppModel.self) private var model408 @State private var handle = ""409 @State private var key = ""410 @State private var error: String?411412 private var groupsTyped: Int { key.uppercased().split(whereSeparator: { !$0.isLetter && !$0.isNumber }).filter { $0 != "SPV1" }.count }413 private var keyValid: Bool { (try? SPV1.decodeRecoveryKey(key)) != nil }414415 var body: some View {416 VStack(alignment: .leading, spacing: 14) {417 Text("Recover your vault").font(.vaultLargeTitle).foregroundStyle(Palette.text)418 Text("Use the recovery key you printed when the account was created. It enrols this device without any other device.")419 .font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)420 LabeledField(label: "Handle") {421 TextField("", text: $handle).textFieldStyle(.vault).rawTextInput().accessibilityIdentifier("recover-handle")422 .onChange(of: handle) { _, v in handle = v.lowercased().filter { !$0.isWhitespace } }423 }424 LabeledField(label: "Recovery key") {425 TextField("SPV1-XXXX-XXXX-…", text: $key, axis: .vertical).lineLimit(3...4).textFieldStyle(.vaultMono).rawTextInput()426 .accessibilityIdentifier("recover-key")427 }428 Group {429 if key.isEmpty { Text("14 groups of 4 characters after SPV1. Dashes and spaces are optional; the last groups carry a checksum.").foregroundStyle(Palette.muted) }430 else if keyValid { Label("Checksum correct", systemImage: "checkmark.circle.fill").foregroundStyle(Palette.accent).accessibilityIdentifier("recover-checksum-ok") }431 else if groupsTyped < 14 { Text("\(groupsTyped) of 14 groups").foregroundStyle(Palette.muted) }432 else { Label("The checksum does not match — check each group", systemImage: "xmark.circle").foregroundStyle(Palette.danger).accessibilityIdentifier("recover-checksum-bad") }433 }434 .font(.caption)435 ErrorText(text: error)436 Button { Task { error = await model.recover(handle: handle, recoveryKey: key) } } label: { Label(model.busy ? "Recovering…" : "Recover on this device", systemImage: "key") }437 .buttonStyle(.vaultPrimaryBlock).disabled(!keyValid || handle.count < 2 || model.busy).accessibilityIdentifier("recover-submit")438 Text("The key is checked on this device first; only a value derived from it is sent to prove you hold it. After recovery, add a passkey in Settings if the old one is gone and consider rotating the recovery key.")439 .font(.caption).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)440 Button("Back") { model.setPhase(.welcome) }.buttonStyle(.vaultGhost).disabled(model.busy).accessibilityIdentifier("recover-back")441 }442 .containerID("recover")443 }444}445446// ── locked ──447448struct LockedView: View {449 @Environment(AppModel.self) private var model450 @State private var confirm: ConfirmRequest?451452 private var biometry: (label: String, symbol: String) {453 let ctx = LAContext()454 _ = ctx.canEvaluatePolicy(.deviceOwnerAuthentication, error: nil)455 switch ctx.biometryType {456 case .touchID: return ("Unlock with Touch ID", "touchid")457 case .faceID: return ("Unlock with Face ID", "faceid")458 case .opticID: return ("Unlock with Optic ID", "opticid")459 default: return ("Unlock", "lock.open")460 }461 }462463 var body: some View {464 VStack(spacing: 14) {465 Image(systemName: "lock").font(.system(size: 26, weight: .medium)).foregroundStyle(Palette.brass)466 .frame(width: 62, height: 62)467 .background(Palette.s2, in: RoundedRectangle(cornerRadius: 16, style: .continuous))468 .overlay(RoundedRectangle(cornerRadius: 16, style: .continuous).strokeBorder(Palette.line, lineWidth: 1))469 .accessibilityHidden(true)470 Text("Vault locked").font(.vaultLargeTitle).foregroundStyle(Palette.text)471 (Text("Enrolled on this device as ").foregroundColor(Palette.muted) + Text(model.handle).fontWeight(.semibold).foregroundColor(Palette.text)).font(.callout)472 .accessibilityIdentifier("locked-handle")473 NoticeLine()474 Button { Task { await model.unlock() } } label: { Label(model.busy ? "Unlocking…" : biometry.label, systemImage: biometry.symbol) }475 .buttonStyle(.vaultPrimaryBlock).disabled(model.busy).keyboardShortcut(.defaultAction).accessibilityIdentifier("unlock")476 Button("Remove this device") {477 confirm = ConfirmRequest(title: "Remove this device?", message: "Everything SP Vault stored on this device is erased: the device keys and the encrypted local copy. Your account and your other devices are not affected. To come back you will need to pair this device again or use your recovery key.", confirmLabel: "Remove this device") {478 await model.removeThisDevice()479 }480 }481 .buttonStyle(.vaultGhostBlock).disabled(model.busy).accessibilityIdentifier("remove-device")482 Text("Unlocking works offline. The key that opens your vault is wrapped for this device and released by its Secure Enclave after Touch ID, Face ID or the device passcode. Your passkey is only asked when the server session has expired.")483 .font(.caption).foregroundStyle(Palette.muted).multilineTextAlignment(.center).fixedSize(horizontal: false, vertical: true)484 }485 .frame(maxWidth: .infinity)486 .containerID("locked")487 .confirmSheet($confirm)488 }489}490