Cotton code
427 lines · 17.7 KB · SwiftRaw
// A NEW DEVICE ASKING TO SIGN IN, ON A DEVICE ALREADY SIGNED IN: THE ONE CARD// (GETTING-IN.md, 22 Nov 2026; Android's `SignInAskCard.kt` is the reference).// Over every Cotton app while the phone is connected.//// `signin.asks` is read every `pollSeconds` the core names. A read only looks.// The card says who asks in the person's words ("Your Mac wants to sign in to// your Cotton"), with **Approve** and **Not me**. Approve reads this phone's// vault key behind Face ID / the passcode (lent for this one approval), then// opens the camera over `scan.heading` (`SquareScanner`): the new device's// square code, read as text and passed untouched to `signin.approve// {askId, scanned, privateKey}`; the core checks it against the ask's// commitment and hands the key over before it says anything is done. **Type// the code instead** opens the ask (`signin.show`) so the new device shows six// digits, typed here. Not me asks the core's confirm first. A device that// cannot hand over the key gets no Approve: the core's `cannot` line, with no// button (OWNER.md). Every word is the core's.import CottonKitimport CottonPaperimport SwiftUI/// One ask waiting on this phone, as `signin.asks` says it.struct SignInAsk: Equatable, Sendable {    let askId: String    let name: String?    let comparing: Bool    /// `asked`: nothing set on the ask yet; Type the code instead opens it (`signin.show`).    let show: String?    /// "Your Mac wants to sign in to your Cotton" (the older `line` where the core sent no title).    let title: String    let sub: String    let approve: String    let notMe: String    let notMeConfirm: String    let notMeDone: String    let scanHeading: String    let typeInstead: String    let scanNone: String    let typeHeading: String    let typeWaiting: String    let never: String    let digits: Int    // The older card's words, kept while Vault's look still reads them.    let line: String    let type: String    let when: String    let refuse: String    let confirm: String    init?(_ value: JSONValue) {        guard let askId = value.text("askId"), let line = value.text("line"), let approve = value.text("approve") else { return nil }        self.askId = askId        name = value.text("name")        comparing = value.text("phase") == "compare"        show = value.text("phase") == "asked" ? (value.text("show") ?? "") : nil        self.line = line        title = value.text("title") ?? line        sub = value.text("sub") ?? value.text("when") ?? ""        self.approve = approve        refuse = value.text("refuse") ?? ""        notMe = value.text("notMe") ?? refuse        confirm = value.text("confirm") ?? refuse        notMeConfirm = value.text("notMeConfirm") ?? confirm        notMeDone = value.text("notMeDone") ?? ""        let scan = value["scan"]        scanHeading = scan?.text("heading") ?? ""        typeInstead = scan?.text("typeInstead") ?? ""        scanNone = scan?.text("none") ?? ""        type = value.text("type") ?? ""        typeHeading = value.text("typeHeading") ?? type        typeWaiting = value.text("typeWaiting") ?? ""        never = value.text("never") ?? ""        digits = value["digits"]?.int ?? 6        when = value.text("when") ?? ""    }}/// A device that cannot hand over the key: who asks, and the one line saying why and what to do. No button.struct SignInCannot: Equatable, Sendable {    let askId: String    let title: String    let line: String    init?(_ value: JSONValue?) {        guard let value, let askId = value.text("askId"), let title = value.text("title"), let line = value.text("line") else { return nil }        self.askId = askId        self.title = title        self.line = line    }}@MainActor@Observablefinal class SignInAsks {    /// The oldest ask waiting, nil while nobody asks.    private(set) var ask: SignInAsk?    /// This device cannot hand over the key: the line in place of a card.    private(set) var cannot: SignInCannot?    /// The code as typed here, for the ask on the card. The last digit sends it: at the largest text, or with the    /// number pad up, Approve stood out of reach under the keyboard (iPhone walk, 23 Nov 2026).    var typed = "" {        didSet {            guard let ask, typing, ask.comparing, !busy else { return }            let now = typed.filter(\.isNumber).count, before = oldValue.filter(\.isNumber).count            if now == ask.digits, before < ask.digits { Task { await approveTyped() } }        }    }    /// A plain note on the card (no camera here): said in the card's quiet ink, not as an error.    private(set) var note: String?    /// The core's sentence for a wrong code or a wrong scan, said on the card.    private(set) var wrong: String?    private(set) var busy = false    /// The camera stands over the app (after Approve and the phone's lock).    var scanning = false    /// Type the code instead was chosen: the digits field stands on the card.    private(set) var typing = false    /// Not me was tapped: the core's confirm stands.    var confirming = false    @ObservationIgnored private let core: any CottonCalling    @ObservationIgnored private let vault: VaultAccess    @ObservationIgnored private let say: @MainActor (String, CottonToast.Tone) -> Void    /// When the next read is due: a tap brings it forward to the core's pace.    @ObservationIgnored private var due = ContinuousClock.now    /// This phone's vault key, lent once behind its lock for the approval on the card; dropped with the card.    @ObservationIgnored private var lent: String?    /// How long between reads when the core names none, or will not answer    /// (signed out, not connected yet).    static let idle: Double = 10    init(core: any CottonCalling, vault: VaultAccess = VaultAccess(), say: @escaping @MainActor (String, CottonToast.Tone) -> Void) {        self.core = core        self.vault = vault        self.say = say    }    /// Read until cancelled, at the pace the core names.    func watch() async {        while !Task.isCancelled {            if ContinuousClock.now >= due { await read() }            try? await Task.sleep(for: .seconds(1))        }    }    /// One read; answers the seconds until the next.    @discardableResult func read() async -> Double {        guard let answer = try? await core.callJSON(CottonMethod.signinAsks) else {            draw(nil, cannot: nil)            return pace(Self.idle)        }        return take(answer)    }    /// The card a read or `signin.show` answered; the seconds until the next read.    @discardableResult private func take(_ answer: JSONValue) -> Double {        draw((answer["waiting"]?.array ?? []).lazy.compactMap(SignInAsk.init).first, cannot: SignInCannot(answer["cannot"]))        return pace(answer.decimal("pollSeconds") ?? Self.idle)    }    @discardableResult private func pace(_ seconds: Double) -> Double {        let every = max(2, seconds)        due = ContinuousClock.now + .seconds(every)        return every    }    private func draw(_ next: SignInAsk?, cannot: SignInCannot?) {        if next?.askId != ask?.askId {            typed = ""            wrong = nil            note = nil            typing = false            scanning = false            confirming = false            lent = nil        }        ask = next        self.cannot = next == nil ? cannot : nil    }    /// This phone's vault key behind its own lock, once per card; nil when the person cancelled or it was refused.    private func lend() async -> String? {        if let lent { return lent }        switch await vault.lent() {        case .key(let key):            lent = key            return key        case .not(.cancelled), .not(.answered):            return nil        case .not(.noPresence):            say(ShellLines.line("unlock", "no_presence"), .error)            return nil        case .not(.refused(let words)):            say(words, .error)            return nil        }    }    /// Approve: the phone's lock, then the camera; where there is no camera, the digits.    func approve() async {        guard ask != nil, !busy else { return }        guard await lend() != nil else { return }        wrong = nil        if SquareScanner.available {            scanning = true        } else {            if let none = ask?.scanNone, !none.isEmpty { note = none }            await typeInstead()        }    }    /// The new device's square code, read by the camera: passed to the core untouched.    func scanned(_ text: String) async {        guard let ask, !busy, let key = await lend() else { return }        busy = true        defer { busy = false }        struct Scanned: Encodable, Sendable { let askId: String; let scanned: String; let privateKey: String; let name: String? }        do {            let said = try await core.callJSON(CottonMethod.signinApprove, Scanned(askId: ask.askId, scanned: text, privateKey: key, name: ask.name))            scanning = false            done(said)        } catch let error as CottonCallError where error.code == "scan_wrong" {            // A scan of some other screen: said over the camera, which stays open, and no try is spent.            wrong = error.message            return        } catch let error as CottonCallError {            scanning = false            say(error.message, .error)            self.ask = nil        } catch {            scanning = false            say(ShellLines.line("board", "customer.refusal.refused"), .error)        }        await read()    }    /// Type the code instead: the ask opened (`signin.show`) so the new device shows its digits, typed here.    func typeInstead() async {        guard let ask, !busy else { return }        scanning = false        typing = true        guard ask.show != nil else { return }        busy = true        defer { busy = false }        struct Show: Encodable, Sendable { let askId: String }        do {            take(try await core.callJSON(CottonMethod.signinShow, Show(askId: ask.askId)))        } catch let error as CottonCallError {            say(error.message, .error)            await read()        } catch {            say(ShellLines.line("board", "customer.refusal.refused"), .error)        }    }    /// Whether the typed code can be sent: every digit typed, the code compared.    var ready: Bool {        guard let ask, ask.comparing, typing, !busy else { return false }        return typed.filter(\.isNumber).count == ask.digits    }    /// Approve with the typed digits, with the key lent at Approve (or now, behind the lock).    func approveTyped() async {        guard let ask, ready, let key = await lend() else { return }        busy = true        defer { busy = false }        struct Approve: Encodable, Sendable { let askId: String; let code: String; let privateKey: String; let name: String? }        let code = typed.filter(\.isNumber)        do {            done(try await core.callJSON(CottonMethod.signinApprove, Approve(askId: ask.askId, code: code, privateKey: key, name: ask.name)))        } catch let error as CottonCallError where error.code == "code_wrong" {            wrong = error.message            typed = ""            return        } catch let error as CottonCallError {            say(error.message, .error)            self.ask = nil        } catch {            say(ShellLines.line("board", "customer.refusal.refused"), .error)        }        await read()    }    /// The approval answered: its words said once (the core says the device can open the things only once the key    /// was handed over), a pass run, the card gone.    /// Back from typing to the card (the typing screen's close): the digits typed so far go.    func stopTyping() {        typing = false        typed = ""        wrong = nil    }    private func done(_ said: JSONValue) {        if let words = said.text("said") { say(words, .success) }        Task { _ = try? await core.callJSON(CottonMethod.syncNow) }        ask = nil        typed = ""        wrong = nil        typing = false        lent = nil    }    /// Kept for Vault's look until it draws the one card: Approve on a typed code.    func approveOld() async { await approveTyped() }    /// Not me, once the person confirmed it.    func refuse() async {        guard let ask, !busy else { return }        busy = true        defer { busy = false }        struct Refuse: Encodable, Sendable { let askId: String; let name: String? }        do {            _ = try await core.callJSON(CottonMethod.signinRefuse, Refuse(askId: ask.askId, name: ask.name))            if !ask.notMeDone.isEmpty { say(ask.notMeDone, .notice) }            self.ask = nil        } catch let error as CottonCallError {            say(error.message, .error)        } catch {            say(ShellLines.line("board", "customer.refusal.refused"), .error)        }        await read()    }}/// The card, beside the vault's, while an ask waits; the one line where this device cannot approve.struct SignInAskBanner: View {    @Bindable var asks: SignInAsks    @Environment(\.vaultLook) private var vaultLook    var body: some View {        Group {            #if os(iOS)            if let look = vaultLook, asks.ask != nil || asks.cannot != nil {                // Inside an app with a look of its own the card is drawn in that look.                VaultSignInBanner(asks: asks, look: look)            } else {                paper            }            #else            paper            #endif        }        #if os(iOS)        .fullScreenCover(isPresented: $asks.scanning) {            if let ask = asks.ask {                SquareScanner(heading: ask.scanHeading, typeInstead: ask.typeInstead, wrong: asks.wrong,                              onRead: { text in Task { await asks.scanned(text) } },                              onTypeInstead: { Task { await asks.typeInstead() } },                              onClose: { asks.scanning = false })            }        }        #endif    }    /// The card on paper, as the apps without a look draw it.    @ViewBuilder private var paper: some View {        if let cannot = asks.cannot {            Paper(dye: .peach, edge: .torn, seed: "signin-cannot", tilt: false, inset: 16) {                VStack(alignment: .leading, spacing: 8) {                    Text(cannot.title).paperTitle(15).fixedSize(horizontal: false, vertical: true)                    Text(cannot.line).paperBody(14).fixedSize(horizontal: false, vertical: true)                        .accessibilityIdentifier("signin-cannot-line")                }            }            .padding(.horizontal, ChromeKnobs.chromeSettingsMargin)            .padding(.top, 6)            .padding(.bottom, 8)            .accessibilityIdentifier("signin-cannot")        } else if let ask = asks.ask {            Paper(dye: .peach, edge: .torn, seed: "signin-ask", tilt: false, inset: 16) {                VStack(alignment: .leading, spacing: 10) {                    Text(ask.title)                        .paperTitle(15)                        .fixedSize(horizontal: false, vertical: true)                        .accessibilityIdentifier("signin-ask-line")                    if !ask.sub.isEmpty {                        Text(ask.sub).paperMeta(14).fixedSize(horizontal: false, vertical: true)                    }                    if asks.typing {                        Text(ask.comparing ? ask.typeHeading : ask.typeWaiting)                            .paperMeta(14)                            .fixedSize(horizontal: false, vertical: true)                        if ask.comparing {                            // Typed from the other screen; never offered from a text message.                            PaperTextField(ask.typeHeading, text: $asks.typed, size: 22)                                .keyboardType(.numberPad)                                .autocorrectionDisabled()                                .accessibilityIdentifier("signin-ask-code")                        }                    }                    if let note = asks.note, asks.wrong == nil {                        Text(note).paperMeta(13).fixedSize(horizontal: false, vertical: true)                            .accessibilityIdentifier("signin-ask-note")                    }                    if let wrong = asks.wrong, !asks.scanning {                        Text(wrong)                            .paperBody(14, ink: .red)                            .fixedSize(horizontal: false, vertical: true)                            .accessibilityIdentifier("signin-ask-wrong")                    }                    HStack(spacing: 24) {                        if asks.typing {                            Button(ask.approve) { Task { await asks.approveTyped() } }                                .disabled(!asks.ready)                                .accessibilityIdentifier("signin-ask-approve-typed")                        } else {                            Button(ask.approve) { Task { await asks.approve() } }                                .disabled(asks.busy)                                .accessibilityIdentifier("signin-ask-approve")                        }                        Button(ask.notMe) { asks.confirming = true }                            .disabled(asks.busy)                            .accessibilityIdentifier("signin-ask-refuse")                    }                }            }            .padding(.horizontal, ChromeKnobs.chromeSettingsMargin)            .padding(.top, 6)            .padding(.bottom, 8)            .accessibilityIdentifier("signin-ask-banner")            .confirmDecision(isPresented: $asks.confirming, title: ask.notMeConfirm, message: "", confirmLabel: ask.notMe,                             identifier: "signin-ask-refuse-confirm") {                Task { await asks.refuse() }            }        }    }}