//! A NEW DEVICE APPROVED FROM ONE ALREADY SIGNED IN (owner, 17 Nov 2026://! signing in should not need an SMS every time; SMS stays for the first//! device and for recovery). The Worker's half is//! `apps/business/src/approval.ts`; every rule a shell would otherwise make//! up — what each state says, when to stop polling, the matching code's//! look, how long ago and how long left — is here, and every word is//! `kits/shell/lines/signin.json`.//!//! THE CODE IS NOT THE SERVER'S (19 Nov 2026). The six//! digits both screens show come from a commit and two nonces, so a server//! that swapped the asking device's key or vault key in between would make the//! two screens disagree ([`commit_of`], [`sas_of`]; the Worker's `askCommit` ///! `askSas`). And the approver TYPES the code instead of tapping Approve, so a//! blind tap lets nobody in. With the code typed right, one approval also lets//! the new device into the vault: the vault's key wrapped for the key the code//! vouched for, written as that device's own row (`devices::admit`).//!//! THE ASKING DEVICE (the sign-in screen, beside "send a code")://!//! ```text//! personal.ask { server, phone, deviceName?, vaultKey? | privateKey? }//! → { askId, heading, line, never, waiting, left, pollSeconds, sendCode, cancel,//! handoff: { deviceId, vaultKey, nonce } }//! personal.askPoll { server, askId }//! → { state: waiting | approved | refused | expired | used, done, line, code?, check?, left?,//! again?, sendCode?, credential?, person?, expiresIn?, databaseId? }//! personal.handoff { phone, app } → { line, button }//! ```//!//! `vaultKey` is this device's X25519 public key (the one `vault.publishKey`//! says), or the public half of `privateKey` when the shell lends that;//! absent, the one this process last published, and with none the//! ask signs in only. While nobody has opened the ask the poll says `line`//! alone; once the approving device has, it carries `code` (two threes) and//! `check`, the words to type it there. The answer to an ask is the same//! whether or not the number is on Cotton. On `approved` the core has already//! claimed the credential with this device's key, as `personal.signIn` hands//! one over. `handoff` is what a sibling Cotton app on the same phone needs to//! approve this ask with no code (`signin.approveSibling`): it never leaves the//! phone.//!//! THE APPROVING DEVICE (any signed-in Cotton app)://!//! ```text//! signin.asks {} → { waiting: [{ askId, name, phase: asked | opening | compare, line, type, show?, never,//! digits, when, vault, approve, refuse, confirm }], pollSeconds }//! signin.show { askId } → the same card, that ask opened//! signin.approve { askId, code, privateKey?, name? } → { ok, vault, said }//! signin.refuse { askId, name? } → { ok, said }//! signin.siblingTicket { askId } → { ticket } (the checked channel only: see below)//! signin.approveSibling { askId, deviceId, vaultKey?, nonce, ticket, privateKey? } → { ok, vault }//! ```//!//! NOTHING IS SET UNTIL A PERSON TAPS (19 Nov 2026; owner//! rule: nothing may say whether a number is on Cotton). `signin.asks` only//! looks: a new ask is `asked`, with `show` ("This is me, show the code") and//! Refuse. `signin.show` is that tap: it sets this device's nonce, so the//! asking device can show its code, and the ask is `opening` until that device//! reveals, then `compare`. Before the tap the asking device's screen is the//! same whether or not the number has a phone open (the Worker's half,//! src/approval.ts). The code is never in the answer. `signin.approve` checks//! the code typed against the one worked out here: wrong, the OBJECT counts it//! (`/v1/approvals/wrong`, across every device of the number and every//! restart) and it is refused `code_wrong` (the sentence says the tries left);//! the third wrong try ends the ask (`code_ended`). Right, the object approves;//! then, with `privateKey` (this device's vault key, after the phone's lock)//! and an ask that named a vault key, the new device's vault row is written//! with its wrap and `vault` is true. That is the ONE way into the vault from//! another device: `vault.approveDevice`'s one tap is refused, and the object//! keeps no wrap onto another device's row without such an ask.//!//! A sibling on the same phone approves through `signin.approveSibling`, with//! no code and no presence. See [`approve_sibling`]: it is safe only because//! the channel is checked, and it refuses without the ticket that channel//! alone carries.use std::collections::HashMap;use std::sync::Mutex;use rand::RngCoreas _;use std::time::{Duration, Instant};use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine;use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::{Exchange, SocketExchange};use cotton_core::rules::shell_lines::resolve;use serde_json::{json, Value};usecrate::handle::CottonHandle;usecrate::methods::MethodError;usecrate::phone::personal_object::ObjectDoor;/// The open host's routes for the asking device.pubconst ASK: &str = "/v1/approval/ask";pubconst POLL: &str = "/v1/approval/poll";pubconst CLAIM: &str = "/v1/approval/claim";pubconst REVEAL: &str = "/v1/approval/reveal";/// The object's routes for the approving device.pubconst APPROVALS: &str = "/v1/approvals";pubconst APPROVE: &str = "/v1/approvals/approve";pubconst REFUSE: &str = "/v1/approvals/refuse";pubconst NONCE: &str = "/v1/approvals/nonce";pubconst WRONG: &str = "/v1/approvals/wrong";/// How often a signed-in device looks for asks while its card is up.pubconst ASKS_POLL_SECONDS: u64 = 10;/// How often it looks while an ask is being opened, so the code comes up fast.pubconst OPENING_POLL_SECONDS: u64 = 2;/// How long a sibling ticket stands between its minting and the approval it is spent on.pubconst TICKET_SECONDS: u64 = 60;/// How often the asking device polls, when the Worker names none.pubconst ASK_POLL_SECONDS: u64 = 3;/// The methods the asking device calls, before any sign-in.pubconst ASKING_METHODS: [&str; 3] = ["personal.ask", "personal.askPoll", "personal.handoff"];/// The methods the approving device calls, through its object door.pubconst METHODS: [&str; 6] = ["signin.approve", "signin.approveSibling", "signin.asks", "signin.refuse", "signin.show", "signin.siblingTicket"];pubuse cotton_core::vault::approval::{claim_statement, commit_of, sas_of};fn bytes32(text: &str) -> Option<[u8; 32]> { URL_SAFE_NO_PAD.decode(text).ok().and_then(|bytes| bytes.try_into().ok())}fn fresh32() -> [u8; 32] {letmut bytes = [0u8; 32]; rand::rngs::OsRng.fill_bytes(&mut bytes); bytes}fn say(line: &str, fills: &[(&str, &str)]) -> String { resolve("signin", line, &[], fills).unwrap_or_default()}pubuse cotton_core::vault::approval::shown_code;/// Whole minutes left, rounded up, never below one while any second is.fn minutes_left(seconds: i64) -> i64 {if seconds <= 0 {0 } else { (seconds + 59) / 60 }}fn left_line(seconds: i64) -> String {let n = minutes_left(seconds).max(1).to_string(); say("asking.left", &[("n", &n)])}/// An ask this process made: when it expires (the poll's "minutes left"),/// what it committed to, and the code once the approver's nonce came. The/// nonce is never written anywhere: an app that restarts mid-ask asks again.structPending { deadline: Instant, device_id: [u8; 32], vault_key: Option<[u8; 32]>, nonce: [u8; 32], code: Option<String>,}fn pending() -> &'staticMutex<HashMap<String, Pending>> {static PENDING: std::sync::OnceLock<Mutex<HashMap<String, Pending>>> = std::sync::OnceLock::new(); PENDING.get_or_init(|| Mutex::new(HashMap::new()))}/// The sibling tickets this process minted and has not spent: ticket → (ask, when it lapses).fn tickets() -> &'staticMutex<HashMap<String, (String, Instant)>> {static TICKETS: std::sync::OnceLock<Mutex<HashMap<String, (String, Instant)>>> = std::sync::OnceLock::new(); TICKETS.get_or_init(|| Mutex::new(HashMap::new()))}/// A ticket for `ask_id`, good once within TICKET_SECONDS.fn mint_ticket(ask_id: &str) -> String {let ticket = URL_SAFE_NO_PAD.encode(fresh32());ifletOk(mut held) = tickets().lock() {let now = Instant::now(); held.retain(|_, (_, lapses)| *lapses > now); held.insert(ticket.clone(), (ask_id.to_string(), now + Duration::from_secs(TICKET_SECONDS))); } ticket}/// Spend `ticket` on `ask_id`: true once, for a live ticket minted for that very ask.fn spend_ticket(ticket: &str, ask_id: &str) -> bool {letOk(mut held) = tickets().lock() else { returnfalse };match held.remove(ticket) {Some((ask, lapses)) => ask == ask_id && lapses > Instant::now(),None => false, }}fn forget(ask_id: &str) {ifletOk(mut held) = pending().lock() { held.remove(ask_id); }}fn text<'a>(request: &'a Value, field: &str) -> Result<&'a str, MethodError> { request .get(field) .and_then(Value::as_str) .map(str::trim) .filter(|value| !value.is_empty()) .ok_or_else(|| MethodError::new("bad_request", format!("`{field}` is missing")))}fn open(server: &str) -> Result<ObjectAddress, MethodError> {ObjectAddress::open(server).map_err(|reason| MethodError::new("bad_request", reason))}// ── the asking device ─────────────────────────────────────────────────────/// Signs as this device: its key's public half is its device id.pubtraitDeviceSigner {fn device_id(&self) -> String;fn sign(&self, message: &[u8]) -> Result<[u8; 64], String>;}implDeviceSignerfor std::sync::Arc<dyn cotton_store::signed::ReceiptSigner> {fn device_id(&self) -> String {self.device_key() }fn sign(&self, message: &[u8]) -> Result<[u8; 64], String> { cotton_store::signed::ReceiptSigner::sign(self.as_ref(), message) }}pubfn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> { call_with(handle, method, request, &SocketExchange)}pubfn call_with(handle: &CottonHandle, method: &str, request: &Value, exchange: &dynExchange) -> Result<Value, MethodError> {if method == "personal.handoff" {return handoff(request); }let client = handle.client();let slot = client.receipt_signer_slot();let signer = slot.get().cloned().ok_or_else(|| MethodError::new("device_key_unreadable", "this device has no device identity"))?;match method {"personal.ask" => {super::personal_object::phone(request)?;letmut request = request.clone();if request.get("vaultKey").and_then(Value::as_str).is_none() {// The shell may lend this device's vault key (it keeps only the private half): its public half is// what the ask names, and the private half goes no further than this line.let public = match request.get("privateKey") {Some(_) => Some(URL_SAFE_NO_PAD.encode(cotton_core::vault::wrap::public_of(&super::vault::private_key_arg(&request)?))),None => client.vault_public(), };ifletSome(public) = public { request["vaultKey"] = json!(public); } }ifletSome(fields) = request.as_object_mut() { fields.remove("privateKey"); } ask(&open(text(&request, "server")?)?, exchange, &signer, &request) }"personal.askPoll" => poll(&open(text(request, "server")?)?, exchange, &signer, text(request, "askId")?),"signin.asks" | "signin.show" | "signin.approve" | "signin.refuse" | "signin.siblingTicket" | "signin.approveSibling" => {let door = client.object_door().ok_or_else(|| MethodError::new("not_connected", "this phone is not connected to its database yet"))?; over(&door, method, request, now_seconds(), &ClientVault(&client)) } other => Err(MethodError::new("unknown_method", format!("`{other}` is not a sign-in approval method"))), }}fn now_seconds() -> i64 { std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)}/// `personal.handoff`: the one-tap button a Cotton app on a phone where a sibling is signed in draws. The number/// shows only its last four digits.fn handoff(request: &Value) -> Result<Value, MethodError> {let phone = text(request, "phone")?;let app = text(request, "app")?;let digits: String = phone.chars().filter(char::is_ascii_digit).collect();let tail = &digits[digits.len().saturating_sub(4)..];let masked = format!("•••• {tail}");Ok(json!({"line": say("handoff.line", &[("app", app)]),"button": say("handoff.button", &[("phone", &masked)]),// The one tap never shows a waiting screen (GETTING-IN.md, step 1): it opens, or this is said over the number."failed": say("handoff.failed", &[("app", app)]), }))}/// What this device is, for the approving card's "Your Mac" (GETTING-IN.md): the shell's `deviceKind` where it/// knows better (an iPad), else what this build runs on.pubfn device_kind(request: &Value) -> &'static str {match request.get("deviceKind").and_then(Value::as_str) {Some("mac") => "mac",Some("iphone") => "iphone",Some("ipad") => "ipad",Some("android") => "android",Some("computer") => "computer", _ if cfg!(target_os = "android") => "android", _ if cfg!(target_os = "ios") => "iphone", _ if cfg!(target_os = "macos") => "mac", _ => "computer", }}/// `personal.ask`: one ask, drawn the same for every number. Commits to this device's key, its vault key and a/// fresh nonce; the code comes once a signed-in device has opened the ask.pubfn ask(address: &ObjectAddress, exchange: &dynExchange, signer: &dynDeviceSigner, request: &Value) -> Result<Value, MethodError> {let device_id = signer.device_id();let device = bytes32(&device_id).ok_or_else(|| MethodError::new("device_key_unreadable", "this device's key is not 32 bytes"))?;let vault_key = match request.get("vaultKey").and_then(Value::as_str).map(str::trim).filter(|k| !k.is_empty()) {Some(key) => Some(bytes32(key).ok_or_else(|| MethodError::new("bad_request", "`vaultKey` is 32 bytes, base64url without padding"))?),None => None, };let nonce = fresh32();let commit = commit_of(&device, vault_key.as_ref().map(|k| k.as_slice()), &nonce);letmut body = json!({ "phone": text(request, "phone")?, "device_id": device_id, "commit": URL_SAFE_NO_PAD.encode(commit) });ifletSome(key) = &vault_key { body["vault_key"] = json!(URL_SAFE_NO_PAD.encode(key)); }ifletSome(name) = request.get("deviceName").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()) { body["device_name"] = json!(name); } body["device_kind"] = json!(device_kind(request));let answer = address.send(exchange, "POST", ASK, Vec::new(), Some(&body))?;let ask_id = answer["ask_id"].as_str().filter(|id| !id.is_empty()).ok_or_else(|| MethodError::new("refused", "the Worker sent no ask"))?;let expires_in = answer["expires_in"].as_i64().unwrap_or(0);let poll_seconds = answer["poll_seconds"].as_u64().filter(|s| *s > 0).unwrap_or(ASK_POLL_SECONDS);ifletOk(mut held) = pending().lock() { held.insert( ask_id.to_string(),Pending { deadline: Instant::now() + Duration::from_secs(expires_in.max(0) as u64), device_id: device, vault_key, nonce, code: None }, ); }Ok(json!({"askId": ask_id,// The square code a signed-in phone scans to open this ask (GETTING-IN.md's own, `getting_in::square`): the// asking card shows it beside the words; the six digits follow once a phone has opened the ask (NEXT-SIGNIN 3)."qr": crate::phone::getting_in::square(ask_id, &nonce),"heading": say("asking.heading", &[]),"line": say("asking.open", &[]),"never": say("asking.never", &[]),"waiting": say("asking.waiting", &[]),"left": left_line(expires_in),"pollSeconds": poll_seconds,"sendCode": say("asking.send_code", &[]),"cancel": say("asking.cancel", &[]),"handoff": {"deviceId": device_id,"vaultKey": vault_key.map(|k| URL_SAFE_NO_PAD.encode(k)),"nonce": URL_SAFE_NO_PAD.encode(nonce), }, }))}/// `personal.askPoll`: where the ask stands. Opened by a signed-in device, this device reveals its nonce and shows/// the code; approved, the credential is claimed with this device's key.pubfn poll(address: &ObjectAddress, exchange: &dynExchange, signer: &dynDeviceSigner, ask_id: &str) -> Result<Value, MethodError> {let answer = address.send(exchange, "POST", POLL, Vec::new(), Some(&json!({ "ask_id": ask_id })))?;let state = answer["state"].as_str().unwrap_or("expired");let ended = |state: &str, line: &str| { forget(ask_id); json!({ "state": state, "done": true, "line": say(line, &[]), "again": say("asking.again", &[]), "sendCode": say("asking.send_code", &[]) }) };match state {"waiting" => {let (left, known, code) = {let held = pending().lock().map_err(|_| MethodError::new("internal_error", "the ask's state is unreadable"))?;let mine = held.get(ask_id); (mine.map(|p| p.deadline.saturating_duration_since(Instant::now()).as_secs() as i64), mine.is_some(), mine.and_then(|p| p.code.clone())) };if !known {// This process did not make the ask (the app restarted): its nonce is gone, so it cannot show a code.returnOk(ended("expired", "asking.lost")); }let code = match (code, answer["nonce_b"].as_str().and_then(bytes32)) { (Some(code), _) => Some(code), (None, Some(nonce_b)) => Some(reveal(address, exchange, ask_id, &nonce_b)?), (None, None) => None, };letmut said = json!({ "state": "waiting", "done": false });match code {Some(code) => {let shown = shown_code(&code); said["code"] = json!(shown); said["line"] = json!(say("asking.type", &[])); said["check"] = json!(say("asking.never", &[])); }None => said["line"] = json!(say("asking.open", &[])), }ifletSome(left) = left { said["left"] = json!(left_line(left)); }let _ = signer;Ok(said) }"approved" => {let challenge = answer["challenge"].as_str().filter(|c| !c.is_empty()).ok_or_else(|| MethodError::new("refused", "the Worker sent no challenge"))?;let sig = signer.sign(claim_statement(ask_id, challenge).as_bytes()).map_err(|reason| MethodError::new("device_key_unreadable", reason))?;let claimed = address.send(exchange, "POST", CLAIM, Vec::new(), Some(&json!({ "ask_id": ask_id, "sig": URL_SAFE_NO_PAD.encode(sig) })))?;let credential = claimed["credential"].as_str().filter(|c| !c.is_empty()).ok_or_else(|| MethodError::new("refused", "the object granted no credential"))?;let database = claimed["database_id"].as_str().filter(|id| !id.is_empty()).ok_or_else(|| MethodError::new("no_database_id", "the sign-in named no database"))?; forget(ask_id);Ok(json!({"state": "approved","done": true,"line": say("asking.approved", &[]),"credential": credential,"person": claimed["person"],"expiresIn": claimed["expires_in"],"databaseId": database, })) }"refused" => {letmut said = ended("refused", "asking.refused");// Three wrong codes ended it, not a person's No (GETTING-IN.md).if answer["why"].as_str() == Some("wrong") { said["why"] = json!("wrong"); }Ok(said) }"used" => Ok(ended("used", "asking.used")), _ => Ok(ended("expired", "asking.expired")), }}/// The approver's nonce is in: say this device's own, and work out the code.fn reveal(address: &ObjectAddress, exchange: &dynExchange, ask_id: &str, nonce_b: &[u8; 32]) -> Result<String, MethodError> {let (device, vault_key, nonce) = {let held = pending().lock().map_err(|_| MethodError::new("internal_error", "the ask's state is unreadable"))?;let mine = held.get(ask_id).ok_or_else(|| MethodError::new("ask_expired", say("asking.lost", &[])))?; (mine.device_id, mine.vault_key, mine.nonce) }; address.send(exchange, "POST", REVEAL, Vec::new(), Some(&json!({ "ask_id": ask_id, "nonce": URL_SAFE_NO_PAD.encode(nonce) })))?;let code = sas_of(&device, vault_key.as_ref().map(|k| k.as_slice()), &nonce, nonce_b);ifletOk(mut held) = pending().lock() {ifletSome(mine) = held.get_mut(ask_id) { mine.code = Some(code.clone()); } }Ok(code)}// ── the approving device ──────────────────────────────────────────────────/// Lets an approved device into the vault: the vault's key, opened with this device's own (`privateKey`, after the/// phone's lock), wrapped for the key the code vouched for.pubtraitVaultAdmit {fn admit(&self, device_id: &str, public_key: &str, name: Option<&str>, private_key: &[u8; 32]) -> Result<(), MethodError>;/// Asked before an approval is sent (coordinator, 22 Nov 2026: "the phone never says Approved unless the key was/// handed over"): whether this phone will hand the key over with `private_key`. `Ok(false)`: there is no key to/// hand (a test's vault, an approval with no lent key where none is kept); an error: it cannot, so nothing is/// approved.fn holds(&self, private_key: Option<&[u8; 32]>) -> Result<bool, MethodError> {Ok(private_key.is_some()) }}structClientVault<'a>(&'a crate::shell::client::ClientController);implVaultAdmitforClientVault<'_> {fn admit(&self, device_id: &str, public_key: &str, name: Option<&str>, private_key: &[u8; 32]) -> Result<(), MethodError> {let client = self.0;ifletSome(sentence) = client.write_refusal() {returnErr(MethodError::new(super::vault::REFUSED_DEVICE, sentence)); }let (vmk, version) = super::vault::opened_vmk(client, private_key)?;super::vault::write(client, "signin.approve", &mut |ctx| cotton_client::vault::devices::admit(ctx, device_id, public_key, name, &vmk, version)).map(|_| ()) }/// On a phone the key is always handed over, so the phone's lock lends this device's own key first; without it/// nothing is approved.fn holds(&self, private_key: Option<&[u8; 32]>) -> Result<bool, MethodError> {let secret = private_key.ok_or_else(|| MethodError::new("key_needed", say("getting_in.key_needed", &[])))?;ifletSome(sentence) = self.0.write_refusal() {returnErr(MethodError::new(super::vault::REFUSED_DEVICE, sentence)); }super::vault::opened_vmk(self.0, secret).map(|_| true) }}/// Approves `ask` with `body` and hands the key over, saying Approved only once the key is there (coordinator,/// 22 Nov 2026). The key is opened before the approval is sent, so a phone that cannot open it approves nothing; a/// device whose app sent no key of its own is told to update first; a hand-over that fails after the approval says/// so, in words that never say Approved.fn hand_over(door: &ObjectDoor, ask: &Held, body: Value, request: &Value, vault: &dynVaultAdmit, kind: &str) -> Result<Value, MethodError> {let secret = match request.get("privateKey") {Some(_) => Some(super::vault::private_key_arg(request)?),None => None, };let holds = vault.holds(secret.as_ref())?;if holds && ask.vault_key.is_none() {returnErr(MethodError::new("update_app", say("getting_in.old_app", &[("kind", kind)]))); } door.send("POST", APPROVE, Some(&body)).map_err(|refusal| refused_in_words(refusal, kind))?;let (Some(key), Some(secret), true) = (&ask.vault_key, secret, holds) else {returnOk(json!({ "ok": true, "vault": false, "said": say("waiting.approved", &[("name", &ask.name)]) })); };match vault.admit(&ask.device_id, key, Some(&ask.name), &secret) {Ok(()) => Ok(json!({ "ok": true, "vault": true, "said": say("getting_in.done", &[("kind", kind)]) })),Err(refusal) => { tracing::warn!("approved, the key not handed over: {}", refusal.code);Err(MethodError::new("not_handed", say("getting_in.not_handed", &[("kind", kind)]))) } }}/// One ask as the object holds it, the code worked out where it can be.structHeld { ask_id: String, device_id: String, vault_key: Option<String>, name: String,/// What it says it is (`mac`, `iphone`, `ipad`, `android`, `computer`), from an app since 22 Nov 2026. kind: Option<String>, commit: Option<String>, nonce_b: Option<String>, reveal: Option<String>, asked_at: i64, expires_at: i64,}implHeld {fn of(ask: &Value) -> Option<Self> {let field = |name: &str| ask[name].as_str().map(str::trim).filter(|v| !v.is_empty()).map(str::to_string);Some(Held { ask_id: field("ask_id")?, device_id: field("device_id").unwrap_or_default(), vault_key: field("vault_key"), name: field("device_name").unwrap_or_else(|| say("waiting.unnamed", &[])), kind: field("device_kind"), commit: field("commit"), nonce_b: field("nonce_b"), reveal: field("reveal"), asked_at: ask["asked_at"].as_i64().unwrap_or(0), expires_at: ask["expires_at"].as_i64()?, }) }/// The code, once the asking device revealed a nonce that hashes to its commit; `None` before, or when what the/// object holds does not add up (never drawn as comparable).fn code(&self) -> Option<String> {let device = bytes32(&self.device_id)?;let vault = match &self.vault_key {Some(key) => Some(bytes32(key)?),None => None, };let reveal = bytes32(self.reveal.as_deref()?)?;let nonce_b = bytes32(self.nonce_b.as_deref()?)?;let commit = bytes32(self.commit.as_deref()?)?;if commit_of(&device, vault.as_ref().map(|k| k.as_slice()), &reveal) != commit {returnNone; }Some(sas_of(&device, vault.as_ref().map(|k| k.as_slice()), &reveal, &nonce_b)) }}fn held(door: &ObjectDoor) -> Result<(i64, Vec<Held>), MethodError> {let (now, asks, holds) = every_ask(door)?;// A device that cannot open the person's things itself lets nobody in (GETTING-IN.md): it is never offered an// Approve that could not work. An object from before says nothing, and holds.Ok((now, if holds { asks } else { Vec::new() }))}/// The object's live asks, and whether this device opens the person's things itself.fn every_ask(door: &ObjectDoor) -> Result<(i64, Vec<Held>, bool), MethodError> {let answer = door.send("GET", APPROVALS, None)?;let now = answer["now"].as_i64().unwrap_or_else(now_seconds);let holds = answer["holds"].as_bool() != Some(false);let asks = answer["asks"].as_array().map(|asks| asks.iter().filter_map(Held::of).filter(|a| a.expires_at >= now).collect()).unwrap_or_default();Ok((now, asks, holds))}/// The word for what an ask's device is ("Mac"), or `None` when it did not say.fn kind_word(kind: Option<&str>) -> Option<String> {let kind = kind?; resolve("signin", &format!("getting_in.kind.{kind}"), &[], &[]).filter(|word| !word.is_empty())}/// A refusal of the object's, said in the person's words where there are some.fn refused_in_words(refusal: MethodError, kind: &str) -> MethodError {match refusal.code.as_str() {"approver_locked" => MethodError::new("approver_locked", say("getting_in.locked", &[])),"ask_expired" | "ask_decided" | "no_such_ask" => MethodError::new(&refusal.code, say("getting_in.gone", &[])),"wrong_scan" => MethodError::new("scan_wrong", say("getting_in.scan_wrong", &[("kind", kind)])), _ => refusal, }}fn find(door: &ObjectDoor, ask_id: &str) -> Result<Held, MethodError> { held(door)?.1.into_iter().find(|a| a.ask_id == ask_id).ok_or_else(|| MethodError::new("no_such_ask", say("waiting.gone", &[])))}/// The approving side through a named door, at `now` (unix seconds) when the object names no time.pubfn over(door: &ObjectDoor, method: &str, request: &Value, now: i64, vault: &dynVaultAdmit) -> Result<Value, MethodError> {match method {"signin.asks" => {// Only looks: nothing is set on an ask until a person taps (`signin.show`), so the asking device's screen// says nothing of whether this phone is open.let (at, asks, holds) = every_ask(door)?;let at = if at > 0 { at } else { now };if !holds {// OWNER.md (22 Nov 2026): a device that cannot hand over the key never offers to approve, and says// why and what to do, in one line, with no button.letmut card = waiting_card(&[], at);ifletSome(ask) = asks.first() {let kind = kind_word(ask.kind.as_deref()).unwrap_or_else(|| say("getting_in.this_device", &[])); card["cannot"] = json!({ "askId": ask.ask_id, "title": match kind_word(ask.kind.as_deref()) { Some(word) => say("getting_in.card_title", &[("kind", &word)]), None => say("getting_in.card_title_unnamed", &[]) }, "line": say("getting_in.cannot", &[("kind", &kind)]) }); }returnOk(card); }Ok(waiting_card(&asks, at)) }"signin.show" => {// "This is me, show the code": this device's nonce, set once, so the asking device can show its code.let ask_id = text(request, "askId")?;let (at, mut asks) = held(door)?;let at = if at > 0 { at } else { now };let ask = asks.iter_mut().find(|a| a.ask_id == ask_id).ok_or_else(|| MethodError::new("no_such_ask", say("waiting.gone", &[])))?;if ask.nonce_b.is_none() {let kind = kind_word(ask.kind.as_deref()).unwrap_or_else(|| say("getting_in.this_device", &[]));let set = door.send("POST", NONCE, Some(&json!({ "ask_id": ask.ask_id, "nonce": URL_SAFE_NO_PAD.encode(fresh32()) }))).map_err(|refusal| refused_in_words(refusal, &kind))?; ask.nonce_b = set["nonce_b"].as_str().map(str::to_string); }Ok(waiting_card(&asks, at)) }"signin.approve"if request.get("scanned").is_some() => approve_scanned(door, request, vault),"signin.approve" => {let ask = find(door, text(request, "askId")?)?;let name = ask.name.clone();let code = ask.code().ok_or_else(|| MethodError::new("not_compared", say("waiting.opening", &[("name", &name)])))?;let typed: String = text(request, "code")?.chars().filter(char::is_ascii_digit).collect();if typed != code {// A refusal's words pass the failure filter (cotton_core::failure), which blanks a word shaped like a// code name: an Android emulator calls itself `sdk_gphone64_x86_64`, and "That isn't the code on// sdk_gphone64_x86_64" was read as "That didn't work. Try again." (walk on dev, 22 Nov 2026). The// device's name is said with its underscores as spaces.let name = name.replace('_', " ");// The object counts it, for every device of the number and across restarts; the last try ends the ask.let counted = door.send("POST", WRONG, Some(&json!({ "ask_id": ask.ask_id })))?;if counted["ended"].as_bool() != Some(false) {returnErr(MethodError::new("code_ended", say("waiting.ended", &[("name", &name)]))); }let left = counted["left"].as_u64().unwrap_or(0).to_string();returnErr(MethodError::new("code_wrong", say("waiting.wrong", &[("name", &name), ("n", &left)]))); }let kind = kind_word(ask.kind.as_deref()).unwrap_or_else(|| say("getting_in.this_device", &[])); hand_over(door, &ask, json!({ "ask_id": ask.ask_id }), request, vault, &kind) }"signin.refuse" => {let ask_id = text(request, "askId")?;let name = request.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| say("waiting.unnamed", &[])); door.send("POST", REFUSE, Some(&json!({ "ask_id": ask_id })))?;Ok(json!({ "ok": true, "said": say("waiting.refused", &[("name", &name)]) })) }"signin.siblingTicket" => Ok(json!({ "ticket": mint_ticket(text(request, "askId")?) })),"signin.approveSibling" => approve_sibling(door, request, vault), other => Err(MethodError::new("unknown_method", format!("`{other}` is not a sign-in approval method"))), }}/// `signin.approve {askId, scanned, privateKey?}`: the person scanned the new device's square code with this app's own/// camera (GETTING-IN.md). The text names the ask and the nonce it committed to; the ask must be the card's, and the/// nonce must hash, with the device and vault key the object relays, to the commit the ask was made with, checked/// HERE, so a server that swapped either key is caught before anything is approved or wrapped. A scan of another/// screen is refused `scan_wrong` and spends no try: it is not a guess at a secret.fn approve_scanned(door: &ObjectDoor, request: &Value, vault: &dynVaultAdmit) -> Result<Value, MethodError> {let ask_id = text(request, "askId")?;let ask = find(door, ask_id)?;let kind = kind_word(ask.kind.as_deref()).unwrap_or_else(|| say("getting_in.this_device", &[]));let wrong = || MethodError::new("scan_wrong", say("getting_in.scan_wrong", &[("kind", &kind)]));let (scanned_ask, nonce) = cotton_core::vault::approval::read_scan(text(request, "scanned")?).ok_or_else(wrong)?;if scanned_ask != ask.ask_id {returnErr(wrong()); }let (Some(device), Some(commit)) = (bytes32(&ask.device_id), ask.commit.as_deref().and_then(bytes32)) else {returnErr(wrong()); };let vault_bytes = match &ask.vault_key {Some(key) => Some(bytes32(key).ok_or_else(wrong)?),None => None, };if commit_of(&device, vault_bytes.as_ref().map(|k| k.as_slice()), &nonce) != commit {returnErr(wrong()); } hand_over(door, &ask, json!({ "ask_id": ask.ask_id, "scanned": URL_SAFE_NO_PAD.encode(nonce) }), request, vault, &kind)}/// `signin.approveSibling`: a Cotton app on this same phone hands over the ask it just made, and this app approves it/// with NO CODE AND NO PRESENCE, and with this device's vault key (`privateKey`) lets it into the vault too.////// THIS IS SAFE ONLY BECAUSE THE CHANNEL IS CHECKED (19 Nov 2026). Its arguments are a stranger's/// to know: anyone may make an ask for any number and hold its id, device, vault key and nonce, so a URL or an intent/// carrying them would let a stranger in on one tap of the owner's. So this refuses (`not_the_channel`) unless the/// request carries a `ticket` that `signin.siblingTicket` minted in this process for this very ask, unspent and under/// TICKET_SECONDS old. The one caller of `signin.siblingTicket` is Android's `SiblingKeys` provider, after the/// platform's `checkSignatures` says the asking app is signed by Cotton's key; it hands the ticket to that app alone,/// which hands it back with the ask. A URL, a deep link or an intent from another signer has no ticket, and cannot/// get one (apps/android `SiblingKeysChannelTest` keeps both calls inside that checked branch). iPhone has no such/// channel over URLs and must never call this from one (its shared keychain group makes the hand-off unneeded).fn approve_sibling(door: &ObjectDoor, request: &Value, vault: &dynVaultAdmit) -> Result<Value, MethodError> {let ask_id = text(request, "askId")?;let ticket = request.get("ticket").and_then(Value::as_str).unwrap_or_default();if !spend_ticket(ticket, ask_id) {returnErr(MethodError::new("not_the_channel", "only a Cotton app on this phone, through its checked channel, hands over an ask")); }let ask = find(door, ask_id)?;let device = text(request, "deviceId")?;let vault_key = request.get("vaultKey").and_then(Value::as_str).map(str::trim).filter(|k| !k.is_empty()).map(str::to_string);let nonce = text(request, "nonce")?;let named = |held: Option<&str>, given: Option<&str>| held == given;let (Some(device_bytes), Some(nonce_bytes), Some(commit)) = (bytes32(device), bytes32(nonce), ask.commit.as_deref().and_then(bytes32)) else {returnErr(MethodError::new("not_that_ask", "the ask this phone holds is not the one the app asked with")); };let vault_bytes = match &vault_key {Some(key) => Some(bytes32(key).ok_or_else(|| MethodError::new("bad_request", "`vaultKey` is 32 bytes, base64url without padding"))?),None => None, };// The object's ask must be the very one the app on this phone made: same device, same vault key, same commit.if ask.device_id != device || !named(ask.vault_key.as_deref(), vault_key.as_deref()) || commit_of(&device_bytes, vault_bytes.as_ref().map(|k| k.as_slice()), &nonce_bytes) != commit {returnErr(MethodError::new("not_that_ask", "the ask this phone holds is not the one the app asked with")); }if ask.nonce_b.is_none() { door.send("POST", NONCE, Some(&json!({ "ask_id": ask.ask_id, "nonce": URL_SAFE_NO_PAD.encode(fresh32()) })))?; } door.address.send(door.exchange.as_ref(), "POST", REVEAL, Vec::new(), Some(&json!({ "ask_id": ask.ask_id, "nonce": nonce })))?; door.send("POST", APPROVE, Some(&json!({ "ask_id": ask.ask_id })))?;let secret = match request.get("privateKey") {Some(_) => Some(super::vault::private_key_arg(request)?),None => None, };let opened = match (&ask.vault_key, secret) { (Some(key), Some(secret)) => match vault.admit(&ask.device_id, key, Some(&ask.name), &secret) {Ok(()) => true,Err(refusal) => { tracing::warn!("sibling approved, vault not opened for it: {}", refusal.code);false } }, _ => false, };Ok(json!({ "ok": true, "vault": opened }))}/// The card over the object's waiting asks: oldest first, each with who, where its codes stand and the time. Never/// the code itself: it is typed here, from the other screen.fn waiting_card(asks: &[Held], now: i64) -> Value {let waiting: Vec<Value> = asks.iter().map(|ask| one_ask(ask, now)).collect();// Fast only while an ask a person opened waits for the asking device's reveal.let opening = asks.iter().any(|ask| ask.nonce_b.is_some() && ask.code().is_none()); json!({ "waiting": waiting, "pollSeconds": if opening { OPENING_POLL_SECONDS } else { ASKS_POLL_SECONDS } })}fn one_ask(ask: &Held, now: i64) -> Value {let name = &ask.name;let minutes_ago = ((now - ask.asked_at).max(0)) / 60;let ago = if minutes_ago == 0 { say("waiting.ago.now", &[]) } else { say("waiting.ago", &[("n", &minutes_ago.to_string())]) };let left = left_line(ask.expires_at - now);let compare = ask.code().is_some();let phase = if compare {"compare" } elseif ask.nonce_b.is_some() {"opening" } else {"asked" };let typed = match phase {"compare" => say("waiting.type", &[("name", name)]),"opening" => say("waiting.opening", &[("name", name)]), _ => say("waiting.asked", &[("name", name)]), };letmut said = json!({"askId": ask.ask_id,"name": name,"phase": phase,"askedAt": ask.asked_at,"expiresAt": ask.expires_at,"line": say("waiting.line", &[("name", name)]),"type": typed,"never": say("waiting.never", &[("name", name)]),"digits": 6,"vault": ask.vault_key.is_some(),"when": say("waiting.when", &[("ago", &ago), ("left", &left)]),"approve": say("waiting.approve", &[]),"refuse": say("waiting.refuse", &[]),"confirm": say("waiting.confirm", &[("name", name)]), });if phase == "asked" { said["show"] = json!(say("waiting.show", &[])); }// The one card of GETTING-IN.md: who asks, in the person's words, Approve (which scans) and Not me.let kind = kind_word(ask.kind.as_deref());let kind_or = kind.clone().unwrap_or_else(|| say("getting_in.this_device", &[])); said["kind"] = json!(ask.kind); said["title"] = json!(match &kind {Some(kind) => say("getting_in.card_title", &[("kind", kind)]),None => say("getting_in.card_title_unnamed", &[]), }); said["sub"] = json!(say("getting_in.card_line", &[("name", name), ("ago", &ago)])); said["approve"] = json!(say("getting_in.approve", &[])); said["notMe"] = json!(say("getting_in.not_me", &[])); said["notMeConfirm"] = json!(say("getting_in.not_me_confirm", &[("kind", &kind_or)])); said["notMeDone"] = json!(say("getting_in.not_me_done", &[("kind", &kind_or)])); said["scan"] = json!({"heading": say("getting_in.scan_heading", &[("kind", &kind_or)]),"typeInstead": say("getting_in.type_instead", &[]),"none": say("getting_in.scan_none", &[]), }); said["typeHeading"] = json!(say("getting_in.type_heading", &[("kind", &kind_or)]));if phase == "opening" { said["typeWaiting"] = json!(say("getting_in.waiting_digits", &[("kind", &kind_or)])); } said["notify"] = json!({"title": said["title"].clone(),"body": say("getting_in.notify_body", &[("name", name)]), }); said}#[cfg(test)]#[path = "signin_approval_tests.rs"]mod tests;