// THE DATA KEY OF SEALED TABLES, KEPT (12 Nov 2026),// AND THE VAULT FOUNDED, APPROVED AND RE-OPENED WITH NO WALL// (16 Nov 2026; e2e rulings R7b, R8, R9).//// Sealed tables are read only with the database's data key. The core holds it// in memory and decides when this app needs it (`seal.status`: `needsKey`,// `founds`, and its words); this file moves it between the core and the// Keychain (`CottonKit/DataKey.swift`) and draws the core's lines. The order// is Android's (`core/SealedKeys.kt`), and nothing in it prompts://// 1. A key the Keychain kept is handed back (`seal.useKey`). Every Cotton// app on the phone keeps it in the one shared group (R9), so an app// installed later opens here, with no step.// 2. **Founding with no question (R8).** While the key is needed and the// core says this device founds (`founds`: signed in, the vault rows// pulled, no other device holds a wrap), the vault is opened with the// key read quietly (`VaultAccess.unlockQuietly`): the core founds the// vault, then takes the data key. A few tries, a pass between each.// 3. A key the core holds that the Keychain lacks is kept (`seal.heldKey`).// 4. `vault.approval`: on a device holding a wrap, another device waiting to// be let in (`waiting`) stands as a card in EVERY app (R7b): who asks,// `how` it comes in, and Refuse behind the core's confirm. THERE IS NO// APPROVE: no device comes into the vault on a tap// and a fingerprint read by eye. On a device waiting itself (`mine`), its// line stands in place of the key's, with `ask` ("Approve on another// device"): behind Face ID / the passcode it makes an ordinary sign-in// ask for this phone's own number with its vault key (`personal.ask`),// shows that ask's code large, to be typed on the holder's sign-in card// (`Boot/SignInAsks.swift`), and polls it (`personal.askPoll`). The// credential its approval brings is dropped, never kept: this phone is// signed in already. The pass runs every `pollSeconds`; the moment// `mine` is gone the vault is opened again, quietly.// 5. Recovery (`Boot/RecoveryKeys.swift`): a new iPhone tries its iCloud// Keychain copy before anything else (R7a); a waiting device offers// I have a code and Ask <name> to help beside its line (R7c, R7d); a// device holding the key keeps the iCloud copy, offers the code once,// and stands a helper's ask in every app.//// Read at launch, at every foreground, after every pass and every// `pollSeconds` while this device waits. **A launch never prompts**: Face ID// is drawn only by the person's tap (the banner's act, the ask).importCottonKitimportSwiftUI/// Another device asking to be let in, as `vault.approval` says it: who, and/// how it comes in. No Approve: it comes in by the code its own ask shows.structApprovalAsk: Equatable, Sendable {let deviceId: Stringlet line: Stringlet how: String?let refuse: Stringlet confirm: String?init?(_ value: JSONValue?) {guardlet value, let deviceId = value.text("deviceId"), let line = value.text("line"),let refuse = value.text("refuse") else { returnnil }self.deviceId = deviceIdself.line = line how = value.text("how")self.refuse = refuse confirm = value.text("confirm") }}/// The number this phone is signed in with, at the open host it signed in at:/// what its own ask for the vault is made for.structSignedInAs: Equatable, Sendable {let server: Stringlet phone: String/// The Keychain's session for this flavour's personal object (blocks: off the main thread).staticfunc held(core: any CottonCalling) -> SignedInAs? {guardlet address = FlavourManifest.current?.personalObject,let phone = BusinessClient(core: core, address: address).session()?.phone, !phone.isEmpty else { returnnil }returnSignedInAs(server: address.server, phone: phone) }}structRefuseDeviceRequest: Encodable, Sendable {let deviceId: String}@MainActor@ObservablefinalclassSealedKeys {/// The core's line while the key is needed (or this device's wait, with/// its code), nil while it is held.private(set) var line: String?private(set) var act: String?/// Another device waiting to be let in, by the code its own ask shows.private(set) var asking: ApprovalAsk?/// This device waits for another to approve it.private(set) var waiting = false/// While waiting: the button that makes this phone's own ask (`mine.ask`).private(set) var mineAsk: String?/// That ask's card (`personal.ask`) and its last poll (`personal.askPoll`).private(set) var vaultAsk: JSONValue?private(set) var vaultPolled: JSONValue?private(set) var busy = false/// GETTING-IN.md: the page while this device waits, by itself (`gettingIn.screen`); nil once it no longer waits.private(set) var page: JSONValue?/// Do this later: the page closed, the slim line with Bring them here stands instead.var later = false/// No other device? on the page: the recovery code and the trusted person.var noOther = false/// The recovery code, the iCloud Keychain copy and the trusted person.let recovery: RecoveryKeys @ObservationIgnored privatelet core: any CottonCalling @ObservationIgnored privatelet vault: VaultAccess @ObservationIgnored privatelet keeper: any DataKeyKeeping @ObservationIgnored privatelet name: @Sendable () -> String @ObservationIgnored privatelet pause: @Sendable (Double) async -> Void @ObservationIgnored privatelet say: @MainActor (String, CottonToast.Tone) -> Void/// A quiet open is under way: a second read does not start another. @ObservationIgnored privatevar opening = false/// The key published once on `joins`; a new database (another sign-in) asks again. @ObservationIgnored privatevar joinAsked = false @ObservationIgnored privatevar joinedDatabase: String? @ObservationIgnored privatevar poll: Task<Void, Never>? @ObservationIgnored privatevar askPolling: Task<Void, Never>? @ObservationIgnored privatevar paging: Task<Void, Never>? @ObservationIgnored privatevar askAgain = false @ObservationIgnored privatelet account: @Sendable () -> SignedInAs?/// How many quiet tries a founding gets, and the pause between them.staticlet foundTries = 4staticlet foundPause = 1.5init( core: any CottonCalling, vault: VaultAccess = VaultAccess(), keeper: any DataKeyKeeping = DataKeychain(), platform: any PlatformKeyKeeping = ICloudPlatformKeys(), name: @escaping @Sendable () -> String = { ThisPhone.deviceName() }, account: (@Sendable () -> SignedInAs?)? = nil, pause: @escaping @Sendable (Double) async -> Void = { try? awaitTask.sleep(for: .seconds($0)) }, say: @escaping @MainActor (String, CottonToast.Tone) -> Void ) {self.core = coreself.account = account ?? { [core] inSignedInAs.held(core: core) }self.vault = vaultself.keeper = keeperself.name = nameself.pause = pauseself.say = say recovery = RecoveryKeys(core: core, vault: vault, platform: platform, name: name, say: say) recovery.opened = { [weakself] inawaitself?.read() } #if COTTON_DEV asking = seeded #endif } #if COTTON_DEV/// DEVELOPER TOOL: an invented device asking to be let in, standing in/// every app from the first frame, for the shell card's own tests/// (launched with `-shell-card-seed YES`). It reaches no server: its/// Refuse only takes the card down and says so (`refuse`). @ObservationIgnored privatevar seeded: ApprovalAsk? = SealedKeys.seededAsk()staticfunc seededAsk(_ arguments: [String] = ProcessInfo.processInfo.arguments) -> ApprovalAsk? {guardlet at = arguments.firstIndex(of: "-shell-card-seed"), at + 1 < arguments.count, arguments[at + 1] == "YES"else { returnnil }let name = ShellLines.line("unlock", "approval.seed_name")returnApprovalAsk(.object(["deviceId": .string("dev-seed-walk-mac"),"line": .string(ShellLines.line("unlock", "approval.asks", ["name": name])),"how": .string(ShellLines.line("unlock", "approval.how", ["name": name])),"refuse": .string(ShellLines.line("unlock", "approval.refuse")),"confirm": .string(ShellLines.line("unlock", "approval.confirm")), ])) } #endif/// Hand back, found, keep, and read what the core says.func read() async {guardvar status = await status() else { return }let database = status.text("database") recovery.standsOn(database: database)if database != joinedDatabase { joinedDatabase = database; joinAsked = false }iflet database, !status.flag("keyHeld"), let kept = keeper.read(database: database) {do { _ = tryawait core.callJSON(CottonMethod.sealUseKey, ["key": kept]) status = awaitself.status() ?? status } catch {Log.write("seal: the kept data key was not taken — \(error)") } }// A phone that has not signed in, on the database it started (the// core's `makes`): nothing is anywhere else yet, so its key is made// with no question and kept below as a first sign-in's key is.if status.flag("needsKey"), status.flag("makes") {do { _ = tryawait core.callJSON(CottonMethod.sealMakeKey) status = awaitself.status() ?? status } catch {Log.write("seal: the key of this phone's own database was not made — \(error)") } }// A new iPhone on the same Apple account opens with its iCloud copy.iflet database, status.flag("needsKey"), !status.flag("founds"), !opening,await recovery.openFromICloud(database: database) { status = awaitself.status() ?? status }if status.flag("needsKey"), status.flag("founds"), !opening {await openQuietly() status = awaitself.status() ?? status }// A new phone on an account another device holds (the core's// `joins`): its key is published once, through `vault.unlock` with// this phone's name, so the holder can let it in and the getting-in// page asks (GETTING IN, 26 Nov 2026; Android's SealedKeys does the// same). Without it the phone sat on "Loading your data…" for ever.if status.flag("needsKey"), status.flag("joins"), !waiting, !joinAsked, !opening { joinAsked = true _ = await vault.unlockQuietly(through: core, name: name()) status = awaitself.status() ?? status }iflet database, status.flag("keyHeld"), keeper.read(database: database) == nil {// Keeping it is for the next launch; the line follows the// core's status whether or not this succeeds.do {let held = tryawait core.callJSON(CottonMethod.sealHeldKey)iflet key = held.text("key"), !keeper.write(key, database: database) {Log.write("seal: the data key was not kept in the Keychain") } } catch {Log.write("seal: the held data key could not be read — \(error)") } }let approval = try? await core.callJSON(CottonMethod.vaultApproval)let mine = approval?["mine"].flatMap { $0.text("deviceId") == nil ? nil : $0 }// Approved while this read was away: open again, with nobody asked.if waiting, mine == nil, status.flag("needsKey"), !opening {await openQuietly() status = awaitself.status() ?? status } waiting = mine != nil && status.flag("needsKey") mineAsk = waiting ? mine?.text("ask") : nilif !waiting { stopAsking() }if waiting { watchPage() } else { stopPage() } asking = ApprovalAsk(approval?["waiting"]) #if COTTON_DEVif asking == nil { asking = seeded } #endiflet said = status["said"]if waiting, let mine {// "Open Cotton on a device…" said in this app's name (Words, Days, Story). line = mine.text("line").map { ShellLines.said($0, as: ShellLines.speaker) } act = nil } else { line = status.flag("needsKey") ? said?.text("line") : nil act = status.flag("needsKey") ? said?.text("act") : nil } keepPolling(waiting ? approval?.decimal("pollSeconds") : nil)if waiting {// The slip's recovery words, and a helper's answer once asked.ifawait recovery.whileWaiting() { await read() } } elseiflet database, status.flag("keyHeld") {await recovery.whileHeld(database: database, bannerUp: line != nil || asking != nil) } }privatefunc status() async -> JSONValue? {do {returntryawait core.callJSON(CottonMethod.sealStatus) } catch {Log.write("seal: the data key's state could not be read — \(error)")returnnil } }/// The vault opened with the key read quietly: founding at a first/// sign-in, or the re-open once this device was approved. A pass between/// tries; a device another must approve stops at once and waits.privatefunc openQuietly() async { opening = truedefer { opening = false }for attempt in0..<Self.foundTries {switchawait vault.unlockQuietly(through: core, name: name()) {case .open:returncase .waitingForMac:let approval = try? await core.callJSON(CottonMethod.vaultApproval)if approval?["mine"]?.text("deviceId") != nil { waiting = truereturn }case .cancelled, .noPresence, .keyMismatch, .refused:return }if attempt + 1 < Self.foundTries { _ = try? await core.callJSON(CottonMethod.syncNow)await pause(Self.foundPause) } } }/// The person's tap: open the vault, which takes the data key, then keep it.func unlock() async {guard !busy else { return } busy = truedefer { busy = false }switchawait vault.unlock(through: core) {case .open:await read()case .waitingForMac(let words), .keyMismatch(let words), .refused(let words): say(words, .notice)await read()case .noPresence: say(ShellLines.line("unlock", "no_presence"), .error)case .cancelled:break } }/// Whether the slim line's act stands: waiting, with the page closed by Do this later.var offersAsk: Bool { waiting && mineAsk != nil && later }/// Bring them here: the page again.func openPage() { later = false watchPage() }/// Ask again (an ended request): a fresh one that replaces it, at the next look.func again() { askAgain = true watchPage() }/// Sign out from the page: the sign-in this flavour keeps is dropped; Sign in shows again.func signOut() async {guardlet address = FlavourManifest.current?.personalObject else { return }let core = core stopPage()awaitTask.detached { awaitBusinessClient(core: core, address: address).signOut() }.value _ = try? await core.callJSON(CottonMethod.syncNow)await read() }/// `gettingIn.screen` every `pollSeconds` while this device waits: the core asks by itself, and says each state.privatefunc watchPage() {guard paging == nilelse { return } paging = Task { @MainActor [weakself] inwhile !Task.isCancelled {guardletself, self.waiting else { return }let account = self.accountguardlet signedIn = awaitTask.detached(operation: { account() }).value else {try? awaitTask.sleep(for: .seconds(5))continue }structScreen: Encodable, Sendable { let server: String; let phone: String; let deviceName: String; let deviceKind: String? }let kind: String? = { #if os(iOS)return UIDevice.current.userInterfaceIdiom == .pad ? "ipad" : nil #elsereturnnil #endif }()let request = Screen(server: signedIn.server, phone: signedIn.phone, deviceName: self.name(), deviceKind: kind)let method = self.askAgain ? CottonMethod.gettingInAgain : CottonMethod.gettingInScreenself.askAgain = falselet answer: JSONValuedo { answer = tryawaitself.core.callJSON(method, request) } catch {Log.write("seal: the getting-in page could not be read — \(error)")try? awaitTask.sleep(for: .seconds(5))continue }guard !Task.isCancelled else { return }if answer.flag("show") == false {self.page = nilself.paging = nilawaitself.read()return }self.page = answerif answer.flag("sync") { _ = try? awaitself.core.callJSON(CottonMethod.syncNow)awaitself.read() }try? awaitTask.sleep(for: .seconds(max(2, answer.decimal("pollSeconds") ?? 3))) } } }privatefunc stopPage() { paging?.cancel() paging = nil page = nil noOther = false }/// *Approve on another device*, while this phone waits for the vault: the/// phone's lock first, then an ordinary ask for this phone's own number/// with its vault key lent for that one call (`personal.ask`), whose code/// shows here, to be typed on the device that holds the vault.func askToBeLetIn() async {guard offersAsk, !busy else { return } busy = truedefer { busy = false }let account = accountguardlet signedIn = awaitTask.detached(operation: { account() }).value else { say(ShellLines.line("board", "customer.refusal.refused"), .error)return }let key: Stringswitchawait vault.lent() {case .key(let lent): key = lentcase .not(.cancelled), .not(.answered): returncase .not(.noPresence): say(ShellLines.line("unlock", "no_presence"), .error)returncase .not(.refused(let words)): say(words, .error)return }structAsk: Encodable, Sendable { let server: String; let phone: String; let deviceName: String; let privateKey: String }do {let card = tryawait core.callJSON(CottonMethod.personalAsk,Ask(server: signedIn.server, phone: signedIn.phone, deviceName: name(), privateKey: key)) stopAsking() vaultPolled = nil vaultAsk = card pollAsk(card, server: signedIn.server) } catchlet error asCottonCallError { say(HomeCustomerRefusal.line(code: error.code, business: FlavourManifest.current?.name ?? ""), .error) } catch { say(ShellLines.line("board", "customer.refusal.refused"), .error) } }/// `personal.askPoll` at the core's pace until done; approved, a pass/// brings the wrap in and the vault opens quietly. The credential the/// claim brings back is dropped: this phone is signed in already.privatefunc pollAsk(_ card: JSONValue, server: String) {guardlet askId = card.text("askId") else { return }let every = max(1, card.decimal("pollSeconds") ?? 3)structPoll: Encodable, Sendable { let server: String; let askId: String } askPolling = Task { @MainActor [weakself] inwhile !Task.isCancelled {try? awaitTask.sleep(for: .seconds(every))guardletself, !Task.isCancelled, self.vaultAsk?.text("askId") == askId else { return }let answer: JSONValuedo { answer = tryawaitself.core.callJSON(CottonMethod.personalAskPoll, Poll(server: server, askId: askId)) } catchlet error asCottonCallError {// Refused (the ask gone, the host's limit): said, and the button stands again.self.say(HomeCustomerRefusal.line(code: error.code, business: FlavourManifest.current?.name ?? ""), .error)self.stopAsking()return } catch {// Not reached this time (no network): the next poll asks again.Log.write("seal: the vault ask's poll did not reach the host — \(error)")continue }guard !Task.isCancelled, self.vaultAsk?.text("askId") == askId else { return }// Only the words: the credential an approval carries is never held.self.vaultPolled = Self.words(of: answer)guard answer.flag("done") else { continue }self.askPolling = nilif answer.text("state") == "approved" { _ = try? awaitself.core.callJSON(CottonMethod.syncNow)awaitself.read() }return } } }/// A poll's answer without what an approval grants.privatestaticfunc words(of answer: JSONValue) -> JSONValue {guardcase .object(var fields) = answer else { return answer }for granted in ["credential", "person", "expiresIn", "databaseId"] { fields.removeValue(forKey: granted) }return .object(fields) }privatefunc stopAsking() { askPolling?.cancel() askPolling = nil vaultAsk = nil vaultPolled = nil }/// *Refuse*, once the person confirmed it.func refuse() async {guardlet asking, !busy else { return } #if COTTON_DEVif asking == seeded { seeded = nilself.asking = nil// Said through the shell's own `say`, as a real refusal's words are, so a test sees where a passing// line is drawn (`ShellToastTests`); it names the invented device and reaches no server. say(ShellLines.line("signin", "waiting.refused", ["name": ShellLines.line("unlock", "approval.seed_name")]), .notice)return } #endif busy = truedefer { busy = false }do { _ = tryawait core.callJSON(CottonMethod.vaultRefuseDevice, RefuseDeviceRequest(deviceId: asking.deviceId)) } catchlet error asCottonCallError { say(error.message, .error) } catch { say(ShellLines.line("passwords", "vault.this_phone_could_not"), .error) }await read() }/// While this device waits, a pass and a read every `pollSeconds`.privatefunc keepPolling(_ seconds: Double?) {guardlet seconds, seconds > 0else { poll?.cancel() poll = nilreturn }guard poll == nilelse { return } poll = Task { @MainActor [weakself] intry? awaitTask.sleep(for: .seconds(seconds))guardletself, !Task.isCancelled else { return }self.poll = nil _ = try? awaitself.core.callJSON(CottonMethod.syncNow)awaitself.read() } }}/// The core's line above the app while the data key is missing, with its act;/// and, in every app, another device asking to be let in.structSealedKeyBanner: View {let keys: SealedKeys @State privatevar confirming = false @Environment(\.vaultLook) privatevar vaultLookvar body: someView { #if os(iOS)iflet look = vaultLook {// Inside Cotton Vault these cards are drawn in Vault's look.VaultSealedKeyCards(keys: keys, look: look) } else { paper } #else paper #endif }/// The cards on paper, as every other app draws them.privatevar paper: someView { VStack(spacing: 0) {iflet line = keys.line {Paper(dye: .peach, edge: .torn, seed: "sealed-key", tilt: false, inset: 16) { VStack(alignment: .leading, spacing: 10) {Text(line) .paperTitle(15) .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("sealed-key-line")iflet act = keys.act {Button(act) { Task { await keys.unlock() } } .disabled(keys.busy) .accessibilityIdentifier("sealed-key-unlock") }if keys.waiting {VaultAskPart(keys: keys) HStack(spacing: 24) {iflet haveCode = keys.recovery.line("haveCode") {Button(haveCode) { keys.recovery.entering = true } .accessibilityIdentifier("recovery-have-code") }iflet helper = keys.recovery.askHelper {Button(helper) { Task { await keys.recovery.askHelp() } } .disabled(keys.recovery.busy || keys.recovery.asked) .accessibilityIdentifier("recovery-ask-helper") } } } } } .padding(.horizontal, ChromeKnobs.chromeSettingsMargin) .padding(.top, 6) .padding(.bottom, 8) .accessibilityIdentifier("sealed-key-banner") }iflet asking = keys.asking {Paper(dye: .peach, edge: .torn, seed: "approval", tilt: false, inset: 16) { VStack(alignment: .leading, spacing: 10) {Text(asking.line) .paperTitle(15) .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("approval-line")iflet how = asking.how {Text(how) .paperMeta(14) .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("approval-how") }Button(asking.refuse) { confirming = true } .disabled(keys.busy) .accessibilityIdentifier("approval-refuse") } } .padding(.horizontal, ChromeKnobs.chromeSettingsMargin) .padding(.top, 6) .padding(.bottom, 8) .accessibilityIdentifier("approval-banner") .confirmDecision(isPresented: $confirming, title: asking.confirm ?? asking.refuse, message: "", confirmLabel: asking.refuse, identifier: "approval-refuse-confirm") {Task { await keys.refuse() } } }RecoveryCards(recovery: keys.recovery) } .cottonCard(isPresented: Bindable(keys.recovery).entering, detents: [.half]) { RecoveryCodeEntry(recovery: keys.recovery) } }}/// On a phone waiting for the vault: *Approve on another device*, then that/// ask's code, large, to be typed on the device that holds the vault, and the/// poll's own line for where it stands. Every word is the core's.structVaultAskPart: View {let keys: SealedKeys/// A sentence naming Cotton, said in this app's own name.privatestaticfunc named(_ text: String?) -> String { ShellLines.said(text ?? "", as: ShellLines.speaker) }var body: someView {let polled = keys.vaultPolled VStack(alignment: .leading, spacing: 8) {iflet card = keys.vaultAsk, polled?.flag("done") != true {iflet code = polled?.text("code") {Text(Self.named(polled?.text("line"))) .paperBody(14) .fixedSize(horizontal: false, vertical: true)Text(code) .paperTitle(34) .monospacedDigit() .accessibilityIdentifier("sealed-ask-code")Text(Self.named(polled?.text("check"))) .paperMeta(13) .fixedSize(horizontal: false, vertical: true) } else {Text(Self.named(polled?.text("line") ?? card.text("line"))) .paperBody(14) .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("sealed-ask-state") } } else {iflet line = polled?.text("line") {Text(Self.named(line)) .paperBody(14, ink: polled?.text("state") == "approved" ? .ink : .red) .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("sealed-ask-state") }if keys.offersAsk, let ask = keys.mineAsk {Button(ask) { keys.openPage() } .disabled(keys.busy) .accessibilityIdentifier("sealed-ask") } } } }}