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/VaultsPage.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// Vaults: one key per vault. Create, rename, delete, members (with out-of-band fingerprint comparison), key rotation.89import SharedVaultKit90import SwiftUI9192extension VaultKind {93 var label: String {94 switch self {95 case .personal: "Personal"96 case .work: "Work"97 case .infrastructure: "Infrastructure"98 case .shared: "Shared"99 }100 }101 var symbol: String {102 switch self {103 case .personal: "person.crop.square"104 case .work: "briefcase"105 case .infrastructure: "server.rack"106 case .shared: "person.2.square.stack"107 }108 }109}110111extension Role {112 var label: String { rawValue.capitalized }113}114115/// Handle → account lookup, then the account fingerprint to compare out of band before anything is encrypted for it.116struct AccountLookupField: View {117 @Environment(AppModel.self) private var model118 @Binding var account: AccountLookup?119 var testID = "lookup"120 @State private var handle = ""121 @State private var error: String?122 @State private var looking = false123124 var body: some View {125 VStack(alignment: .leading, spacing: 10) {126 LabeledField(label: "Handle of the recipient", hint: "The handle they chose when they created their account.") {127 HStack(spacing: 8) {128 TextField("", text: $handle).textFieldStyle(.vault).rawTextInput().accessibilityLabel("Handle").accessibilityIdentifier("\(testID)-handle")129 .onChange(of: handle) { _, v in130 handle = v.lowercased().filter { !$0.isWhitespace }131 if account?.handle != handle { account = nil }132 }133 .onSubmit(lookup)134 Button(looking ? "Looking…" : "Find", action: lookup).buttonStyle(.vaultSecondary).disabled(handle.count < 2 || looking)135 .accessibilityIdentifier("\(testID)-find")136 }137 }138 ErrorText(text: error)139 if let a = account {140 VStack(alignment: .leading, spacing: 6) {141 Eyebrow("Verify \(a.handle)'s fingerprint")142 Text(a.fingerprint).font(.system(.title3, design: .monospaced).weight(.bold)).foregroundStyle(Palette.brass).textSelection(.enabled)143 .accessibilityLabel("Fingerprint of \(a.handle)").accessibilityValue(a.fingerprint).accessibilityIdentifier("\(testID)-fingerprint")144 Text("Ask \(a.handle) to read the fingerprint shown in their Settings, over a channel you trust (in person, a call). If it differs, the server may have substituted keys: do not continue.")145 .font(.caption).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)146 }147 .padding(12).frame(maxWidth: .infinity, alignment: .leading)148 .background(Palette.brassSoft, in: RoundedRectangle(cornerRadius: Metrics.radius, style: .continuous))149 .overlay(RoundedRectangle(cornerRadius: Metrics.radius, style: .continuous).strokeBorder(Palette.brassLine, lineWidth: 1))150 }151 }152 }153154 private func lookup() {155 guard handle.count >= 2, !looking else { return }156 looking = true; error = nil157 Task {158 defer { looking = false }159 do { account = try await model.engine.lookupAccount(handle: handle) }160 catch let e as ApiError where e.status == 404 { error = "No account has this handle." }161 catch { self.error = model.errorText(error) }162 }163 }164}165166struct VaultsPage: View {167 @Environment(AppModel.self) private var model168 @State private var creating = false169 @State private var renaming: VaultView?170 @State private var addingTo: VaultView?171 @State private var confirm: ConfirmRequest?172 @State private var working: String?173 @State private var error: String?174175 var body: some View {176 ToolPage("Vaults", subtitle: "Each vault is encrypted under its own key. Sharing a vault gives members that key; removing a member replaces it.") {177 Button { creating = true } label: { Label("New vault", systemImage: "plus") }.buttonStyle(.vaultPrimary).accessibilityIdentifier("vaults-new")178 } content: {179 ErrorText(text: error)180 if let working {181 HStack(spacing: 10) { ProgressView().controlSize(.small); Text(working).font(.callout).foregroundStyle(Palette.muted) }182 .frame(height: 28).accessibilityIdentifier("vaults-working")183 }184 if model.vaults.isEmpty { EmptyState(symbol: "lock.square", title: "No vault yet", text: "Vaults appear after the first sync.") }185 ForEach(model.vaults) { v in vaultCard(v) }186 }187 .sheet(isPresented: $creating) { VaultEditSheet(vault: nil) }188 .sheet(item: $renaming) { VaultEditSheet(vault: $0) }189 .sheet(item: $addingTo) { AddMemberSheet(vault: $0) }190 .confirmSheet($confirm)191 }192193 @ViewBuilder private func vaultCard(_ v: VaultView) -> some View {194 let owner = v.role == .owner195 let count = model.count(in: .vault(v.vaultId))196 SectionCard {197 CardRow {198 HStack(spacing: 12) {199 ItemGlyph(title: v.meta.name, symbol: v.meta.kind.symbol, size: 40)200 VStack(alignment: .leading, spacing: 4) {201 Text(v.meta.name.isEmpty ? "Untitled vault" : v.meta.name).font(.vaultHeadline).foregroundStyle(Palette.text)202 HStack(spacing: 6) {203 Pill(text: v.meta.kind.label)204 Pill(text: v.role.label, tint: owner ? Palette.accent : Palette.muted)205 Text("\(count) item\(count == 1 ? "" : "s") · key epoch \(v.epoch)").font(.caption).foregroundStyle(Palette.muted)206 }207 }208 Spacer(minLength: 8)209 Button("Open") { model.section = .vault(v.vaultId) }.buttonStyle(.vaultCompact).accessibilityLabel("Open \(v.meta.name)")210 .accessibilityIdentifier("vault-open-\(v.vaultId.prefix(8))")211 }212 }213 ForEach(v.members) { m in214 CardRow {215 HStack(spacing: 10) {216 Image(systemName: "person.crop.circle").foregroundStyle(Palette.muted).accessibilityHidden(true)217 Text(m.handle).foregroundStyle(Palette.text)218 if m.accountId == model.account?.accountId { Pill(text: "You", tint: Palette.accent) }219 Spacer(minLength: 8)220 Pill(text: m.role.label)221 if owner, m.accountId != v.ownerId {222 Button("Remove") { removeMember(v, m) }.buttonStyle(.vaultDangerGhost).disabled(working != nil)223 .accessibilityLabel("Remove \(m.handle) from \(v.meta.name)")224 }225 }226 }227 }228 CardRow(last: true) {229 if owner {230 ViewThatFits(in: .horizontal) {231 HStack(spacing: 8) { ownerActions(v, count: count) }232 VStack(alignment: .leading, spacing: 8) { ownerActions(v, count: count) }233 }234 } else {235 Text("Only the owner can change members, rotate the key or delete this vault.").font(.caption).foregroundStyle(Palette.muted)236 }237 }238 }239 .containerID("vault-card-\(v.vaultId.prefix(8))")240 }241242 @ViewBuilder private func ownerActions(_ v: VaultView, count: Int) -> some View {243 Button { addingTo = v } label: { Label("Add member", systemImage: "person.badge.plus") }.buttonStyle(.vaultCompact).accessibilityIdentifier("vault-add-member")244 Button { renaming = v } label: { Label("Rename", systemImage: "pencil") }.buttonStyle(.vaultCompact).accessibilityIdentifier("vault-rename")245 Button { rotate(v) } label: { Label("Rotate key", systemImage: "arrow.triangle.2.circlepath") }.buttonStyle(.vaultCompact).accessibilityIdentifier("vault-rotate")246 Button { delete(v, count: count) } label: { Label("Delete", systemImage: "trash") }.buttonStyle(.vaultDangerGhost).accessibilityIdentifier("vault-delete")247 }248249 private func run(_ label: String, _ success: String, _ op: @escaping () async throws -> Void) async {250 working = label; error = nil251 error = await model.perform(success, op)252 working = nil253 }254255 private func removeMember(_ v: VaultView, _ m: Member) {256 confirm = ConfirmRequest(title: "Remove \(m.handle)?",257 message: "A new key epoch is created for “\(v.meta.name)” and every record is re-encrypted under it on this device. \(m.handle) does not receive the new key and can no longer read new or changed items. What \(m.handle) already copied or downloaded cannot be taken back: change the passwords that matter. This device may ask to confirm your presence. Keep the app open until the re-encryption finishes.",258 confirmLabel: "Remove and rotate key") {259 await run("Rotating the key and re-encrypting…", "\(m.handle) removed; vault key rotated") { try await model.engine.rotateVaultKey(vaultId: v.vaultId, remove: [m.accountId]) }260 }261 }262263 private func rotate(_ v: VaultView) {264 confirm = ConfirmRequest(title: "Rotate the key of “\(v.meta.name)”?",265 message: "A new key epoch is created, wrapped for every current member, and all records are re-encrypted under it on this device. Use this when you suspect the vault key leaked. Data that was already downloaded elsewhere stays readable there. Keep the app open until it finishes.",266 confirmLabel: "Rotate key", destructive: false) {267 await run("Rotating the key and re-encrypting…", "Vault key rotated") { try await model.engine.rotateVaultKey(vaultId: v.vaultId, remove: []) }268 }269 }270271 private func delete(_ v: VaultView, count: Int) {272 confirm = ConfirmRequest(title: "Delete “\(v.meta.name)”?",273 message: "The vault and its \(count) item\(count == 1 ? "" : "s") are deleted for every member, on every device. This cannot be undone. Export an encrypted backup first if you may need the contents.",274 confirmLabel: "Delete vault", typed: v.meta.name.isEmpty ? "DELETE" : v.meta.name) {275 await run("Deleting…", "Vault deleted") {276 try await model.engine.deleteVault(vaultId: v.vaultId)277 if model.section == .vault(v.vaultId) { model.section = .allItems }278 }279 }280 }281}282283struct ToolSheet<Content: View>: View {284 let title: String285 @ViewBuilder var content: () -> Content286 var body: some View {287 ScrollView {288 VStack(alignment: .leading, spacing: 14) {289 Text(title).font(.vaultTitle).foregroundStyle(Palette.text).accessibilityAddTraits(.isHeader)290 content()291 }292 .padding(22)293 }294 .frame(minWidth: 320, idealWidth: 480, maxWidth: 560)295 .background(Palette.s1)296 }297}298299private struct VaultEditSheet: View {300 @Environment(AppModel.self) private var model301 @Environment(\.dismiss) private var dismiss302 let vault: VaultView?303 @State private var name = ""304 @State private var kind = VaultKind.personal305 @State private var error: String?306307 var body: some View {308 ToolSheet(title: vault == nil ? "New vault" : "Rename vault") {309 Text(vault == nil ? "Each vault has its own key. A new vault is private until you add members." : "Encrypted like everything else: the server never sees vault names.")310 .font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)311 LabeledField(label: "Name") {312 TextField("", text: $name).textFieldStyle(.vault).accessibilityLabel("Vault name").accessibilityIdentifier("vault-name").onSubmit(save)313 }314 LabeledField(label: "Kind") {315 Picker("Kind", selection: $kind) { ForEach(VaultKind.allCases, id: \.self) { Text($0.label).tag($0) } }316 .pickerStyle(.segmented).labelsHidden().accessibilityIdentifier("vault-kind")317 }318 ErrorText(text: error)319 HStack {320 Spacer()321 Button("Cancel") { dismiss() }.buttonStyle(.vaultSecondary).keyboardShortcut(.cancelAction)322 Button(vault == nil ? "Create vault" : "Save", action: save).buttonStyle(.vaultPrimary)323 .disabled(name.trimmingCharacters(in: .whitespaces).isEmpty || model.busy).accessibilityIdentifier("vault-save")324 }325 }326 .presentationDetents([.medium])327 .onAppear { if let vault { name = vault.meta.name; kind = vault.meta.kind } }328 }329330 private func save() {331 let n = String(name.trimmingCharacters(in: .whitespaces).prefix(100))332 guard !n.isEmpty else { return }333 Task {334 error = await model.perform(vault == nil ? "Vault created" : "Saved") {335 if let vault {336 var meta = vault.meta337 meta.name = n; meta.kind = kind338 try await model.engine.renameVault(vaultId: vault.vaultId, meta: meta)339 } else {340 try await model.engine.createVault(meta: VaultMeta(name: n, kind: kind))341 }342 }343 if error == nil { dismiss() }344 }345 }346}347348private struct AddMemberSheet: View {349 @Environment(AppModel.self) private var model350 @Environment(\.dismiss) private var dismiss351 let vault: VaultView352 @State private var account: AccountLookup?353 @State private var role = Role.editor354 @State private var compared = false355 @State private var error: String?356357 var body: some View {358 ToolSheet(title: "Add a member to “\(vault.meta.name)”") {359 Text("The vault key is wrapped for the member's account key on this device and signed by you. They will be able to read every item in this vault, including its history.")360 .font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)361 AccountLookupField(account: $account, testID: "member")362 if let account {363 if vault.members.contains(where: { $0.accountId == account.accountId }) {364 Callout(kind: .info, text: "\(account.handle) is already a member of this vault.")365 } else {366 LabeledField(label: "Role", hint: role == .reader ? "Readers can see and copy items but not change them." : "Editors can add, change and delete items.") {367 Picker("Role", selection: $role) { Text("Editor").tag(Role.editor); Text("Reader").tag(Role.reader) }368 .pickerStyle(.segmented).labelsHidden().accessibilityIdentifier("member-role")369 }370 Toggle("I compared the fingerprint with \(account.handle)", isOn: $compared).accessibilityIdentifier("member-compared")371 }372 }373 ErrorText(text: error)374 Text("Adding a member is a sensitive action: this device may ask to confirm your presence.").font(.caption).foregroundStyle(Palette.muted)375 HStack {376 Spacer()377 Button("Cancel") { dismiss() }.buttonStyle(.vaultSecondary).keyboardShortcut(.cancelAction)378 Button("Add member", action: add).buttonStyle(.vaultPrimary)379 .disabled(account == nil || !compared || model.busy || vault.members.contains { $0.accountId == account?.accountId })380 .accessibilityIdentifier("member-add")381 }382 }383 .onChange(of: account) { _, _ in compared = false }384 }385386 private func add() {387 guard let account else { return }388 Task {389 error = await model.perform("\(account.handle) added to \(vault.meta.name)") { try await model.engine.addMember(vaultId: vault.vaultId, member: account, role: role) }390 if error == nil { dismiss() }391 }392 }393}394