Cotton code
665 lines · 30.0 KB · SwiftRaw
// 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).import CottonKitimport SwiftUI/// 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.struct ApprovalAsk: Equatable, Sendable {    let deviceId: String    let line: String    let how: String?    let refuse: String    let confirm: String?    init?(_ value: JSONValue?) {        guard let value, let deviceId = value.text("deviceId"), let line = value.text("line"),            let refuse = value.text("refuse") else { return nil }        self.deviceId = deviceId        self.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.struct SignedInAs: Equatable, Sendable {    let server: String    let phone: String    /// The Keychain's session for this flavour's personal object (blocks: off the main thread).    static func held(core: any CottonCalling) -> SignedInAs? {        guard let address = FlavourManifest.current?.personalObject,            let phone = BusinessClient(core: core, address: address).session()?.phone, !phone.isEmpty else { return nil }        return SignedInAs(server: address.server, phone: phone)    }}struct RefuseDeviceRequest: Encodable, Sendable {    let deviceId: String}@MainActor@Observablefinal class SealedKeys {    /// 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 private let core: any CottonCalling    @ObservationIgnored private let vault: VaultAccess    @ObservationIgnored private let keeper: any DataKeyKeeping    @ObservationIgnored private let name: @Sendable () -> String    @ObservationIgnored private let pause: @Sendable (Double) async -> Void    @ObservationIgnored private let say: @MainActor (String, CottonToast.Tone) -> Void    /// A quiet open is under way: a second read does not start another.    @ObservationIgnored private var opening = false    /// The key published once on `joins`; a new database (another sign-in) asks again.    @ObservationIgnored private var joinAsked = false    @ObservationIgnored private var joinedDatabase: String?    @ObservationIgnored private var poll: Task<Void, Never>?    @ObservationIgnored private var askPolling: Task<Void, Never>?    @ObservationIgnored private var paging: Task<Void, Never>?    @ObservationIgnored private var askAgain = false    @ObservationIgnored private let account: @Sendable () -> SignedInAs?    /// How many quiet tries a founding gets, and the pause between them.    static let foundTries = 4    static let foundPause = 1.5    init(        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? await Task.sleep(for: .seconds($0)) },        say: @escaping @MainActor (String, CottonToast.Tone) -> Void    ) {        self.core = core        self.account = account ?? { [core] in SignedInAs.held(core: core) }        self.vault = vault        self.keeper = keeper        self.name = name        self.pause = pause        self.say = say        recovery = RecoveryKeys(core: core, vault: vault, platform: platform, name: name, say: say)        recovery.opened = { [weak self] in await self?.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 private var seeded: ApprovalAsk? = SealedKeys.seededAsk()    static func seededAsk(_ arguments: [String] = ProcessInfo.processInfo.arguments) -> ApprovalAsk? {        guard let at = arguments.firstIndex(of: "-shell-card-seed"), at + 1 < arguments.count,            arguments[at + 1] == "YES" else { return nil }        let name = ShellLines.line("unlock", "approval.seed_name")        return ApprovalAsk(.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 {        guard var status = await status() else { return }        let database = status.text("database")        recovery.standsOn(database: database)        if database != joinedDatabase { joinedDatabase = database; joinAsked = false }        if let database, !status.flag("keyHeld"), let kept = keeper.read(database: database) {            do {                _ = try await core.callJSON(CottonMethod.sealUseKey, ["key": kept])                status = await self.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 {                _ = try await core.callJSON(CottonMethod.sealMakeKey)                status = await self.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.        if let database, status.flag("needsKey"), !status.flag("founds"), !opening,            await recovery.openFromICloud(database: database) {            status = await self.status() ?? status        }        if status.flag("needsKey"), status.flag("founds"), !opening {            await openQuietly()            status = await self.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 = await self.status() ?? status        }        if let 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 = try await core.callJSON(CottonMethod.sealHeldKey)                if let 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 = await self.status() ?? status        }        waiting = mine != nil && status.flag("needsKey")        mineAsk = waiting ? mine?.text("ask") : nil        if !waiting { stopAsking() }        if waiting { watchPage() } else { stopPage() }        asking = ApprovalAsk(approval?["waiting"])        #if COTTON_DEV        if asking == nil { asking = seeded }        #endif        let 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.            if await recovery.whileWaiting() { await read() }        } else if let database, status.flag("keyHeld") {            await recovery.whileHeld(database: database, bannerUp: line != nil || asking != nil)        }    }    private func status() async -> JSONValue? {        do {            return try await core.callJSON(CottonMethod.sealStatus)        } catch {            Log.write("seal: the data key's state could not be read — \(error)")            return nil        }    }    /// 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.    private func openQuietly() async {        opening = true        defer { opening = false }        for attempt in 0..<Self.foundTries {            switch await vault.unlockQuietly(through: core, name: name()) {            case .open:                return            case .waitingForMac:                let approval = try? await core.callJSON(CottonMethod.vaultApproval)                if approval?["mine"]?.text("deviceId") != nil {                    waiting = true                    return                }            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 = true        defer { busy = false }        switch await 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 {        guard let address = FlavourManifest.current?.personalObject else { return }        let core = core        stopPage()        await Task.detached { await BusinessClient(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.    private func watchPage() {        guard paging == nil else { return }        paging = Task { @MainActor [weak self] in            while !Task.isCancelled {                guard let self, self.waiting else { return }                let account = self.account                guard let signedIn = await Task.detached(operation: { account() }).value else {                    try? await Task.sleep(for: .seconds(5))                    continue                }                struct Screen: 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                    #else                    return nil                    #endif                }()                let request = Screen(server: signedIn.server, phone: signedIn.phone, deviceName: self.name(), deviceKind: kind)                let method = self.askAgain ? CottonMethod.gettingInAgain : CottonMethod.gettingInScreen                self.askAgain = false                let answer: JSONValue                do {                    answer = try await self.core.callJSON(method, request)                } catch {                    Log.write("seal: the getting-in page could not be read — \(error)")                    try? await Task.sleep(for: .seconds(5))                    continue                }                guard !Task.isCancelled else { return }                if answer.flag("show") == false {                    self.page = nil                    self.paging = nil                    await self.read()                    return                }                self.page = answer                if answer.flag("sync") {                    _ = try? await self.core.callJSON(CottonMethod.syncNow)                    await self.read()                }                try? await Task.sleep(for: .seconds(max(2, answer.decimal("pollSeconds") ?? 3)))            }        }    }    private func 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 = true        defer { busy = false }        let account = account        guard let signedIn = await Task.detached(operation: { account() }).value else {            say(ShellLines.line("board", "customer.refusal.refused"), .error)            return        }        let key: String        switch await vault.lent() {        case .key(let lent): key = lent        case .not(.cancelled), .not(.answered): return        case .not(.noPresence):            say(ShellLines.line("unlock", "no_presence"), .error)            return        case .not(.refused(let words)):            say(words, .error)            return        }        struct Ask: Encodable, Sendable { let server: String; let phone: String; let deviceName: String; let privateKey: String }        do {            let card = try await 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)        } catch let error as CottonCallError {            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.    private func pollAsk(_ card: JSONValue, server: String) {        guard let askId = card.text("askId") else { return }        let every = max(1, card.decimal("pollSeconds") ?? 3)        struct Poll: Encodable, Sendable { let server: String; let askId: String }        askPolling = Task { @MainActor [weak self] in            while !Task.isCancelled {                try? await Task.sleep(for: .seconds(every))                guard let self, !Task.isCancelled, self.vaultAsk?.text("askId") == askId else { return }                let answer: JSONValue                do {                    answer = try await self.core.callJSON(CottonMethod.personalAskPoll, Poll(server: server, askId: askId))                } catch let error as CottonCallError {                    // 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 = nil                if answer.text("state") == "approved" {                    _ = try? await self.core.callJSON(CottonMethod.syncNow)                    await self.read()                }                return            }        }    }    /// A poll's answer without what an approval grants.    private static func words(of answer: JSONValue) -> JSONValue {        guard case .object(var fields) = answer else { return answer }        for granted in ["credential", "person", "expiresIn", "databaseId"] { fields.removeValue(forKey: granted) }        return .object(fields)    }    private func stopAsking() {        askPolling?.cancel()        askPolling = nil        vaultAsk = nil        vaultPolled = nil    }    /// *Refuse*, once the person confirmed it.    func refuse() async {        guard let asking, !busy else { return }        #if COTTON_DEV        if asking == seeded {            seeded = nil            self.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 = true        defer { busy = false }        do {            _ = try await core.callJSON(CottonMethod.vaultRefuseDevice, RefuseDeviceRequest(deviceId: asking.deviceId))        } catch let error as CottonCallError {            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`.    private func keepPolling(_ seconds: Double?) {        guard let seconds, seconds > 0 else {            poll?.cancel()            poll = nil            return        }        guard poll == nil else { return }        poll = Task { @MainActor [weak self] in            try? await Task.sleep(for: .seconds(seconds))            guard let self, !Task.isCancelled else { return }            self.poll = nil            _ = try? await self.core.callJSON(CottonMethod.syncNow)            await self.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.struct SealedKeyBanner: View {    let keys: SealedKeys    @State private var confirming = false    @Environment(\.vaultLook) private var vaultLook    var body: some View {        #if os(iOS)        if let 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.    private var paper: some View {        VStack(spacing: 0) {            if let 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")                        if let 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) {                                if let haveCode = keys.recovery.line("haveCode") {                                    Button(haveCode) { keys.recovery.entering = true }                                        .accessibilityIdentifier("recovery-have-code")                                }                                if let 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")            }            if let 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")                        if let 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.struct VaultAskPart: View {    let keys: SealedKeys    /// A sentence naming Cotton, said in this app's own name.    private static func named(_ text: String?) -> String { ShellLines.said(text ?? "", as: ShellLines.speaker) }    var body: some View {        let polled = keys.vaultPolled        VStack(alignment: .leading, spacing: 8) {            if let card = keys.vaultAsk, polled?.flag("done") != true {                if let 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 {                if let 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")                }            }        }    }}