// 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.importCottonKitimportSwiftUIimportUniformTypeIdentifiers#if os(iOS)import UIKitimportUniformTypeIdentifiers#endif/// A code drawn on the card: just made by the offer, or shown again.structShownCode: 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.structHelpAsk: Equatable, Sendable, Identifiable {let id: Stringlet line: Stringlet approve: Stringlet decline: Stringlet approved: String?init?(_ value: JSONValue) {guardlet id = value.text("id"), let line = value.text("line"), let approve = value.text("approve"),let decline = value.text("decline") else { returnnil }self.id = idself.line = lineself.approve = approveself.decline = decline approved = value.text("approved") }}structRecoveryKeyRequest: Encodable, Sendable { let privateKey: String }structRecoveryCheckRequest: Encodable, Sendable { let code: String }structRecoveryOpenRequest: Encodable, Sendable {let code: Stringlet privateKey: Stringlet 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.structRecoveryStatusRequest: Encodable, Sendable { let copy: String? }structPlatformMakeRequest: Encodable, Sendable {let store: Stringlet privateKey: String}structPlatformOpenRequest: Encodable, Sendable {let store: Stringlet key: Stringlet privateKey: Stringlet name: String}structRecoveryTrustRequest: Encodable, Sendable {let number: Stringlet name: String?let privateKey: String}structRecoveryHelpRequest: Encodable, Sendable {let privateKey: Stringlet name: String}structHelpAskRequest: Encodable, Sendable { let id: String }@MainActor@ObservablefinalclassRecoveryKeys {/// `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 = falseprivate(set) var helpAsks: [HelpAsk] = []/// The code typed under I have a code, and what the typo check said.var entering = falsevar 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 privatelet core: any CottonCalling/// The core these keys call, for a screen drawn beside them (the trusted recovery screens).var calling: any CottonCalling { core } @ObservationIgnored privatelet vault: VaultAccess @ObservationIgnored privatelet platform: any PlatformKeyKeeping @ObservationIgnored privatelet name: @Sendable () -> String @ObservationIgnored privatelet presence: @Sendable () throws -> Void @ObservationIgnored privatelet say: @MainActor (String, CottonToast.Tone) -> Void/// Read the sealed state again once something opened this device. @ObservationIgnored var opened: (@MainActor () async -> Void)? @ObservationIgnored privatevar offerDone = false @ObservationIgnored privatevar aloneSaid = false @ObservationIgnored privatevar platformKept = false/// What the Keychain did with the copy this launch (`RecoveryStatusRequest`). @ObservationIgnored privatevar 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 privatevar platformTried = false @ObservationIgnored privatevar platformTries = 0 @ObservationIgnored privatevar helpLoop: Task<Void, Never>?/// The store iCloud Keychain carries (`recovery.*` `store`).staticlet store = "apple"/// How many times a new phone tries the iCloud copy before it stops.staticlet maxPlatformTries = 6/// How often a phone holding the vault looks for a helper's ask.staticlet helpSeconds: Double = 20/// How long a copied code stays on the pasteboard.staticlet copiedSeconds: Double = 120init( core: any CottonCalling, vault: VaultAccess, platform: any PlatformKeyKeeping = ICloudPlatformKeys(), name: @escaping @Sendable () -> String = { ThisPhone.deviceName() }, presence: @escaping @Sendable () throws -> Void = { tryVaultPresence.ask() }, say: @escaping @MainActor (String, CottonToast.Tone) -> Void ) {self.core = coreself.vault = vaultself.platform = platformself.name = nameself.presence = presenceself.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 { returnfalse } platformTries += 1let name = name()let store = Self.storeswitchawait vault.handing(CottonMethod.recoveryOpenPlatform, through: core, quiet: true, { privateKey inPlatformOpenRequest(store: store, key: key, privateKey: privateKey, name: name) }) {case .answered(let answer): platformTries = Self.maxPlatformTriesiflet words = answer.text("line") { say(words, .success) }return answer.flag("opened")case .cancelled, .noPresence, .refused:returnfalse } }/// 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 { returnfalse }let name = name()switchawait vault.handing(CottonMethod.recoveryHelped, through: core, quiet: true, { key inRecoveryHelpRequest(privateKey: key, name: name) }) {case .answered(let answer) where answer.flag("opened"): asked = falseiflet words = answer.text("line") { say(words, .success) }returntruedefault:returnfalse } }/// *Ask <name> to help*.func askHelp() async {guard !busy else { return } busy = truedefer { busy = false }let name = name()switchawait vault.handing(CottonMethod.recoveryAskHelp, through: core, quiet: true, { key inRecoveryHelpRequest(privateKey: key, name: name) }) {case .answered(let answer): asked = trueiflet 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 >= 24else { problem = nilreturn }let sent = typedguardlet 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.funcopen() async {guard !busy, problem == nilelse { return } busy = truedefer { busy = false }let code = typedlet name = name()switchawait vault.handing(CottonMethod.recoveryOpen, through: core, quiet: true, { key inRecoveryOpenRequest(code: code, privateKey: key, name: name) }) {case .answered(let answer): entering = false typed = ""iflet words = answer.text("line") { say(words, .success) }await opened?()case .refused(let words): problem = wordscase .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 = databaseif status == nil || (!platformKept && !platformTried) { await refresh() }guardlet 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") != falseif current, platform.read(database: database) != nil { platformKept = true copyKept = "back" } else { platformTried = trueawait 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 = trueswitchawait vault.handing(CottonMethod.recoveryMake, through: core, quiet: true, { key inRecoveryKeyRequest(privateKey: key) }) {case .answered(let answer):iflet 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 privatevar 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?) {guardlet 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 {guardlet database = heldDatabase, platform.write(key, database: database) else {Log.write("recovery: the iCloud Keychain copy was not kept")returnfalse } platformKept = true copyKept = "back"await refresh()returntrue }privatefunc keepICloudCopy(database: String) async {let store = Self.storeswitchawait vault.handing(CottonMethod.recoveryMakePlatform, through: core, quiet: true, { key inPlatformMakeRequest(store: store, privateKey: key) }) {case .answered(let answer):iflet 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() {guardlet 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)]) #endififlet 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? {guardlet shown, let text = line("fileText") else { returnnil }returnRecoveryFile(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 = falseguard kept else { return }RecoverySaved.saved()iflet 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 = falseawait 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 == trueif offered { RecoverySaved.offered() } shown = nilif 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")) }privatefunc withKey(_ method: String, said: String?) async {guard !busy else { return } busy = truedefer { busy = false }switchawait vault.handing(method, through: core, { key inRecoveryKeyRequest(privateKey: key) }) {case .answered(let answer):iflet code = answer.text("code") { shown = ShownCode(code: code, offered: false) }iflet 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 = truedefer { busy = false }switchawait vault.handing(CottonMethod.recoveryTrust, through: core, { key inRecoveryTrustRequest(number: number, name: name, privateKey: key) }) {case .answered(let answer):iflet 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.privatefunc watchHelpAsks() {guard helpLoop == nilelse { return } helpLoop = Task { @MainActor [weakself] inwhile !Task.isCancelled {guardletselfelse { return }awaitself.readHelpAsks()try? awaitTask.sleep(for: .seconds(Self.helpSeconds)) } } }func readHelpAsks() async {guardlet 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 = truedefer { busy = false }let presence = presencelet allowed = awaitTask.detached(priority: .userInitiated) { () -> Boolindo { try presence(); returntrue } catch { returnfalse } }.valueguard allowed else { return }do { _ = tryawait core.callJSON(CottonMethod.recoveryHelpApprove, HelpAskRequest(id: ask.id))iflet words = ask.approved { say(words, .success) } } catchlet error asCottonCallError { 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.structRecoveryCards: View { @Bindable var recovery: RecoveryKeysvar body: someView { cards .fileExporter(isPresented: $recovery.exporting, document: recovery.file, contentType: .plainText, defaultFilename: recovery.line("fileName") ?? "") { result in recovery.savedToFiles((try? result.get()) != nil) } }privatevar cards: someView { VStack(spacing: 0) {iflet 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) {iflet saveFiles = recovery.line("saveFiles"), recovery.file != nil {Button(saveFiles) { recovery.saveToFiles() } .accessibilityIdentifier("recovery-save-files") }iflet copy = recovery.line("copy") {Button(copy) { recovery.copy() } .accessibilityIdentifier("recovery-copy") }iflet 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) {iflet show = recovery.line("show") {Button(show) { Task { await recovery.showFromReminder() } } .accessibilityIdentifier("recovery-reminder-show") }iflet 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") } } } } }privatefunc card<Content: View>(seed: String, @ViewBuilder _ content: () -> Content) -> someView {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.structRecoveryCodeEntry: View { @Bindable var recovery: RecoveryKeysvar body: someView {Paper(dye: .peach, edge: .torn, seed: "recovery-entry", tilt: false, inset: 20) { VStack(alignment: .leading, spacing: 14) {iflet 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")iflet problem = recovery.problem {Text(problem) .paperMeta(14) .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("recovery-entry-problem") }ifletopen = 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) }}privateextensionView {/// Capitals and no autocorrection: a recovery code is not a word. @ViewBuilder func codeEntry() -> someView { #if os(iOS) textInputAutocapitalization(.characters).autocorrectionDisabled() #else autocorrectionDisabled() #endif }}/// The recovery code as a small text file, for Save to Files.structRecoveryFile: FileDocument {staticvar readableContentTypes: [UTType] { [.plainText] }let text: Stringinit(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.enumRecoverySaved {staticlet week: TimeInterval = 7 * 24 * 3600privatestaticvar store: UserDefaults { .standard }privatestaticlet savedKey = "cotton-recovery-saved-at", offeredKey = "cotton-recovery-offered-at", remindedKey = "cotton-recovery-reminded"staticfunc saved(now: Date = Date()) { store.set(now.timeIntervalSince1970, forKey: savedKey) }staticfunc offered(now: Date = Date()) { if store.double(forKey: offeredKey) == 0 { store.set(now.timeIntervalSince1970, forKey: offeredKey) } }staticfunc reminded() { store.set(true, forKey: remindedKey) }staticfunc due(now: Date = Date()) -> Bool { remindAt(offeredAt: store.double(forKey: offeredKey), savedAt: store.double(forKey: savedKey), reminded: store.bool(forKey: remindedKey), now: now.timeIntervalSince1970) }staticfunc remindAt(offeredAt: TimeInterval, savedAt: TimeInterval, reminded: Bool, now: TimeInterval) -> Bool { offeredAt > 0 && savedAt == 0 && !reminded && now - offeredAt >= week }}