Cotton code
676 lines · 28.5 KB · SwiftRaw
// LOSING A PHONE NEVER LOSES THE DATA, ON THE iPHONE (e2e rulings R7a, R7c,// R7d; 16 Nov 2026). The core does the work// (`crates/cotton-ffi/src/phone/recovery.rs`) and says every word// (`recovery.status.lines`, kit `kits/shell/lines/unlock.json`); this file// asks it at the moments Android's shell does (`RecoveryCard.kt`,// `core/SealedKeys.kt`) and draws its answers on the shell's own paper.////   * **iCloud Keychain copy (R7a).** A phone holding the vault keeps a//     platform key (`recovery.makePlatform { store: "apple" }`) as a//     synchronizable Keychain item (`CottonKit/PlatformKey.swift`). A new//     iPhone on the same Apple account that needs the key and does not found//     reads that item and opens with it (`recovery.openPlatform`), no step.//   * **The recovery code (R7c).** Offered once, the first time this phone//     holds the vault and no code is set: the code is made at once and shown//     with Copy (local only, gone in two minutes) and Not now. Not now on a//     phone that is the person's only way in says the honest line, once.//     "I have a code" stands beside the waiting slip, checks a typo as the//     code is typed (`recovery.check`), and opens with no other device.//     The code shown offers Copy only, never "Save to my passwords" (owner,//     16 Nov 2026: removed on iPhone and Android; a better way to keep the//     code is to be designed with him).//   * **A trusted person (R7d).** Beside the waiting slip, "Ask <name> to//     help" (`recovery.askHelp`, then `recovery.helped` on every read until//     it opens). On a phone holding the vault, in every app, a helper's card//     ("Help <name> get back in") read every 20 seconds while the app is in//     front: Approve behind Face ID / the passcode, Not now.//// Nothing here ever blocks first use, and nothing prompts but Approve, Show// and Make a new code (Account), and choosing a helper.import CottonKitimport SwiftUIimport UniformTypeIdentifiers#if os(iOS)    import UIKit    import UniformTypeIdentifiers#endif/// A code drawn on the card: just made by the offer, or shown again.struct ShownCode: Equatable, Sendable {    let code: String    /// Made by the offer (Not now), not asked from Account (Done).    let offered: Bool}/// A helper's card: someone who trusted this person asks to get back in.struct HelpAsk: Equatable, Sendable, Identifiable {    let id: String    let line: String    let approve: String    let decline: String    let approved: String?    init?(_ value: JSONValue) {        guard let id = value.text("id"), let line = value.text("line"), let approve = value.text("approve"),            let decline = value.text("decline") else { return nil }        self.id = id        self.line = line        self.approve = approve        self.decline = decline        approved = value.text("approved")    }}struct RecoveryKeyRequest: Encodable, Sendable { let privateKey: String }struct RecoveryCheckRequest: Encodable, Sendable { let code: String }struct RecoveryOpenRequest: Encodable, Sendable {    let code: String    let privateKey: String    let name: String}/// `recovery.status` told what this phone's Keychain did with the iCloud/// copy: `back` (kept: it outlives a delete of the app on/// this iPhone, and iCloud Keychain carries it to a new one when it is on),/// `none` (the Keychain refused it). Nil until a round has tried.struct RecoveryStatusRequest: Encodable, Sendable { let copy: String? }struct PlatformMakeRequest: Encodable, Sendable {    let store: String    let privateKey: String}struct PlatformOpenRequest: Encodable, Sendable {    let store: String    let key: String    let privateKey: String    let name: String}struct RecoveryTrustRequest: Encodable, Sendable {    let number: String    let name: String?    let privateKey: String}struct RecoveryHelpRequest: Encodable, Sendable {    let privateKey: String    let name: String}struct HelpAskRequest: Encodable, Sendable { let id: String }@MainActor@Observablefinal class RecoveryKeys {    /// `recovery.status`, as last read.    private(set) var status: JSONValue?    private(set) var shown: ShownCode?    /// Save to Files is open over the card (GETTING-IN.md).    var exporting = false    /// The one reminder, a week after Not now on a code never saved: its card stands.    private(set) var reminding = false    private(set) var helpAsks: [HelpAsk] = []    /// The code typed under I have a code, and what the typo check said.    var entering = false    var typed = "" {        didSet { if typed != oldValue { Task { await check() } } }    }    private(set) var problem: String?    private(set) var busy = false    /// This device asked its helper.    private(set) var asked = false    @ObservationIgnored private let core: any CottonCalling    /// The core these keys call, for a screen drawn beside them (the trusted recovery screens).    var calling: any CottonCalling { core }    @ObservationIgnored private let vault: VaultAccess    @ObservationIgnored private let platform: any PlatformKeyKeeping    @ObservationIgnored private let name: @Sendable () -> String    @ObservationIgnored private let presence: @Sendable () throws -> Void    @ObservationIgnored private let say: @MainActor (String, CottonToast.Tone) -> Void    /// Read the sealed state again once something opened this device.    @ObservationIgnored var opened: (@MainActor () async -> Void)?    @ObservationIgnored private var offerDone = false    @ObservationIgnored private var aloneSaid = false    @ObservationIgnored private var platformKept = false    /// What the Keychain did with the copy this launch (`RecoveryStatusRequest`).    @ObservationIgnored private var copyKept: String?    /// The copy was tried this launch. A Keychain that will not keep it (no    /// iCloud Keychain to write to, a simulator) is asked once, not at every    /// pull: each try makes a new platform key on the object, whose write    /// brings the next pull, and the app never came to rest.    @ObservationIgnored private var platformTried = false    @ObservationIgnored private var platformTries = 0    @ObservationIgnored private var helpLoop: Task<Void, Never>?    /// The store iCloud Keychain carries (`recovery.*` `store`).    static let store = "apple"    /// How many times a new phone tries the iCloud copy before it stops.    static let maxPlatformTries = 6    /// How often a phone holding the vault looks for a helper's ask.    static let helpSeconds: Double = 20    /// How long a copied code stays on the pasteboard.    static let copiedSeconds: Double = 120    init(        core: any CottonCalling, vault: VaultAccess, platform: any PlatformKeyKeeping = ICloudPlatformKeys(),        name: @escaping @Sendable () -> String = { ThisPhone.deviceName() },        presence: @escaping @Sendable () throws -> Void = { try VaultPresence.ask() },        say: @escaping @MainActor (String, CottonToast.Tone) -> Void    ) {        self.core = core        self.vault = vault        self.platform = platform        self.name = name        self.presence = presence        self.say = say    }    /// One of the core's words for recovery.    func line(_ key: String) -> String? { status?["lines"]?.text(key) }    /// Whom this person trusted, as the core says it (`trusted.ask`: Ask    /// <name> to help), on a device that waits.    var askHelper: String? { status?["trusted"]?.text("ask") }    func refresh() async {        status = try? await core.callJSON(CottonMethod.recoveryStatus, RecoveryStatusRequest(copy: copyKept))    }    // ── a new phone ──────────────────────────────────────────────────────    /// A new iPhone on the same Apple account: the iCloud Keychain copy, read    /// and tried with nobody asked. True once it opened.    func openFromICloud(database: String) async -> Bool {        guard platformTries < Self.maxPlatformTries, let key = platform.read(database: database) else { return false }        platformTries += 1        let name = name()        let store = Self.store        switch await vault.handing(CottonMethod.recoveryOpenPlatform, through: core, quiet: true, { privateKey in            PlatformOpenRequest(store: store, key: key, privateKey: privateKey, name: name)        }) {        case .answered(let answer):            platformTries = Self.maxPlatformTries            if let words = answer.text("line") { say(words, .success) }            return answer.flag("opened")        case .cancelled, .noPresence, .refused:            return false        }    }    /// While this device waits: the recovery words for its slip, and, once it    /// asked its helper, whether the help arrived.    func whileWaiting() async -> Bool {        if status == nil { await refresh() }        guard asked else { return false }        let name = name()        switch await vault.handing(CottonMethod.recoveryHelped, through: core, quiet: true, { key in            RecoveryHelpRequest(privateKey: key, name: name)        }) {        case .answered(let answer) where answer.flag("opened"):            asked = false            if let words = answer.text("line") { say(words, .success) }            return true        default:            return false        }    }    /// *Ask <name> to help*.    func askHelp() async {        guard !busy else { return }        busy = true        defer { busy = false }        let name = name()        switch await vault.handing(CottonMethod.recoveryAskHelp, through: core, quiet: true, { key in            RecoveryHelpRequest(privateKey: key, name: name)        }) {        case .answered(let answer):            asked = true            if let words = answer.text("line") { say(words, .notice) }        case .refused(let words):            say(words, .error)        case .cancelled, .noPresence:            break        }    }    /// The typo check, once a whole code is typed.    func check() async {        let letters = typed.filter { $0.isLetter || $0.isNumber }        guard letters.count >= 24 else {            problem = nil            return        }        let sent = typed        guard let answer = try? await core.callJSON(CottonMethod.recoveryCheck, RecoveryCheckRequest(code: sent)), sent == typed else { return }        problem = answer.flag("ok") ? nil : answer.text("line")    }    /// *Open* under I have a code: no prompt, this phone holds no vault yet.    func open() async {        guard !busy, problem == nil else { return }        busy = true        defer { busy = false }        let code = typed        let name = name()        switch await vault.handing(CottonMethod.recoveryOpen, through: core, quiet: true, { key in            RecoveryOpenRequest(code: code, privateKey: key, name: name)        }) {        case .answered(let answer):            entering = false            typed = ""            if let words = answer.text("line") { say(words, .success) }            await opened?()        case .refused(let words):            problem = words        case .cancelled, .noPresence:            break        }    }    // ── a phone holding the vault ────────────────────────────────────────    /// Once the key is held: the iCloud copy kept, the code offered once, and    /// the helper's asks looked for. `bannerUp` holds the offer back while    /// another line stands.    func whileHeld(database: String, bannerUp: Bool) async {        heldDatabase = database        if status == nil || (!platformKept && !platformTried) { await refresh() }        guard let status = self.status, status.flag("holdsVault") else { return }        if !platformKept, !platformTried {            let apple = status["apple"]            // Kept when the object holds a current `apple` wrap AND this            // phone's Keychain holds its key; else made (again), which            // retires the old wrap and replaces the synced item.            let current = apple?.text("made") != nil && apple?.maybeFlag("current") != false            if current, platform.read(database: database) != nil {                platformKept = true                copyKept = "back"            } else {                platformTried = true                await keepICloudCopy(database: database)            }        }        // The one reminder (GETTING-IN.md): a week after Not now, if the code was never saved; never again.        if !reminding, shown == nil, !bannerUp, RecoverySaved.due(), line("reminder") != nil {            RecoverySaved.reminded()            reminding = true        }        if status.flag("offer"), !offerDone, !bannerUp, shown == nil {            offerDone = true            switch await vault.handing(CottonMethod.recoveryMake, through: core, quiet: true, { key in RecoveryKeyRequest(privateKey: key) }) {            case .answered(let answer):                if let code = answer.text("code") { shown = ShownCode(code: code, offered: true) }            default:                break            }        }        watchHelpAsks()    }    /// The database this phone holds the vault of, as the last round saw it.    @ObservationIgnored private var heldDatabase: String?    /// The phone now stands on another database (the account deleted or signed out, another number signed in):    /// what was offered or read for the last one goes. The offered code stood over Days after its account was    /// deleted (launch-ios walk, 22 Nov 2026).    func standsOn(database: String?) {        guard let held = heldDatabase, held != database else { return }        heldDatabase = nil        status = nil        shown = nil        helpAsks = []        offerDone = false        aloneSaid = false        platformKept = false        platformTried = false        platformTries = 0        copyKept = nil    }    /// A platform key another screen made (Cotton Vault's Security ›    /// Recovery › Turn on, `recovery.makePlatform`), kept in iCloud Keychain    /// exactly as the offer above keeps it. False when it was not kept.    func keepPlatform(_ key: String) async -> Bool {        guard let database = heldDatabase, platform.write(key, database: database) else {            Log.write("recovery: the iCloud Keychain copy was not kept")            return false        }        platformKept = true        copyKept = "back"        await refresh()        return true    }    private func keepICloudCopy(database: String) async {        let store = Self.store        switch await vault.handing(CottonMethod.recoveryMakePlatform, through: core, quiet: true, { key in            PlatformMakeRequest(store: store, privateKey: key)        }) {        case .answered(let answer):            if let key = answer.text("key"), platform.write(key, database: database) {                platformKept = true                copyKept = "back"            } else {                copyKept = "none"                Log.write("recovery: the iCloud Keychain copy was not kept")            }            // Read again either way: the offer's line follows what the Keychain did.            await refresh()        default:            Log.write("recovery: no platform key was made")        }    }    /// *Copy*: on this phone only, gone from the pasteboard in two minutes.    func copy() {        guard let shown = self.shown else { return }        #if os(iOS)            UIPasteboard.general.setItems(                // Marked concealed (AUDIT E): no clipboard keeper, Cotton's own Clips included, keeps the code.                [[UTType.plainText.identifier: shown.code, PasteboardMark.concealed: Data()]],                options: [.localOnly: true, .expirationDate: Date().addingTimeInterval(Self.copiedSeconds)])        #endif        if let words = line("copied") { say(words, .success) }    }    /// *Save to Files*: the code in a small text file the person places (GETTING-IN.md); said once it is kept.    func saveToFiles() { if shown != nil { exporting = true } }    /// The file the export writes: `fileText` with the code in it.    var file: RecoveryFile? {        guard let shown, let text = line("fileText") else { return nil }        return RecoveryFile(text: text.replacingOccurrences(of: "{code}", with: shown.code))    }    /// The export's answer: kept, the code counts as saved and no reminder comes.    func savedToFiles(_ kept: Bool) {        exporting = false        guard kept else { return }        RecoverySaved.saved()        if let words = line("saved") { say(words, .success) }    }    /// The reminder's Not now: gone, never again.    func notNowReminder() { reminding = false }    /// The reminder's Show my recovery code: behind the lock, then offered as at the start.    func showFromReminder() async {        reminding = false        await show()    }    /// *Not now* on the offer, *Done* on a code shown again. Not now on a    /// phone that is the person's only way in says so, once (R7).    func dismiss() async {        let offered = shown?.offered == true        if offered { RecoverySaved.offered() }        shown = nil        if offered, status?.flag("alone") == true, !aloneSaid, let words = line("alone") {            aloneSaid = true            say(words, .notice)        }        await refresh()    }    /// *Show my recovery code*, behind the phone's lock.    func show() async {        await withKey(CottonMethod.recoveryShow, said: nil)    }    /// *Make a new code*, behind the phone's lock; the old one opens nothing.    func makeNew() async {        await withKey(CottonMethod.recoveryMake, said: line("madeNew"))    }    private func withKey(_ method: String, said: String?) async {        guard !busy else { return }        busy = true        defer { busy = false }        switch await vault.handing(method, through: core, { key in RecoveryKeyRequest(privateKey: key) }) {        case .answered(let answer):            if let code = answer.text("code") { shown = ShownCode(code: code, offered: false) }            if let said { say(said, .success) }            await refresh()        case .refused(let words):            say(words, .error)        case .noPresence:            say(ShellLines.line("unlock", "no_presence"), .error)        case .cancelled:            break        }    }    /// *Ask someone to help*: the person chosen from Your people, behind the    /// phone's lock.    func trust(number: String, name: String?) async {        guard !busy else { return }        busy = true        defer { busy = false }        switch await vault.handing(CottonMethod.recoveryTrust, through: core, { key in            RecoveryTrustRequest(number: number, name: name, privateKey: key)        }) {        case .answered(let answer):            if let words = answer.text("line") { say(words, .success) }            await refresh()        case .refused(let words):            say(words, .error)        case .noPresence:            say(ShellLines.line("unlock", "no_presence"), .error)        case .cancelled:            break        }    }    /// A helper's asks, read now and every 20 seconds while this phone holds    /// the vault.    private func watchHelpAsks() {        guard helpLoop == nil else { return }        helpLoop = Task { @MainActor [weak self] in            while !Task.isCancelled {                guard let self else { return }                await self.readHelpAsks()                try? await Task.sleep(for: .seconds(Self.helpSeconds))            }        }    }    func readHelpAsks() async {        guard let answer = try? await core.callJSON(CottonMethod.recoveryHelpAsks) else { return }        helpAsks = answer.list("asks").compactMap(HelpAsk.init)    }    /// *Approve* on a helper's card, behind the phone's lock.    func approve(_ ask: HelpAsk) async {        guard !busy else { return }        busy = true        defer { busy = false }        let presence = presence        let allowed = await Task.detached(priority: .userInitiated) { () -> Bool in            do { try presence(); return true } catch { return false }        }.value        guard allowed else { return }        do {            _ = try await core.callJSON(CottonMethod.recoveryHelpApprove, HelpAskRequest(id: ask.id))            if let words = ask.approved { say(words, .success) }        } catch let error as CottonCallError {            say(error.message, .error)        } catch {            say(ShellLines.line("passwords", "vault.this_phone_could_not"), .error)        }        await readHelpAsks()    }    /// *Not now* on a helper's card.    func decline(_ ask: HelpAsk) async {        _ = try? await core.callJSON(CottonMethod.recoveryHelpDecline, HelpAskRequest(id: ask.id))        await readHelpAsks()    }}/// The recovery cards that stand over every app: the code (offered or shown/// again) and a helper's ask.struct RecoveryCards: View {    @Bindable var recovery: RecoveryKeys    var body: some View {        cards            .fileExporter(isPresented: $recovery.exporting, document: recovery.file, contentType: .plainText,                          defaultFilename: recovery.line("fileName") ?? "") { result in                recovery.savedToFiles((try? result.get()) != nil)            }    }    private var cards: some View {        VStack(spacing: 0) {            if let shown = recovery.shown {                card(seed: "recovery-code") {                    // A copy the Keychain would not keep: the core's reason is the offer's line.                    if shown.offered, let offer = recovery.status?.text("away") ?? recovery.line("offer") {                        Text(offer)                            .paperTitle(15)                            .fixedSize(horizontal: false, vertical: true)                            .accessibilityIdentifier("recovery-offer")                    }                    Text(shown.code)                        .font(.system(size: 19, weight: .semibold, design: .monospaced))                        .textSelection(.enabled)                        .fixedSize(horizontal: false, vertical: true)                        .accessibilityIdentifier("recovery-code")                    HStack(spacing: 24) {                        if let saveFiles = recovery.line("saveFiles"), recovery.file != nil {                            Button(saveFiles) { recovery.saveToFiles() }                                .accessibilityIdentifier("recovery-save-files")                        }                        if let copy = recovery.line("copy") {                            Button(copy) { recovery.copy() }                                .accessibilityIdentifier("recovery-copy")                        }                        if let close = recovery.line(shown.offered ? "notNow" : "done") {                            Button(close) { Task { await recovery.dismiss() } }                                .accessibilityIdentifier("recovery-dismiss")                        }                    }                }            }            if recovery.reminding, recovery.shown == nil, let reminder = recovery.line("reminder") {                card(seed: "recovery-reminder") {                    Text(reminder)                        .paperTitle(15)                        .fixedSize(horizontal: false, vertical: true)                        .accessibilityIdentifier("recovery-reminder-line")                    HStack(spacing: 24) {                        if let show = recovery.line("show") {                            Button(show) { Task { await recovery.showFromReminder() } }                                .accessibilityIdentifier("recovery-reminder-show")                        }                        if let later = recovery.line("notNow") {                            Button(later) { recovery.notNowReminder() }                                .accessibilityIdentifier("recovery-reminder-later")                        }                    }                }            }            ForEach(recovery.helpAsks) { ask in                card(seed: "help-\(ask.id)") {                    Text(ask.line)                        .paperTitle(15)                        .fixedSize(horizontal: false, vertical: true)                        .accessibilityIdentifier("help-ask-line")                    HStack(spacing: 24) {                        Button(ask.approve) { Task { await recovery.approve(ask) } }                            .disabled(recovery.busy)                            .accessibilityIdentifier("help-ask-approve")                        Button(ask.decline) { Task { await recovery.decline(ask) } }                            .disabled(recovery.busy)                            .accessibilityIdentifier("help-ask-decline")                    }                }            }        }    }    private func card<Content: View>(seed: String, @ViewBuilder _ content: () -> Content) -> some View {        Paper(dye: .peach, edge: .torn, seed: seed, tilt: false, inset: 16) {            VStack(alignment: .leading, spacing: 10) { content() }        }        .padding(.horizontal, ChromeKnobs.chromeSettingsMargin)        .padding(.top, 6)        .padding(.bottom, 8)    }}/// *I have a code*: the code typed, its typo said as it is typed, and Open.struct RecoveryCodeEntry: View {    @Bindable var recovery: RecoveryKeys    var body: some View {        Paper(dye: .peach, edge: .torn, seed: "recovery-entry", tilt: false, inset: 20) {            VStack(alignment: .leading, spacing: 14) {                if let enter = recovery.line("enter") {                    Text(enter)                        .paperTitle(17)                        .fixedSize(horizontal: false, vertical: true)                }                TextField(recovery.line("hint") ?? "", text: $recovery.typed)                    .font(.system(size: 17, design: .monospaced))                    .codeEntry()                    .accessibilityIdentifier("recovery-entry-field")                if let problem = recovery.problem {                    Text(problem)                        .paperMeta(14)                        .fixedSize(horizontal: false, vertical: true)                        .accessibilityIdentifier("recovery-entry-problem")                }                if let open = recovery.line("open") {                    Button(open) { Task { await recovery.open() } }                        .disabled(recovery.busy || recovery.problem != nil || recovery.typed.filter { $0.isLetter || $0.isNumber }.count < 24)                        .accessibilityIdentifier("recovery-entry-open")                }            }        }        .padding(16)    }}private extension View {    /// Capitals and no autocorrection: a recovery code is not a word.    @ViewBuilder func codeEntry() -> some View {        #if os(iOS)            textInputAutocapitalization(.characters).autocorrectionDisabled()        #else            autocorrectionDisabled()        #endif    }}/// The recovery code as a small text file, for Save to Files.struct RecoveryFile: FileDocument {    static var readableContentTypes: [UTType] { [.plainText] }    let text: String    init(text: String) { self.text = text }    init(configuration: ReadConfiguration) throws {        text = configuration.file.regularFileContents.flatMap { String(data: $0, encoding: .utf8) } ?? ""    }    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {        FileWrapper(regularFileWithContents: Data(text.utf8))    }}/// When the code was offered and saved on this phone, and whether its one reminder came (GETTING-IN.md: one/// reminder a week after Not now, if never saved). Android's `RecoverySaved` keeps the same three.enum RecoverySaved {    static let week: TimeInterval = 7 * 24 * 3600    private static var store: UserDefaults { .standard }    private static let savedKey = "cotton-recovery-saved-at", offeredKey = "cotton-recovery-offered-at", remindedKey = "cotton-recovery-reminded"    static func saved(now: Date = Date()) { store.set(now.timeIntervalSince1970, forKey: savedKey) }    static func offered(now: Date = Date()) { if store.double(forKey: offeredKey) == 0 { store.set(now.timeIntervalSince1970, forKey: offeredKey) } }    static func reminded() { store.set(true, forKey: remindedKey) }    static func due(now: Date = Date()) -> Bool {        remindAt(offeredAt: store.double(forKey: offeredKey), savedAt: store.double(forKey: savedKey), reminded: store.bool(forKey: remindedKey), now: now.timeIntervalSince1970)    }    static func remindAt(offeredAt: TimeInterval, savedAt: TimeInterval, reminded: Bool, now: TimeInterval) -> Bool {        offeredAt > 0 && savedAt == 0 && !reminded && now - offeredAt >= week    }}