// 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.importCottonKitimportCottonPaperimportSwiftUI/// One ask waiting on this phone, as `signin.asks` says it.structSignInAsk: Equatable, Sendable {let askId: Stringlet 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: Stringlet sub: Stringlet approve: Stringlet notMe: Stringlet notMeConfirm: Stringlet notMeDone: Stringlet scanHeading: Stringlet typeInstead: Stringlet scanNone: Stringlet typeHeading: Stringlet typeWaiting: Stringlet never: Stringlet digits: Int// The older card's words, kept while Vault's look still reads them.let line: Stringlet type: Stringlet when: Stringlet refuse: Stringlet confirm: Stringinit?(_ value: JSONValue) {guardlet askId = value.text("askId"), let line = value.text("line"), let approve = value.text("approve") else { returnnil }self.askId = askId name = value.text("name") comparing = value.text("phase") == "compare" show = value.text("phase") == "asked" ? (value.text("show") ?? "") : nilself.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.structSignInCannot: Equatable, Sendable {let askId: Stringlet title: Stringlet line: Stringinit?(_ value: JSONValue?) {guardlet value, let askId = value.text("askId"), let title = value.text("title"), let line = value.text("line") else { returnnil }self.askId = askIdself.title = titleself.line = line }}@MainActor@ObservablefinalclassSignInAsks {/// 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 {guardlet ask, typing, ask.comparing, !busy else { return }let now = typed.filter(\.isNumber).count, before = oldValue.filter(\.isNumber).countif 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 privatelet core: any CottonCalling @ObservationIgnored privatelet vault: VaultAccess @ObservationIgnored privatelet say: @MainActor (String, CottonToast.Tone) -> Void/// When the next read is due: a tap brings it forward to the core's pace. @ObservationIgnored privatevar due = ContinuousClock.now/// This phone's vault key, lent once behind its lock for the approval on the card; dropped with the card. @ObservationIgnored privatevar lent: String?/// How long between reads when the core names none, or will not answer/// (signed out, not connected yet).staticlet idle: Double = 10init(core: any CottonCalling, vault: VaultAccess = VaultAccess(), say: @escaping @MainActor (String, CottonToast.Tone) -> Void) {self.core = coreself.vault = vaultself.say = say }/// Read until cancelled, at the pace the core names.func watch() async {while !Task.isCancelled {ifContinuousClock.now >= due { await read() }try? awaitTask.sleep(for: .seconds(1)) } }/// One read; answers the seconds until the next. @discardableResult func read() async -> Double {guardlet 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 privatefunc 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 privatefunc pace(_ seconds: Double) -> Double {let every = max(2, seconds) due = ContinuousClock.now + .seconds(every)return every }privatefunc draw(_ next: SignInAsk?, cannot: SignInCannot?) {if next?.askId != ask?.askId { typed = "" wrong = nil note = nil typing = false scanning = false confirming = false lent = nil } ask = nextself.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.privatefunc lend() async -> String? {iflet lent { return lent }switchawait vault.lent() {case .key(let key): lent = keyreturn keycase .not(.cancelled), .not(.answered):returnnilcase .not(.noPresence): say(ShellLines.line("unlock", "no_presence"), .error)returnnilcase .not(.refused(let words)): say(words, .error)returnnil } }/// Approve: the phone's lock, then the camera; where there is no camera, the digits.func approve() async {guard ask != nil, !busy else { return }guardawait lend() != nilelse { return } wrong = nilifSquareScanner.available { scanning = true } else {iflet 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 {guardlet ask, !busy, let key = await lend() else { return } busy = truedefer { busy = false }structScanned: Encodable, Sendable { let askId: String; let scanned: String; let privateKey: String; let name: String? }do {let said = tryawait core.callJSON(CottonMethod.signinApprove, Scanned(askId: ask.askId, scanned: text, privateKey: key, name: ask.name)) scanning = false done(said) } catchlet error asCottonCallErrorwhere error.code == "scan_wrong" {// A scan of some other screen: said over the camera, which stays open, and no try is spent. wrong = error.messagereturn } catchlet error asCottonCallError { 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 {guardlet ask, !busy else { return } scanning = false typing = trueguard ask.show != nilelse { return } busy = truedefer { busy = false }structShow: Encodable, Sendable { let askId: String }do { take(tryawait core.callJSON(CottonMethod.signinShow, Show(askId: ask.askId))) } catchlet error asCottonCallError { 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 {guardlet ask, ask.comparing, typing, !busy else { returnfalse }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 {guardlet ask, ready, let key = await lend() else { return } busy = truedefer { busy = false }structApprove: Encodable, Sendable { let askId: String; let code: String; let privateKey: String; let name: String? }let code = typed.filter(\.isNumber)do { done(tryawait core.callJSON(CottonMethod.signinApprove, Approve(askId: ask.askId, code: code, privateKey: key, name: ask.name))) } catchlet error asCottonCallErrorwhere error.code == "code_wrong" { wrong = error.message typed = ""return } catchlet error asCottonCallError { 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 }privatefunc done(_ said: JSONValue) {iflet 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 {guardlet ask, !busy else { return } busy = truedefer { busy = false }structRefuse: Encodable, Sendable { let askId: String; let name: String? }do { _ = tryawait core.callJSON(CottonMethod.signinRefuse, Refuse(askId: ask.askId, name: ask.name))if !ask.notMeDone.isEmpty { say(ask.notMeDone, .notice) }self.ask = nil } catchlet error asCottonCallError { 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.structSignInAskBanner: View { @Bindable var asks: SignInAsks @Environment(\.vaultLook) privatevar vaultLookvar body: someView {Group { #if os(iOS)iflet 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) {iflet ask = asks.ask {SquareScanner(heading: ask.scanHeading, typeInstead: ask.typeInstead, wrong: asks.wrong, onRead: { text inTask { 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 privatevar paper: someView {iflet 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") } elseiflet 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") } }iflet note = asks.note, asks.wrong == nil {Text(note).paperMeta(13).fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("signin-ask-note") }iflet 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() } } } }}