Cotton code
627 lines · 27.9 KB · SwiftRaw
// 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)import CottonKitimport SwiftUI#if os(iOS)    import AuthenticationServices    import LocalAuthentication    import UIKit    import UniformTypeIdentifiers#endif/// Secrets' three places, as text tabs at the foot (assets/design/keys/DECISIONS.md "The structure").enum VaultTab: String, CaseIterable, Hashable, Sendable {    case secrets, people, you}/// A screen pushed inside a place.enum VaultRoute: Hashable {    case item(String)    case items(filter: String)    case history(String)    case health    case look    case 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.enum VaultSheet: 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 dashlane    var id: String {        switch self {        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@Observablefinal class VaultModel {    var look: VaultLook?    var tab: VaultTab = .secrets    var 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 private let vault: VaultAccess    @ObservationIgnored private var backgroundedAt: Date?    init(core: any CottonCalling, toasts: ToastCenter, unlockAsks: UnlockAsks, signInAsks: SignInAsks, vault: VaultAccess = VaultAccess()) {        self.core = core        self.vault = vault        self.toasts = toasts        self.unlockAsks = unlockAsks        self.signInAsks = signInAsks        SecretsFonts.register()    }    /// Whether the vault stands open on this phone, as the list last answered (nil before it has).    var open: 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)        if case .read(let gate) = await secrets("secrets.gate", ["passcode": .bool(passcode)], as: SecretsGate.self) {            self.gate = gate.open ? nil : gate            if !gate.open {                cannotOpen = gate.line                changed()                return            }        }        switch await vault.lent() {        case .key(let key):            do {                _ = try await core.callJSON("vault.unlock", JSONValue.object(["privateKey": .string(key)]))                open = true            } catch let error as CottonCallError where 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.                if let items = try? await core.call("vault.items", JSONValue.object(["filter": "all"]), as: VaultItems.self), items.total == 0 {                    open = true                } else {                    cannotOpen = error.message                }            } catch let error as CottonCallError {                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 = words        case .not:            break        }        changed()    }    // ── reading ─────────────────────────────────────────────────────────    /// The look, once.    func readLook() async {        guard look == nil else { return }        do {            look = try await 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 {            return try await core.call(method, request, as: type)        } catch let error as CottonCallError {            Log.write("vault: \(method) refused — \(error.code)")            toasts.show(error.message, tone: .error)        } catch {            Log.write("vault: \(method) did not read — \(error)")        }        return nil    }    /// You's choices that change how the app behaves here: the lock's minutes    /// (the chosen row is `tone: accent`).    func readChoices() async {        guard let settings = await read("vault.settings", .object(["platform": "ios"]), as: VaultSettings.self) else { return }        take(settings)    }    func take(_ settings: VaultSettings) {        titles[.you] = settings.title        for group in settings.groups {            guard let 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.int            default: break            }        }    }    var scheme: ColorScheme? {        switch appearance {        case "light": return .light        case "dark": return .dark        default: return nil        }    }    func changed() { generation += 1 }    // ── the lock ────────────────────────────────────────────────────────    func scene(_ phase: ScenePhase) {        switch phase {        case .background:            backgroundedAt = Date()            keeping?.cancel()            keeping = nil            if 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:            if let 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).            if open == 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 private var keeping: Task<Void, Never>?    func keep() {        keeping?.cancel()        keeping = Task { [weak self] in            while !Task.isCancelled {                guard let self else { return }                if self.open == true {                    let answer = try? await self.core.callJSON("vault.keep", JSONValue.object([:]))                    if let answer, case .object(let fields) = answer, fields["open"] == .bool(false) {                        self.open = false                        self.changed()                    }                }                try? await Task.sleep(for: .seconds(60))            }        }    }    private func 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 {        guard let confirm = act.confirm else { return true }        return await withCheckedContinuation { continuation in            asking = VaultAsking(confirm: confirm, tone: act.tone) { [weak self] yes in                self?.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.    private static func 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.request        for (key, value) in extra { request = request.setting(key, value) }        if act.presence {            switch await vault.lent() {            case .key(let key):                if Self.takesKey(act.method) { request = request.setting("privateKey", .string(key)) }            case .not(.cancelled):                return nil            case .not(.noPresence):                toasts.show(ShellLines.line("unlock", "no_presence"), tone: .error)                return nil            case .not(.refused(let words)):                toasts.show(words, tone: .error)                return nil            case .not:                return nil            }        }        do {            return try await core.callJSON(act.method, request)        } catch let error as CottonCallError where error.code == "vault_locked" && !act.presence {            // A shut vault asks the lock once, then the same request again.            var asked = act            asked.presence = true            return await send(asked, adding: extra)        } catch let error as CottonCallError {            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)        }        return nil    }    /// 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.        if let input = act.input, extra[input.key] == nil {            sheet = .input(act)            return        }        guard await confirmed(act) else { return }        // Opening a screen sends nothing until it reads its own answer.        switch act.method {        case "vault.item":            if let id = act.request["id"]?.string { push(.item(id)) }            return        case "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()            return        case "signin.show":            await signInAsks.read()            return        case "signin.passkeyOptions":            await addPasskey(act)            return        case "vault.breach":            await checkBreaches(act)            return        case "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 = .dashlane            return        case "secrets.asks":            if let ask = act.request["ask"]?.string { sheet = .answer(ask) }            return        default: break        }        guard let 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":            if let id = act.request["id"]?.string { push(.history(id)) }        case "vault.edit":            if let edit = Self.decode(answer, as: VaultEdit.self) { sheet = .edit(edit) }        case "vault.field":            if let field = Self.decode(answer, as: VaultFieldAnswer.self) { copy(field.value, clearAfter: field.clearAfter, toast: field.copiedToast) }        case "vault.code":            if let 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":            if let 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.            if let key = answer.text("key") { _ = await recovery?.keepPlatform(key) }            if let 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:            if let 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.    private func acted(_ answer: JSONValue) async {        guard let 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).        if let toast = acted.toast, answer["ask"] == nil {            if let undo = toast.undo {                toasts.show(toast.text, tone: .notice, window: Self.toastSeconds, undo: { [weak self] in Task { await self?.run(undo) } })            } else {                toasts.show(toast.text, tone: .success, window: Self.toastSeconds)            }        }        if acted.gone { pop() }        if let 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.    private func reshare(_ answer: JSONValue) async {        guard let 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)        guard await confirmed(act), let sent = await send(act) else { return }        if let said = sent.text("line") { toasts.show(said, tone: .success, window: Self.toastSeconds) }    }    /// What only the phone can do (`platform`).    private func perform(_ platform: JSONValue) async {        if platform.text("platform_action") == "open_flow" {            guard let flow = Self.decode(platform, as: RecordKeptFlow.self) else { return }            _ = await nativeFlow?(flow)            return        }        #if os(iOS)            switch platform.text("action") {            case "open_url":                if let address = platform.text("url"), let url = URL(string: address) { await UIApplication.shared.open(url) }            case "open_fill_settings":                do {                    try await 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.        private func importCsv(then method: String) async {            guard let picked = await SystemFilePicker.pick([.commaSeparatedText, .plainText]), let url = picked.first else { return }            let opened = url.startAccessingSecurityScopedResource()            defer { if opened { url.stopAccessingSecurityScopedResource() } }            guard let 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 = try await core.callJSON(method, act.request)            } catch let error as CottonCallError where error.code == "vault_locked" {                var asked = act                asked.presence = true                answer = await send(asked)            } catch let error as CottonCallError {                toasts.show(error.message, tone: .error)            } catch {                toasts.show(ShellLines.line("passwords", "vault.this_phone_could_not"), tone: .error)            }            if let 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.    private func checkBreaches(_ act: VaultAct) async {        var lent: String?        if act.presence {            switch await vault.lent() {            case .key(let key): lent = key            case .not(.noPresence):                toasts.show(ShellLines.line("unlock", "no_presence"), tone: .error)                return            case .not(.refused(let words)):                toasts.show(words, tone: .error)                return            case .not:                return            }        }        var keyed = act        keyed.presence = false        let key: [String: JSONValue] = lent.map { ["privateKey": .string($0)] } ?? [:]        guard let asked = await send(keyed, adding: key) else { return }        guard let 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] = [:]        if case .object(let given)? = platform["headers"] { for (name, value) in given { headers[name] = value.string } }        let ranges = await VaultBreachFetch.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))]))        if let 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).    private func addPasskey(_ act: VaultAct) async {        #if os(iOS)            guard let options = await send(act), let request = options.text("requestJson") else { return }            let response: String            do {                response = try await AccountPasskeySheet.add(requestJSON: request)            } catch AccountPasskeyRefusal.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())]))            if let 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)            guard let text = answer.text("text") else { return }            let name = answer.text("fileName") ?? "export.csv"            let url = FileManager.default.temporaryDirectory.appendingPathComponent(name)            do {                try Data(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 = { _, _, _, _ in try? 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.    static let toastSeconds: TimeInterval = 4    // ── navigation ─────────────────────────────────────────────────────    func push(_ route: VaultRoute) { paths[tab, default: []].append(route) }    func pop() {        guard var 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 = .secrets        await run(act)    }    static func decode<T: Decodable>(_ value: JSONValue, as type: T.Type) -> T? {        do {            let data = try JSONEncoder().encode(value)            return try JSONDecoder().decode(type, from: data)        } catch {            Log.write("vault: an answer did not read as \(type) — \(error)")            return nil        }    }}#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?.rootViewController            while let presented = top?.presentedViewController { top = presented }            return top        }    }#endif#endif