// Cotton Vault's one model: every act a screen shows is sent back here as the// core gave it (`VaultAct`), behind the phone's lock when it says `presence`,// after its question when it says `confirm`, and its answer is drawn where its// method says. The model decides no screen: it carries answers to them.//// Presence is this device's own lock (Face ID or the passcode), read as the// rest of the app reads it (`VaultAccess.lent`): the private key reaches the// one call that takes it as `privateKey` and is never kept.#if os(iOS)importCottonKitimportSwiftUI#if os(iOS)importAuthenticationServicesimportLocalAuthenticationimport UIKitimportUniformTypeIdentifiers#endif/// Secrets' three places, as text tabs at the foot (assets/design/keys/DECISIONS.md "The structure").enumVaultTab: String, CaseIterable, Hashable, Sendable {case secrets, people, you}/// A screen pushed inside a place.enumVaultRoute: Hashable {case item(String)case items(filter: String)case history(String)case healthcase lookcase recovery/// One of his people: what they hold, had and share with him (`secrets.person`).case person(String)/// The one-time check with a person (`secrets.check`).case check(String, name: String)/// A secret one of his people shared with him (`secrets.shared`).case shared(String)}/// What a sheet over Vault holds.enumVaultSheet: Identifiable {case edit(VaultEdit)case kinds(VaultAddMenu)case quick(VaultRow)case input(VaultAct)case export(title: String, answer: JSONValue)case shown(title: String, value: String)/// Share one secret (`secrets.share.plan`).case share(String)/// Take one secret back from one person (`secrets.take.plan`).case take(id: String, number: String)/// Answer an ask (`secrets.asks`).case answer(String)/// Ask one of his people for a secret.case askFor(number: String, name: String)/// Bring in from Dashlane (`secrets.import.plan`).case dashlanevar id: String {switchself {case .edit(let edit): return"edit:\(edit.id ?? edit.kind)"case .kinds: return"kinds"case .quick(let row): return"quick:\(row.id)"case .input(let act): return"input:\(act.id)"case .export(let title, _): return"export:\(title)"case .shown(let title, _): return"shown:\(title)"case .share(let id): return"share:\(id)"case .take(let id, let number): return"take:\(id):\(number)"case .answer(let ask): return"answer:\(ask)"case .askFor(let number, _): return"ask:\(number)"case .dashlane: return"dashlane" } }}@MainActor@ObservablefinalclassVaultModel {var look: VaultLook?var tab: VaultTab = .secretsvar paths: [VaultTab: [VaultRoute]] = [:]var sheet: VaultSheet?var asking: VaultAsking?/// Bumped after every act that may change what a screen shows: each/// screen reads its answer again.private(set) var generation = 0/// The tab titles, as each place's answer names itself.var titles: [VaultTab: String] = [:]/// `system`, `light` or `dark`, as Settings' Appearance chose.private(set) var appearance = "system"/// Minutes in the background before the vault locks (0: at once).private(set) var lockMinutes: Int?/// A generated password a form's Generate is waiting for.var fillingField: String?var generated: String? @ObservationIgnored let core: any CottonCalling @ObservationIgnored let toasts: ToastCenter @ObservationIgnored let unlockAsks: UnlockAsks @ObservationIgnored let signInAsks: SignInAsks/// The shell's recovery rounds, which keep an iCloud copy Vault's act made. @ObservationIgnored var recovery: RecoveryKeys? @ObservationIgnored var nativeFlow: (@MainActor (RecordKeptFlow) async -> Bool)? @ObservationIgnored privatelet vault: VaultAccess @ObservationIgnored privatevar backgroundedAt: Date?init(core: any CottonCalling, toasts: ToastCenter, unlockAsks: UnlockAsks, signInAsks: SignInAsks, vault: VaultAccess = VaultAccess()) {self.core = coreself.vault = vaultself.toasts = toastsself.unlockAsks = unlockAsksself.signInAsks = signInAsksSecretsFonts.register() }/// Whether the vault stands open on this phone, as the list last answered (nil before it has).varopen: Bool?/// Why the lock could not be asked (a phone with no passcode), in the core's words; nil when it can.var cannotOpen: String?/// The gate's answer while it stands shut (no passcode on this phone): its title, its words and its act.var gate: SecretsGate?/// The Unlock screen's one act: the phone's lock, then the vault opened for its while.func unlock() async { cannotOpen = nil// Secrets opens only behind the phone's own lock (`secrets.gate`, DECISIONS question 14): a phone with no// passcode is told why, with the way to its settings.let passcode = LAContext().canEvaluatePolicy(.deviceOwnerAuthentication, error: nil)ifcase .read(let gate) = await secrets("secrets.gate", ["passcode": .bool(passcode)], as: SecretsGate.self) {self.gate = gate.open ? nil : gateif !gate.open { cannotOpen = gate.line changed()return } }switchawait vault.lent() {case .key(let key):do { _ = tryawait core.callJSON("vault.unlock", JSONValue.object(["privateKey": .string(key)]))open = true } catchlet error asCottonCallErrorwhere error.code == "vault_not_wrapped_yet" {// A phone that has never signed in has no vault to open yet. With nothing kept here there is nothing// to guard: Secrets opens, so he can sign in from You or add his first secret.iflet items = try? await core.call("vault.items", JSONValue.object(["filter": "all"]), as: VaultItems.self), items.total == 0 {open = true } else { cannotOpen = error.message } } catchlet error asCottonCallError { cannotOpen = error.message } catch { cannotOpen = ShellLines.line("passwords", "vault.this_phone_could_not") }case .not(.noPresence):// Secrets asks for the phone's passcode before it opens (DECISIONS question 14), and says why. cannotOpen = ShellLines.line("unlock", "no_presence")case .not(.refused(let words)):// Why it cannot open (waiting for another device to share the key, a key that no longer matches) stands// on Unlock in place, not in a toast that goes. cannotOpen = wordscase .not:break } changed() }// ── reading ─────────────────────────────────────────────────────────/// The look, once.func readLook() async {guard look == nilelse { return }do { look = tryawait core.call("vault.look", EmptyRequest(), as: VaultLook.self) } catch {Log.write("vault: the look could not be read — \(error)") } }/// One screen's answer. A refusal is said once and answers nil.func read<Answer: Decodable & Sendable>(_ method: String, _ request: JSONValue = .object([:]), as type: Answer.Type) async -> Answer? {do {returntryawait core.call(method, request, as: type) } catchlet error asCottonCallError {Log.write("vault: \(method) refused — \(error.code)") toasts.show(error.message, tone: .error) } catch {Log.write("vault: \(method) did not read — \(error)") }returnnil }/// You's choices that change how the app behaves here: the lock's minutes/// (the chosen row is `tone: accent`).func readChoices() async {guardlet settings = await read("vault.settings", .object(["platform": "ios"]), as: VaultSettings.self) else { return } take(settings) }func take(_ settings: VaultSettings) { titles[.you] = settings.titlefor group in settings.groups {guardlet chosen = group.rows.first(where: { $0.tone == .accent }), let value = chosen.open?.request["value"] else { continue }switch group.id {case"appearance": appearance = value.string ?? "system"case"lock": lockMinutes = value.intdefault: break } } }var scheme: ColorScheme? {switch appearance {case"light": return .lightcase"dark": return .darkdefault: returnnil } }func changed() { generation += 1 }// ── the lock ────────────────────────────────────────────────────────func scene(_ phase: ScenePhase) {switch phase {case .background: backgroundedAt = Date() keeping?.cancel() keeping = nilif lockMinutes == 0 {Task { await lock() } } else {// The core holds the key exactly as long as Lock after says, from now.Task { _ = try? await core.callJSON("vault.keep", JSONValue.object(["leaving": .bool(true)])) } }case .active:iflet at = backgroundedAt, let minutes = lockMinutes, minutes > 0, Date().timeIntervalSince(at) >= Double(minutes * 60) {Task { await lock() } } backgroundedAt = nil keep()// What came while he was away (an ask, a share, a take back) is read again as he comes back (the walk,// 25 Nov 2026: Ben's ask showed on Asha's list only after a relaunch).ifopen == true { changed() }default: break } }/// While Secrets is in front and open, the core's hold on the key is renewed each minute, so it locks after he/// LEAVES, never in his hand (launch-ios's walk, 25 Nov 2026). If the core has shut it meanwhile, Unlock says so. @ObservationIgnored privatevar keeping: Task<Void, Never>?func keep() { keeping?.cancel() keeping = Task { [weakself] inwhile !Task.isCancelled {guardletselfelse { return }ifself.open == true {let answer = try? awaitself.core.callJSON("vault.keep", JSONValue.object([:]))iflet answer, case .object(let fields) = answer, fields["open"] == .bool(false) {self.open = falseself.changed() } }try? awaitTask.sleep(for: .seconds(60)) } } }privatefunc lock() async { _ = try? await core.callJSON("vault.lock", EmptyRequest())// Secrets stands shut again: Unlock, until the phone's lock opens it.open = false changed() }// ── acts ────────────────────────────────────────────────────────────/// Ask an act's question, if it has one.func confirmed(_ act: VaultAct) async -> Bool {guardlet confirm = act.confirm else { returntrue }returnawait withCheckedContinuation { continuation in asking = VaultAsking(confirm: confirm, tone: act.tone) { [weakself] yes inself?.asking = nil continuation.resume(returning: yes) } } }/// The methods that take this device's vault key as `privateKey`; any/// other act behind presence asks the lock and is sent as it came.privatestaticfunc takesKey(_ method: String) -> Bool { ["vault.", "recovery.", "keys.", "password.", "secrets."].contains { method.hasPrefix($0) } }/// Send one act's request (with what was typed added), behind presence/// when it says so. Answers the core's answer, or nil when nothing was/// sent or it was refused (the refusal said).func send(_ act: VaultAct, adding extra: [String: JSONValue] = [:]) async -> JSONValue? {var request = act.requestfor (key, value) in extra { request = request.setting(key, value) }if act.presence {switchawait vault.lent() {case .key(let key):ifSelf.takesKey(act.method) { request = request.setting("privateKey", .string(key)) }case .not(.cancelled):returnnilcase .not(.noPresence): toasts.show(ShellLines.line("unlock", "no_presence"), tone: .error)returnnilcase .not(.refused(let words)): toasts.show(words, tone: .error)returnnilcase .not:returnnil } }do {returntryawait core.callJSON(act.method, request) } catchlet error asCottonCallErrorwhere error.code == "vault_locked" && !act.presence {// A shut vault asks the lock once, then the same request again.var asked = act asked.presence = truereturnawait send(asked, adding: extra) } catchlet error asCottonCallError {Log.write("vault: \(act.method) refused — \(error.code)") toasts.show(error.message, tone: .error) } catch {Log.write("vault: \(act.method) did not answer — \(error)") toasts.show(ShellLines.line("passwords", "vault.this_phone_could_not"), tone: .error) }returnnil }/// Run an act end to end: its question, its presence, its request, and/// its answer drawn where its method says.func run(_ act: VaultAct, adding extra: [String: JSONValue] = [:]) async {// An act that asks for a field first (`input`): its panel, then this// act again with what was typed under its key.iflet input = act.input, extra[input.key] == nil { sheet = .input(act)return }guardawait confirmed(act) else { return }// Opening a screen sends nothing until it reads its own answer.switch act.method {case"vault.item":iflet id = act.request["id"]?.string { push(.item(id)) }returncase"vault.items": push(.items(filter: act.request["filter"]?.string ?? "all"))return// The unlock card and the sign-in approval stand over the window// by themselves once read (`UnlockAsksLayer`, `SignInAskBanner`).case"unlock.card":await unlockAsks.read()returncase"signin.show":await signInAsks.read()returncase"signin.passkeyOptions":await addPasskey(act)returncase"vault.breach":await checkBreaches(act)returncase"vault.act"where act.request["act"]?.string == "import" && act.request["from"]?.string == "dashlane","vault.act"where act.request["act"]?.string == "open_page" && act.request["page"]?.string == "import":// (The core's You row opens page `import` now; the walk, 26 Nov 2026: the row did nothing.)// A whole Dashlane export is Secrets' own page now: the plan said first, then one sealed write. sheet = .dashlanereturncase"secrets.asks":iflet ask = act.request["ask"]?.string { sheet = .answer(ask) }returndefault: break }guardlet answer = await send(act, adding: extra) else { return }await take(answer, of: act) }/// An answer drawn where its method says.func take(_ answer: JSONValue, of act: VaultAct) async {switch act.method {case"vault.history":iflet id = act.request["id"]?.string { push(.history(id)) }case"vault.edit":iflet edit = Self.decode(answer, as: VaultEdit.self) { sheet = .edit(edit) }case"vault.field":iflet field = Self.decode(answer, as: VaultFieldAnswer.self) { copy(field.value, clearAfter: field.clearAfter, toast: field.copiedToast) }case"vault.code":iflet code = Self.decode(answer, as: VaultCodeAnswer.self) { copy(code.code, clearAfter: code.clearAfter, toast: code.copiedToast) }case"vault.act", "vault.save":await acted(answer)case"recovery.make", "recovery.show":iflet code = answer.text("code") { sheet = .shown(title: act.label, value: code) } changed()case"recovery.makePlatform":// This phone's copy in iCloud Keychain, kept as the shell's offer keeps it.iflet key = answer.text("key") { _ = await recovery?.keepPlatform(key) }iflet said = answer.text("said") { toasts.show(said, tone: .success, window: Self.toastSeconds) } changed()case"keys.exportCsv", "keys.exportCxf":// The warning first, with Share under it (as on Android). sheet = .export(title: act.label, answer: answer)case"vault.unlock": changed()default:iflet said = answer.text("said") { toasts.show(said, tone: .success) } changed() } }/// `vault.act`'s and `vault.save`'s answer: its toast (with Undo), the/// item redrawn, back to the list when it went, or what only the phone can do.privatefunc acted(_ answer: JSONValue) async {guardlet acted = Self.decode(answer, as: VaultActAnswer.self) else { return }// When a question follows (Send the new one to …?), it speaks for the save: no toast lies over its buttons// (the walk, 26 Nov 2026: "Saved." covered Send it).iflet toast = acted.toast, answer["ask"] == nil {iflet undo = toast.undo { toasts.show(toast.text, tone: .notice, window: Self.toastSeconds, undo: { [weakself] inTask { awaitself?.run(undo) } }) } else { toasts.show(toast.text, tone: .success, window: Self.toastSeconds) } }if acted.gone { pop() }iflet platform = acted.platform { await perform(platform) }await reshare(answer) changed() }/// A shared secret saved with a new value: the core asks whether the new one goes to the people who still hold it/// (CONTRACT "Add and edit": `ask { line, yes, no }`); yes sends it, sealed for each, behind the phone's lock.privatefunc reshare(_ answer: JSONValue) async {guardlet ask = answer["ask"], let line = ask.text("line"), let yes = ask.text("yes"), let no = ask.text("no"),let id = answer.text("id") ?? ask.text("id") else { return }var act = VaultAct(id: "reshare", label: yes, method: "secrets.reshare", request: .object(["id": .string(id)]), presence: true, tone: .accent) act.confirm = VaultConfirm(title: line, body: "", yes: yes, no: no)guardawait confirmed(act), let sent = await send(act) else { return }iflet said = sent.text("line") { toasts.show(said, tone: .success, window: Self.toastSeconds) } }/// What only the phone can do (`platform`).privatefunc perform(_ platform: JSONValue) async {if platform.text("platform_action") == "open_flow" {guardlet flow = Self.decode(platform, as: RecordKeptFlow.self) else { return } _ = await nativeFlow?(flow)return } #if os(iOS)switch platform.text("action") {case"open_url":iflet address = platform.text("url"), let url = URL(string: address) { await UIApplication.shared.open(url) }case"open_fill_settings":do {tryawait ASSettingsHelper.openCredentialProviderAppSettings() } catch {Log.write("vault: the AutoFill settings did not open — \(error)") }case"pick_csv":await importCsv(then: platform.text("then") ?? CottonMethod.passwordImportCsv)default:Log.write("vault: no phone act \(platform.text("action") ?? "?")") } #endif } #if os(iOS)/// Pick a CSV and send its text to `then`; a locked vault asks the lock once.privatefunc importCsv(then method: String) async {guardlet picked = awaitSystemFilePicker.pick([.commaSeparatedText, .plainText]), let url = picked.first else { return }let opened = url.startAccessingSecurityScopedResource()defer { if opened { url.stopAccessingSecurityScopedResource() } }guardlet text = try? String(contentsOf: url, encoding: .utf8) else { toasts.show(ShellLines.line("passwords", "vault.this_phone_could_not"), tone: .error)return }let act = VaultAct(id: "import", label: "", method: method, request: .object(["csv": .string(text)]))var answer: JSONValue?do { answer = tryawait core.callJSON(method, act.request) } catchlet error asCottonCallErrorwhere error.code == "vault_locked" {var asked = act asked.presence = true answer = await send(asked) } catchlet error asCottonCallError { toasts.show(error.message, tone: .error) } catch { toasts.show(ShellLines.line("passwords", "vault.this_phone_could_not"), tone: .error) }iflet said = answer?.text("said") { toasts.show(said, tone: .success, window: 8) } changed() } #endif/// Check for breaches, in its two steps (SHAPES `vault.breach`): the/// ranges the core names, each fetched as given (`VaultBreachFetch`), then/// the bodies handed back to `then` with the key the first step was lent,/// so one presence covers both; its toast, then Security read again.privatefunc checkBreaches(_ act: VaultAct) async {var lent: String?if act.presence {switchawait vault.lent() {case .key(let key): lent = keycase .not(.noPresence): toasts.show(ShellLines.line("unlock", "no_presence"), tone: .error)returncase .not(.refused(let words)): toasts.show(words, tone: .error)returncase .not:return } }var keyed = act keyed.presence = falselet key: [String: JSONValue] = lent.map { ["privateKey": .string($0)] } ?? [:]guardlet asked = await send(keyed, adding: key) else { return }guardlet platform = asked["platform"], platform.text("action") == "fetch_ranges"else {await acted(asked)return }let prefixes = platform["prefixes"]?.strings ?? []let addresses = platform["addresses"]?.strings ?? []var headers: [String: String] = [:]ifcase .object(let given)? = platform["headers"] { for (name, value) in given { headers[name] = value.string } }let ranges = awaitVaultBreachFetch.ranges(Array(zip(prefixes, addresses)), headers: headers)let then = VaultAct(id: act.id, label: act.label, method: platform.text("then") ?? act.method, request: .object(["ranges": .object(ranges.mapValues(JSONValue.string))]))iflet checked = await send(then, adding: key) { await acted(checked) } }/// Add a passkey for Cotton: the core's options, the system's sheet, the/// passkey kept at the object (as Account does it).privatefunc addPasskey(_ act: VaultAct) async { #if os(iOS)guardlet options = await send(act), let request = options.text("requestJson") else { return }let response: Stringdo { response = tryawaitAccountPasskeySheet.add(requestJSON: request) } catchAccountPasskeyRefusal.cancelled { toasts.show(SignInWords.passkeyCancelled)return } catch { toasts.show(ShellLines.line("passwords", "vault.this_phone_could_not"), tone: .error)return }let add = VaultAct(id: "add", label: "", method: CottonMethod.signinPasskeyAdd, request: .object(["responseJson": .string(response), "name": .string(ThisPhone.deviceName())]))iflet said = await send(add)?.text("said") { toasts.show(said, tone: .success) } changed() #endif }/// An export's text to the system's share sheet.func share(_ answer: JSONValue) { #if os(iOS)guardlet text = answer.text("text") else { return }let name = answer.text("fileName") ?? "export.csv"let url = FileManager.default.temporaryDirectory.appendingPathComponent(name)do {tryData(text.utf8).write(to: url, options: [.atomic, .completeFileProtection]) } catch { toasts.show(ShellLines.line("passwords", "vault.this_phone_could_not"), tone: .error)return }let sheet = UIActivityViewController(activityItems: [url], applicationActivities: nil) sheet.completionWithItemsHandler = { _, _, _, _ intry? FileManager.default.removeItem(at: url) } UIApplication.shared.topViewController?.present(sheet, animated: true) #endif }/// A value to the clipboard, cleared after the answer's seconds (0: kept).func copy(_ value: String, clearAfter: Int, toast: String) { #if os(iOS)var options: [UIPasteboard.OptionsKey: Any] = [.localOnly: true]if clearAfter > 0 { options[.expirationDate] = Date().addingTimeInterval(TimeInterval(clearAfter)) }// Marked concealed (AUDIT E): Cotton's own Clips, and any clipboard keeper, leave a password alone. UIPasteboard.general.setItems([[UTType.utf8PlainText.identifier: value, PasteboardMark.concealed: Data()]], options: options) #endif toasts.show(toast, tone: .success, window: Self.toastSeconds) }/// How long a receipt stands (SHAPES "Decided" 11), Undo or not.staticlet toastSeconds: TimeInterval = 4// ── navigation ─────────────────────────────────────────────────────func push(_ route: VaultRoute) { paths[tab, default: []].append(route) }func pop() {guardvar path = paths[tab], !path.isEmpty else { return } path.removeLast() paths[tab] = path }/// The generator's Use in a new login, or a form's Generate.func useNew(_ act: VaultAct) async { tab = .secretsawait run(act) }staticfunc decode<T: Decodable>(_ value: JSONValue, as type: T.Type) -> T? {do {let data = try JSONEncoder().encode(value)returntry JSONDecoder().decode(type, from: data) } catch {Log.write("vault: an answer did not read as \(type) — \(error)")returnnil } }}#if os(iOS)extension UIApplication {/// The view controller on top, to present the share sheet over.var topViewController: UIViewController? {let scene = connectedScenes.compactMap { $0 as? UIWindowScene }.first { $0.activationState == .foregroundActive }var top = scene?.keyWindow?.rootViewControllerwhilelet presented = top?.presentedViewController { top = presented }return top } }#endif#endif