Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Browser9// File : SPBrowser/Shared/Account/AccountView.swift10// Module : SPBrowser11// Repository : https://git.spboucher.ai/sp-browser12// Created : 2026-11-1813// Last Modified : 2026-11-1814//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : None specified (no license file in this repository)80// Maintainer : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import SwiftUI8889/// Loads and mutates what the account screen shows.90@MainActor91@Observable92final class AccountViewModel {93 let services: BrowserServices94 var details: AccountDetails?95 var pending: [PendingDevice] = []96 var errorMessage: String?97 var isWorking = false98 /// A recovery kit that must be shown to the user now (it cannot be shown again).99 var recoveryKit: SyncCrypto.RecoveryKit?100101 init(services: BrowserServices) { self.services = services }102103 var account: AccountService { services.account }104105 func refresh() async {106 guard account.isSignedIn else { details = nil; pending = []; return }107 do {108 _ = try await account.refreshKey()109 details = try await account.details()110 pending = (try? await account.pendingDevices()) ?? []111 services.sync.refreshPhase()112 } catch let error as BackendError where error.kind == .unauthenticated {113 account.sessionWasRejected()114 details = nil115 } catch {116 if details == nil { errorMessage = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription }117 }118 }119120 /// Runs an account action, surfacing failures (a dismissed system sheet is not an error).121 func perform(_ action: @escaping @MainActor () async throws -> Void) {122 guard !isWorking else { return }123 isWorking = true124 errorMessage = nil125 Task {126 do { try await action() } catch PasskeyError.cancelled {} catch {127 errorMessage = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription128 }129 isWorking = false130 await refresh()131 }132 }133134 func createAccount(name: String, invite: String) {135 perform { [self] in recoveryKit = try await account.createAccount(displayName: name, inviteCode: invite.isEmpty ? nil : invite) }136 }137 func signIn() { perform { [self] in try await account.signIn(); await services.sync.syncNow() } }138 func recover(_ text: String) {139 perform { [self] in140 guard let kit = SyncCrypto.RecoveryKit(text: text) else { throw PasskeyError.failed(L("This is not a valid recovery key.")) }141 if account.isSignedIn { try await account.unlock(with: kit) } else { try await account.recover(with: kit) }142 await services.sync.syncNow()143 }144 }145 func setUpSync() { perform { [self] in recoveryKit = try await account.setUpSync() } }146 func approve(_ device: PendingDevice) { perform { [self] in try await account.approve(device) } }147 func remove(device id: String) { perform { [self] in try await account.removeDevice(id: id) } }148 func addPasskey() { perform { [self] in try await account.addPasskey(label: services.device.name) } }149 func remove(passkey id: String) { perform { [self] in try await account.removePasskey(id: id) } }150 func newRecoveryKit() { perform { [self] in recoveryKit = try await account.newRecoveryKit() } }151 func signOut() { perform { [self] in await account.signOut(); services.mirror.forgetRemoteOnlyData() } }152 func signOutEverywhere() { perform { [self] in try await account.signOutEverywhere(); services.mirror.forgetRemoteOnlyData() } }153 func eraseSyncedData() { perform { [self] in try await account.eraseSyncedData(); services.mirror.resetServerState() } }154 func deleteAccount() { perform { [self] in try await account.deleteAccount(); services.mirror.forgetRemoteOnlyData() } }155 func syncNow() { Task { await services.sync.syncNow(); await refresh() } }156}157158/// Account, devices, passkeys and synchronization — the same screen on Mac, iPhone and iPad.159struct AccountView: View {160 @State private var model: AccountViewModel161 @Binding var syncEnabled: Bool162 @State private var name = ""163 @State private var invite = ""164 @State private var recoveryText = ""165 @State private var showsRecoveryEntry = false166 @State private var confirm: Confirmation?167168 enum Confirmation: String, Identifiable { case signOutEverywhere, erase, delete; var id: String { rawValue } }169170 init(services: BrowserServices, syncEnabled: Binding<Bool>) {171 _model = State(initialValue: AccountViewModel(services: services))172 _syncEnabled = syncEnabled173 }174175 private var account: AccountService { model.account }176 private var sync: SyncCoordinator { model.services.sync }177178 var body: some View {179 Form {180 if let message = model.errorMessage {181 Section { Label(message, systemImage: "exclamationmark.triangle").foregroundStyle(.orange).accessibilityIdentifier("account-error") }182 }183 if account.isSignedIn { signedIn } else { signedOut }184 }185 .formStyle(.grouped)186 .disabled(model.isWorking)187 .overlay(alignment: .topTrailing) { if model.isWorking { ProgressView().controlSize(.small).padding(12) } }188 .task { await model.refresh() }189 .sheet(item: Binding(get: { model.recoveryKit.map(KitBox.init) }, set: { if $0 == nil { model.recoveryKit = nil } })) { box in190 RecoveryKitSheet(kit: box.kit) { model.recoveryKit = nil }191 }192 .confirmationDialog(confirmTitle, isPresented: Binding(get: { confirm != nil }, set: { if !$0 { confirm = nil } }), titleVisibility: .visible) {193 switch confirm {194 case .signOutEverywhere: Button(L("Sign Out of All Devices"), role: .destructive) { model.signOutEverywhere() }195 case .erase: Button(L("Erase Synchronized Data"), role: .destructive) { model.eraseSyncedData() }196 case .delete: Button(L("Delete Account"), role: .destructive) { model.deleteAccount() }197 case nil: EmptyView()198 }199 } message: { Text(confirmMessage) }200 }201202 private struct KitBox: Identifiable { let kit: SyncCrypto.RecoveryKit; var id: String { kit.text } }203204 private var confirmTitle: String {205 switch confirm {206 case .signOutEverywhere: return L("Sign out of every device?")207 case .erase: return L("Erase the synchronized copy?")208 case .delete: return L("Delete your SP Browser account?")209 case nil: return ""210 }211 }212213 private var confirmMessage: String {214 switch confirm {215 case .signOutEverywhere: return L("Every Mac, iPhone and iPad signed in to this account will have to sign in again with a passkey.")216 case .erase: return L("History, bookmarks and tabs are removed from the server and stop synchronizing. What is on each device stays there.")217 case .delete: return L("The account, its passkeys, its devices and everything synchronized are deleted from the server. This cannot be undone. Data on this device is kept.")218 case nil: return ""219 }220 }221222 // MARK: Signed out223224 @ViewBuilder private var signedOut: some View {225 Section {226 VStack(alignment: .leading, spacing: 6) {227 Label(L("SP Browser account"), systemImage: "person.crop.circle.badge.checkmark").font(.headline)228 Text(L("Sign in to keep history, bookmarks, open tabs, reading list and search history in step between your Macs, iPhones and iPads. Everything synchronized is encrypted on your devices: the server cannot read it."))229 .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)230 }231 Button { model.signIn() } label: { Label(L("Sign In with a Passkey"), systemImage: "person.badge.key") }232 .accessibilityIdentifier("account-sign-in")233 }234 Section(L("New account")) {235 TextField(L("Your name"), text: $name).accessibilityIdentifier("account-name")236 TextField(L("Invitation code"), text: $invite)237 #if os(iOS)238 .textInputAutocapitalization(.characters).autocorrectionDisabled()239 #endif240 .accessibilityIdentifier("account-invite")241 Button { model.createAccount(name: name.trimmingCharacters(in: .whitespaces), invite: invite) } label: {242 Label(L("Create Account with a Passkey"), systemImage: "plus.circle")243 }244 .disabled(name.trimmingCharacters(in: .whitespaces).isEmpty)245 .accessibilityIdentifier("account-create")246 Text(L("A passkey is created with Touch ID, Face ID or your device passcode. There is no password."))247 .font(.caption).foregroundStyle(.secondary)248 }249 Section {250 DisclosureGroup(L("Lost your passkeys?"), isExpanded: $showsRecoveryEntry) { recoveryEntry(button: L("Recover Account")) }251 }252 }253254 private func recoveryEntry(button: String) -> some View {255 VStack(alignment: .leading, spacing: 8) {256 TextField("SPB1-XXXX-XXXX-…", text: $recoveryText, axis: .vertical).lineLimit(2...4).font(.system(.callout, design: .monospaced))257 #if os(iOS)258 .textInputAutocapitalization(.characters).autocorrectionDisabled()259 #endif260 .accessibilityLabel(L("Recovery key"))261 Button(button) { model.recover(recoveryText) }.disabled(SyncCrypto.RecoveryKit(text: recoveryText) == nil)262 }263 }264265 // MARK: Signed in266267 @ViewBuilder private var signedIn: some View {268 Section {269 LabeledContent(L("Account"), value: account.session?.user.displayName ?? "")270 if let details = model.details {271 LabeledContent(L("Member since"), value: Date(timeIntervalSince1970: details.user.createdAt / 1000).formatted(date: .abbreviated, time: .omitted))272 LabeledContent(L("Active sessions"), value: "\(details.sessions.count)")273 }274 }275 syncSection276 if !model.pending.isEmpty {277 Section(L("Devices waiting for approval")) {278 ForEach(model.pending) { device in279 VStack(alignment: .leading, spacing: 6) {280 Label(device.name, systemImage: symbol(for: device.platform)).font(.headline)281 Text(L("Approve only if this code is the one shown on that device:")).font(.caption).foregroundStyle(.secondary)282 Text(device.verificationCode).font(.system(.title2, design: .monospaced).weight(.semibold)).textSelection(.enabled)283 HStack {284 Button(L("Approve")) { model.approve(device) }.buttonStyle(.borderedProminent)285 Button(L("Remove Device"), role: .destructive) { model.remove(device: device.id) }286 }287 }288 .padding(.vertical, 2)289 }290 }291 }292 if let details = model.details {293 Section(L("Registered devices")) {294 ForEach(details.devices) { device in295 HStack(spacing: 10) {296 Image(systemName: symbol(for: device.platform)).frame(width: 22).foregroundStyle(.secondary)297 VStack(alignment: .leading, spacing: 1) {298 HStack(spacing: 6) {299 Text(device.name)300 if device.isCurrent { Text(L("This device")).font(.caption2.weight(.semibold)).padding(.horizontal, 5).padding(.vertical, 1).background(SPTheme.accent.opacity(0.18), in: Capsule()) }301 }302 Text(deviceLine(device)).font(.caption).foregroundStyle(.secondary)303 }304 Spacer()305 if !device.isCurrent { Button(L("Remove"), role: .destructive) { model.remove(device: device.id) }.buttonStyle(.borderless) }306 }307 }308 }309 Section(L("Passkeys")) {310 ForEach(details.passkeys) { passkey in311 HStack {312 Image(systemName: "person.badge.key").frame(width: 22).foregroundStyle(.secondary)313 VStack(alignment: .leading, spacing: 1) {314 Text(passkey.label.isEmpty ? L("Passkey") : passkey.label)315 Text((passkey.synced ? L("Synchronized by your password manager") : L("Stored on one device only")) + " · " +316 Date(timeIntervalSince1970: passkey.createdAt / 1000).formatted(date: .abbreviated, time: .omitted))317 .font(.caption).foregroundStyle(.secondary)318 }319 Spacer()320 if details.passkeys.count > 1 { Button(L("Remove"), role: .destructive) { model.remove(passkey: passkey.id) }.buttonStyle(.borderless) }321 }322 }323 Button { model.addPasskey() } label: { Label(L("Add a Passkey on This Device"), systemImage: "plus") }324 Text(L("A passkey kept in iCloud Keychain works on your other Apple devices. Otherwise, add one on each device or keep your recovery key."))325 .font(.caption).foregroundStyle(.secondary)326 }327 Section(L("Security")) {328 if account.keyStatus == .ready {329 Button { model.newRecoveryKit() } label: { Label(L("Create a New Recovery Key…"), systemImage: "key") }330 }331 Button { model.signOut() } label: { Label(L("Sign Out"), systemImage: "rectangle.portrait.and.arrow.right") }.accessibilityIdentifier("account-sign-out")332 Button { confirm = .signOutEverywhere } label: { Label(L("Sign Out of All Devices…"), systemImage: "xmark.shield") }333 if account.keyStatus == .ready {334 Button(role: .destructive) { confirm = .erase } label: { Label(L("Erase Synchronized Data…"), systemImage: "icloud.slash") }335 }336 Button(role: .destructive) { confirm = .delete } label: { Label(L("Delete Account and Synchronized Data…"), systemImage: "trash") }337 }338 } else {339 Section { Button { model.signOut() } label: { Label(L("Sign Out"), systemImage: "rectangle.portrait.and.arrow.right") } }340 }341 }342343 @ViewBuilder private var syncSection: some View {344 Section("SP Sync") {345 Toggle(L("Synchronize this device"), isOn: $syncEnabled)346 .onChange(of: syncEnabled) { sync.accountStateChanged() }347 .accessibilityIdentifier("sync-toggle")348 switch account.keyStatus {349 case .notSetUp:350 Text(L("Synchronization is not set up for this account yet.")).font(.callout).foregroundStyle(.secondary)351 Button(L("Set Up Synchronization")) { model.setUpSync() }352 case .waitingForApproval(let code):353 VStack(alignment: .leading, spacing: 6) {354 Label(L("Waiting for one of your other devices"), systemImage: "lock.rotation").font(.headline)355 Text(L("Open SP Browser → Settings → Account on a device that is already synchronized and approve this one. Check that it shows this code:"))356 .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)357 Text(code).font(.system(.title, design: .monospaced).weight(.semibold)).accessibilityIdentifier("verification-code")358 Button(L("Check Again")) { model.syncNow() }359 }360 DisclosureGroup(L("Use the recovery key instead"), isExpanded: $showsRecoveryEntry) { recoveryEntry(button: L("Unlock with Recovery Key")) }361 case .ready:362 LabeledContent(L("Status"), value: statusText)363 if let last = sync.lastSync { LabeledContent(L("Last synchronization"), value: last.formatted(.relative(presentation: .named))) }364 if sync.pendingChanges > 0 { LabeledContent(L("Changes waiting to be sent"), value: "\(sync.pendingChanges)") }365 if let records = model.details?.sync.records { LabeledContent(L("Encrypted records on the server"), value: "\(records)") }366 Button(L("Synchronize Now")) { model.syncNow() }.disabled(!syncEnabled || sync.phase == .syncing)367 case .signedOut:368 EmptyView()369 }370 Text(L("History, bookmarks, favorites, open tabs, reading list, search history and search preferences are synchronized. They are encrypted on this device with a key the server never receives. Private windows are never synchronized."))371 .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)372 }373 }374375 private var statusText: String {376 switch sync.phase {377 case .off: return L("Off")378 case .signedOut: return L("Signed out")379 case .waitingForKey: return L("Waiting for approval")380 case .idle: return L("Up to date")381 case .syncing: return L("Synchronizing…")382 case .offline: return L("Offline — will retry")383 case .failed(let message): return message384 }385 }386387 private func symbol(for platform: String) -> String {388 switch platform {389 case "ios": return "iphone"390 case "ipados": return "ipad"391 default: return "desktopcomputer"392 }393 }394395 private func deviceLine(_ device: AccountDetails.Device) -> String {396 var parts = [device.model.isEmpty ? device.platform : device.model]397 parts.append(L("seen %@", Date(timeIntervalSince1970: device.lastSeenAt / 1000).formatted(.relative(presentation: .named))))398 if let sync = device.lastSyncAt { parts.append(L("synchronized %@", Date(timeIntervalSince1970: sync / 1000).formatted(.relative(presentation: .named)))) }399 if !device.hasSyncKey { parts.append(L("waiting for the encryption key")) }400 return parts.joined(separator: " · ")401 }402}403404/// Shows the recovery key once. The user must acknowledge having saved it.405struct RecoveryKitSheet: View {406 let kit: SyncCrypto.RecoveryKit407 let done: () -> Void408 @State private var saved = false409 @State private var copied = false410411 var body: some View {412 VStack(alignment: .leading, spacing: 14) {413 Label(L("Your recovery key"), systemImage: "key.fill").font(.title2.weight(.semibold))414 Text(L("If you lose every passkey and every device, this key is the only way back into your account and your synchronized data. It is shown only now, and the server does not have it. Keep it somewhere safe and offline."))415 .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)416 Text(kit.text).font(.system(.body, design: .monospaced)).textSelection(.enabled).padding(12)417 .frame(maxWidth: .infinity, alignment: .leading)418 .background(RoundedRectangle(cornerRadius: SPTheme.radiusM).fill(SPTheme.card))419 .accessibilityIdentifier("recovery-key")420 HStack {421 Button { PlatformActions.copy(kit.text); copied = true } label: { Label(copied ? L("Copied") : L("Copy"), systemImage: copied ? "checkmark" : "doc.on.doc") }422 ShareLink(item: kit.text) { Label(L("Save or Print…"), systemImage: "square.and.arrow.up") }423 }424 Toggle(L("I have saved my recovery key"), isOn: $saved).accessibilityIdentifier("recovery-saved")425 HStack { Spacer(); Button(L("Done"), action: done).buttonStyle(.borderedProminent).disabled(!saved).keyboardShortcut(.defaultAction).accessibilityIdentifier("recovery-done") }426 }427 .padding(22)428 #if os(macOS)429 .frame(width: 520)430 #endif431 .interactiveDismissDisabled()432 }433}434