//! What this device remembers about being refused — and it only ever //! remembers a NO. //! //! The port of `apps/cotton/src/replica/deviceRefusal.ts`. Three pieces of //! state, and each exists because of a specific failure: //! //! * **A standing terminal refusal.** `device_not_approved`, `device_revoked`, //! `device_bad_signature`, `no_device_key`: four answers nothing this phone //! does will change. Once one is recorded, every OWNER route is refused //! WITHOUT SENDING — retrying a refusal nothing has changed is a battery, //! not a fix. //! //! **Only the two that are DECISIONS are written down** ([`RefusalKind::is_a_decision`]): //! `device_not_approved` and `device_revoked` are somebody's answer about //! this device's row, so a relaunch paints the sentence rather than a //! spinner. `device_bad_signature` and `no_device_key` are infrastructure — //! a server verifying against an origin it was not reached on, a Keychain //! that was locked at launch — and persisting one made a single bad request //! permanent: every later launch refused locally, before sending, telling //! the person to pair a phone their server still lists as approved. Those //! two gate this process and a fresh launch asks once more. //! //! **The phone persists a NO, never a yes**: there is no "approved" flag //! anywhere, because the server's device row is the only record of who is //! in. //! * **A clock offset per origin.** Learned from a `403 device_clock`, kept in //! memory only, so the next launch asks again rather than trusting an //! afternoon-old correction. //! * **A clock hold per origin.** A second `device_clock` in one chain holds //! THAT origin for a minute: two corrections that both failed means the //! drift is not something a retry fixes. Per origin, because a Mac with a //! bad clock must not stop the phone talking to a relay. //! //! **The dedupe rule.** The same terminal kind from the same server keeps the //! FIRST note; a different kind, or the same kind from a DIFFERENT server, //! replaces it. Join pre-fills its server field from the note, so the most //! recent refuser is the one to offer. "The same server" is the address AND //! the machine ([`Refuser`]). //! //! **A terminal note belongs to the MACHINE that said it, not to the name.** A //! household is one relay name and the relay hands it to whichever Mac is //! active, so the address stays the same when the server behind it changes. //! On 2026-09-28 a stale Mac held the name for sixty seconds and answered //! a headless server's peer sync `403 device_not_approved` — its copy had not //! caught up with the approval — and that note stopped the headless server for //! two hours without once asking the Mac that had it approved. So a note records //! [`Refuser`], and the transport (`signed_http.rs`, the gate) asks the name //! who answers it now: the same machine gets the same verdict without being //! asked again, and a DIFFERENT machine is asked once. //! //! **A note is about ONE DATABASE** ([`NoteKey`]). A device syncs Mine and any //! number of places, and a refusal in a place is a refusal of this device in //! THAT file: it stops that place's loop and nothing else. Mine's note is the //! one that decides the device — the boot gate, the live socket, the erase — //! and a place's note can never ask for an erase: only Mine's answer can wipe //! this device. use std::collections::{BTreeMap, HashMap}; use std::path::{Path, PathBuf}; use std::sync::Mutex; use serde::{Deserialize, Serialize}; /// How long one origin is held after two `device_clock` refusals in a row. pub const CLOCK_HOLD_MS: i64 = 60_000; /// How long the gate takes "the same machine still answers this name" as the /// answer before it asks again. /// /// A minute — the peer-sync timer's own order of magnitude — so a caller that /// asks many times a second while a note stands costs one `GET /health` a /// minute, not one per call, and a name that has moved is noticed within one. pub const ANSWERER_QUIET_MS: i64 = 60_000; /// The five ways a device is refused, as the phone files them. /// /// The names are the phone's (`deviceRefusal.ts`); the CODES are the server's, /// and `no_device_key` is this tree's spelling of the phone's /// `device_key_unreadable` — the screen maps both to one sentence. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum RefusalKind { NotApproved, Revoked, BadSignature, KeyUnreadable, /// The one non-terminal kind: a clock is something a person fixes and then /// everything works again. Clock, } impl RefusalKind { pub fn is_terminal(self) -> bool { !matches!(self, RefusalKind::Clock) } /// Is this a DECISION somebody made about this device — the only kind that /// is written down? /// /// **Terminal and persisted are not the same question, and conflating them /// is what kept a phone at the Join screen for ever.** All four terminal /// kinds stop the loop for THIS process, because retrying a refusal that /// nothing has changed is a battery. Only two of them are a decision a /// person has to reverse: /// /// * `NotApproved` and `Revoked` are the server's answer about a device /// row. Nothing this phone can do changes them, so they are written to /// `refusal.json` and a relaunch paints the sentence rather than a /// spinner. /// * `BadSignature` and `KeyUnreadable` are INFRASTRUCTURE. A 401 /// `device_bad_signature` is also what a server answers while it is /// verifying against an origin it was not reached on (`deps.origins()` /// — `COTTON_PUBLIC_URL` plus the loopback and the relay), and /// `no_device_key` is a Keychain that was locked at the moment the app /// started. Writing either one down makes ONE bad request permanent: /// every later launch refuses locally, before sending, and the person is /// told to pair a phone that is still approved on their server. So they /// gate within the process and a fresh launch asks once more. pub fn is_a_decision(self) -> bool { matches!(self, RefusalKind::NotApproved | RefusalKind::Revoked) } /// The kind a server refusal code files under, or `None` for a code this /// module has no opinion about. pub fn of_code(code: &str) -> Option { match code { "device_not_approved" => Some(RefusalKind::NotApproved), "device_revoked" => Some(RefusalKind::Revoked), "device_bad_signature" => Some(RefusalKind::BadSignature), // Both spellings, because the client and the phone named the same // state differently and a note written by either must read back. "no_device_key" | "device_key_unreadable" => Some(RefusalKind::KeyUnreadable), "device_clock" => Some(RefusalKind::Clock), _ => None, } } pub fn as_str(self) -> &'static str { match self { RefusalKind::NotApproved => "not_approved", RefusalKind::Revoked => "revoked", RefusalKind::BadSignature => "bad_signature", RefusalKind::KeyUnreadable => "key_unreadable", RefusalKind::Clock => "clock", } } } /// Which machine gave a note — the server's own tag /// (`cotton_core::device::server_id`), read off the answer that refused. /// /// Three states rather than an `Option`, because "an older build wrote this and /// never looked" and "this build looked and the server did not say" are /// different facts and the gate treats them differently: /// /// * [`Refuser::Unrecorded`] — absent from the file: a note an older build /// wrote. It is STALE after one retry: the next owner request goes out once, /// and whatever answers it writes a note that is not this one. Never a loop, /// because this build never writes this state. /// * [`Refuser::Unnamed`] — this build recorded it and the answer carried no /// tag (a server older than the header). Compared as "no name", so a machine /// that DOES name itself is a different machine. /// * [`Refuser::Server`] — the tag the refusing machine sent. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Refuser { #[default] Unrecorded, Unnamed, Server(String), } impl Refuser { /// What an answer's [`cotton_core::device::server_id::SERVER_ID_HEADER`] /// said. A blank header said nothing. pub fn of_header(value: Option<&str>) -> Refuser { match value.map(str::trim).filter(|value| !value.is_empty()) { Some(tag) => Refuser::Server(tag.to_string()), None => Refuser::Unnamed, } } /// The machine's tag, when one was recorded. pub fn tag(&self) -> Option<&str> { match self { Refuser::Server(tag) => Some(tag), Refuser::Unrecorded | Refuser::Unnamed => None, } } /// Is `answering` — the tag the name answers with NOW — a different machine /// from the one that gave this note? /// /// Only a machine that NAMES itself can be told apart: a name that answers /// with no tag might be the same machine, so it is not a reason to ask /// again. An [`Refuser::Unrecorded`] note is not judged here at all — it /// gets its one retry without the question. pub fn is_other_than(&self, answering: Option<&str>) -> bool { match answering { Some(answering) => self.tag() != Some(answering), None => false, } } } /// A standing refusal, as it is held and as it is written down. /// /// Nothing localised is stored: the SENTENCE is rebuilt from the code, so it /// follows whatever the app reads today rather than whatever it read the /// afternoon the refusal happened. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DeviceRefusal { pub kind: RefusalKind, /// The server's own code, kept because the screen keys on it. pub code: String, /// Which server refused. `None` for a refusal about this device's own key, /// which no server was asked about. pub server_url: Option, pub server_name: Option, /// When, ISO-8601 UTC. pub at: String, /// Did the server ask this device to ERASE ITSELF rather than to stop? /// /// `DELETE /v1/devices/approved/{id}` with `{"erase": true}` files the row /// as `revoked_reason = "erased"`, and the chokepoint's `403 /// device_revoked` then carries `"erase": true` — so the first request this /// device makes after somebody wiped it from another device is the request /// that tells it. /// /// **It changes what a screen offers, not what this module decides.** A /// revocation is still a DECISION ([`RefusalKind::is_a_decision`]) and is /// still written down; the flag is the difference between drawing two verbs /// — *Keep my copy* and *Erase Cotton from this iPhone* — and taking the /// second one without asking, which is what the owner already answered when /// they ticked the box on the other device. /// /// Absent in a note written by an older build, and absent from a body that /// did not say: `false` is the safe reading, because it asks. #[serde(default)] pub erase: bool, /// THE SERVING EPOCH the refusal named (slice 12): the refusing file's /// latest serving fact's epoch, `None` when it named none. The replica /// takes `erase` only from an epoch it has handed over to /// (`cotton_client::bootstrap::may_erase`), so the note keeps which one it /// was. Always written, `null` included. #[serde(deserialize_with = "nullable_epoch")] pub serving_epoch: Option, /// WHICH MACHINE said it — see [`Refuser`]. Absent in a note an older build /// wrote, which reads back as [`Refuser::Unrecorded`]. #[serde(default)] pub refuser: Refuser, /// WHICH KEY was refused: the device id the refused request was signed /// with. A refusal is of a key, so a device that re-keyed ("Re-key this /// device") reads a note about its replaced key as no note at all — see /// [`RefusalMemory::at_for`]. `None` in a note not made from a signed /// answer, and in one an older build wrote; either stands for every key. #[serde(default, skip_serializing_if = "Option::is_none")] pub device: Option, } // Required in a note, and `null` is a value: through `deserialize_with`, so an // absent key is missing rather than `None`. fn nullable_epoch<'de, D>(deserializer: D) -> Result, D::Error> where D: serde::Deserializer<'de>, { Option::::deserialize(deserializer) } /// Which database a note is about. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum NoteKey { /// The person's own database, and every request that names none. Mine, /// Another database this device syncs, by its id. Place(String), } /// `refusal.json`: Mine's note and each place's, decisions only. #[derive(Debug, Default, Serialize, Deserialize)] struct NoteFile { #[serde(default, skip_serializing_if = "Option::is_none")] mine: Option, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] places: BTreeMap, } /// The whole of what this device remembers about being refused. #[derive(Debug)] pub struct RefusalMemory { /// Where the standing note is written. `None` for a memory nothing /// persists — a test, and the join flow's dry run. path: Option, state: Mutex, } #[derive(Debug, Default)] struct State { /// The note standing against each database, terminal or not. standing: BTreeMap, /// What `refusal.json` holds — the DECISIONS among them. Kept apart from /// `standing` because a note that is not written down must not erase one /// that is. written: BTreeMap, /// `origin → (server_now_ms - this_device_now_ms)`. offsets: HashMap, /// `origin → hold until, epoch ms`. holds: HashMap, /// `origin → epoch ms` until which the gate does not ask that origin again /// who answers it — see [`RefusalMemory::note_same_answerer`]. quiet: HashMap, } impl Default for RefusalMemory { fn default() -> Self { RefusalMemory { path: None, state: Mutex::new(State::default()), } } } impl RefusalMemory { /// A memory that persists its standing note beside the connection record. /// /// Reads it at once: a relaunch has to paint Join before anything asks the /// server, which is exactly what a standing note is for. pub fn at(path: impl Into) -> RefusalMemory { let path = path.into(); let written = read_notes(&path); RefusalMemory { path: Some(path), state: Mutex::new(State { standing: written.clone(), written, ..State::default() }), } } /// [`Self::at`], for the device whose key is `device_id`: a written note /// about ANOTHER key — the key this device replaced when it re-keyed — is /// not this key's refusal, and is dropped from the file as it is read. pub fn at_for(path: impl Into, device_id: &str) -> RefusalMemory { let path = path.into(); let mut written = read_notes(&path); let before = written.len(); written.retain(|_, note| note.device.as_deref().is_none_or(|key| key == device_id)); let memory = RefusalMemory { path: Some(path), state: Mutex::new(State { standing: written.clone(), written, ..State::default() }), }; if memory.state().written.len() != before { let written = memory.state().written.clone(); memory.persist(&written); } memory } fn state(&self) -> std::sync::MutexGuard<'_, State> { self.state .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// MINE's standing note, terminal or not. pub fn standing(&self) -> Option { self.standing_for(&NoteKey::Mine) } /// MINE's note IF it is one that stops the loop for good — the note that /// decides the device: the boot gate, the live socket and the erase. pub fn standing_terminal(&self) -> Option { self.standing().filter(|note| note.kind.is_terminal()) } /// The note standing against one database, terminal or not. Its own note /// only — a place's answer does not include Mine's. pub fn standing_for(&self, key: &NoteKey) -> Option { self.state().standing.get(key).cloned() } /// The terminal note that stops a request about `key`. /// /// For a place it is Mine's when Mine has one — a device refused in its /// own database is refused everywhere — and otherwise the place's own. pub fn standing_terminal_for(&self, key: &NoteKey) -> Option { let terminal = |key: &NoteKey| { self.standing_for(key) .filter(|note| note.kind.is_terminal()) }; match key { NoteKey::Mine => terminal(&NoteKey::Mine), NoteKey::Place(_) => terminal(&NoteKey::Mine).or_else(|| terminal(key)), } } /// Record a refusal of MINE, or clear Mine's note with `None`. pub fn note(&self, next: Option) { self.note_for(NoteKey::Mine, next); } /// Record a refusal about one database, or clear its note with `None`. /// /// The dedupe rule lives here: the same terminal kind from the same server /// keeps the FIRST note, so the `at` a screen shows is when it actually /// happened rather than the last time something asked. /// /// A place's note never carries `erase`, whatever it was handed: only /// Mine's answer can ask this device to wipe itself. pub fn note_for(&self, key: NoteKey, next: Option) { let next = match (&key, next) { (NoteKey::Place(_), Some(note)) => Some(DeviceRefusal { erase: false, ..note }), (_, next) => next, }; let write = { let mut state = self.state(); if next.is_none() { // Clearing lifts every hold with it: the person has just // joined, or fixed the clock, and holding an origin from // before that would refuse the first request of the new state. state.holds.clear(); } let keep_first = match (state.standing.get(&key), &next) { (Some(current), Some(next)) => { next.kind.is_terminal() && current.kind == next.kind && current.server_url == next.server_url && current.refuser == next.refuser } _ => false, }; if keep_first { return; } match &next { Some(note) => { state.standing.insert(key.clone(), note.clone()); } None => { state.standing.remove(&key); } } // A new note, or none: whatever the gate learned about who answers // was learned about the OLD one. state.quiet.clear(); // A DECISION is written down. Everything else is remembered for // this process only — and, just as deliberately, is not allowed to // ERASE a decision already on disk: a note that is not written // down is not an opinion about the file either. Only an explicit // CLEAR removes one — a join, or a fixed clock. match &next { Some(note) if note.kind.is_a_decision() => { state.written.insert(key, note.clone()); Some(state.written.clone()) } Some(_) => None, None => state.written.remove(&key).map(|_| state.written.clone()), } }; if let Some(written) = write { self.persist(&written); } } /// What THIS origin's clock is offset by, in milliseconds. `0` when /// nothing has been learned. pub fn clock_offset_ms(&self, origin: &str) -> i64 { self.state().offsets.get(origin).copied().unwrap_or(0) } /// Learn an origin's clock from what it said about itself. pub fn note_server_clock(&self, origin: &str, server_ms: i64, now_ms: i64) { self.state() .offsets .insert(origin.to_string(), server_ms - now_ms); } /// Is this origin held, and until when? pub fn clock_hold_until(&self, origin: &str) -> Option { self.state().holds.get(origin).copied() } pub fn note_clock_hold(&self, origin: &str, until_ms: i64) { self.state().holds.insert(origin.to_string(), until_ms); } pub fn clear_clock_hold(&self, origin: &str) { self.state().holds.remove(origin); } /// Has the gate recently learned that THIS origin is still answered by the /// machine the note is about (or could not tell)? Then it does not ask /// again yet. pub fn answerer_is_quiet(&self, origin: &str, now_ms: i64) -> bool { self.state() .quiet .get(origin) .is_some_and(|until| now_ms < *until) } /// The gate asked who answers `origin` and it was the machine that gave /// the note, or nobody said: don't ask again for [`ANSWERER_QUIET_MS`]. pub fn note_same_answerer(&self, origin: &str, now_ms: i64) { self.state() .quiet .insert(origin.to_string(), now_ms + ANSWERER_QUIET_MS); } /// The one retry an older build's note gets has been ANSWERED — by some /// server, with some status — so Mine's note is no longer stale. pub fn spend_stale_retry(&self) { self.spend_stale_retry_for(&NoteKey::Mine); } /// The one retry an older build's note gets has been ANSWERED — by some /// server, with some status — so the note is no longer stale. /// /// [`Refuser::Unrecorded`] becomes [`Refuser::Unnamed`], written down, and /// the gate never lets it out unasked again: one fresh attempt, never a /// loop. A note that is not unrecorded is left exactly as it is — a refusal /// on that retry has already replaced it with its own. pub fn spend_stale_retry_for(&self, key: &NoteKey) { let written = { let mut state = self.state(); let spent = match state.standing.get_mut(key) { Some(note) if note.refuser == Refuser::Unrecorded => { note.refuser = Refuser::Unnamed; Some(note.clone()) } _ => None, }; match spent { Some(note) if note.kind.is_a_decision() => { state.written.insert(key.clone(), note); Some(state.written.clone()) } _ => None, } }; if let Some(written) = written { self.persist(&written); } } /// What a successful answer from this origin clears. /// /// ONLY the clock: a terminal note survives every 200 here. The one 200 /// that DOES clear a terminal note is the answer to the gate's fresh /// attempt — a different machine, or an older build's stale note — and the /// transport clears that itself (`signed_http.rs`), because only it knows /// the request went out as one. A pairing route's 2xx goes out under every /// note and says nothing about whether this device is admitted. /// /// Every database's clock note goes: the clock is the origin's, and every /// database behind one origin shares it. pub fn note_success(&self, origin: &str) { self.clear_clock_hold(origin); let clocks: Vec = self .state() .standing .iter() .filter(|(_, note)| note.kind == RefusalKind::Clock) .map(|(key, _)| key.clone()) .collect(); for key in clocks { self.note_for(key, None); } } /// Write every decision down, or remove the file when there is none. /// /// Best effort on purpose: losing this file costs one spinner on the next /// launch, and failing a refusal because it could not be written down /// would be worse. fn persist(&self, written: &BTreeMap) { let Some(path) = &self.path else { return; }; if written.is_empty() { // not a copy: the refusals journal. let _ = std::fs::remove_file(path); return; } let mut file = NoteFile::default(); for (key, note) in written { match key { NoteKey::Mine => file.mine = Some(note.clone()), // Belt and braces: `note_for` already refuses a place's erase, // and the file never says one either. NoteKey::Place(id) => { file.places.insert( id.clone(), DeviceRefusal { erase: false, ..note.clone() }, ); } } } if let Some(parent) = path.parent() { let _ = std::fs::create_dir_all(parent); } if let Ok(text) = serde_json::to_string_pretty(&file) { // not a copy: the refusals journal. let _ = std::fs::write(path, text); } } } fn read_notes(path: &Path) -> BTreeMap { let mut notes = BTreeMap::new(); let Some(file) = std::fs::read_to_string(path) .ok() .and_then(|text| serde_json::from_str::(&text).ok()) else { return notes; }; // A note naming a kind this build does not write down is a note from // another era — an older build persisted `device_bad_signature` too — and // it is dropped rather than honoured. Honouring it would refuse every // owner route of this launch on the strength of one infrastructure // failure somebody else's build recorded. if let Some(note) = file.mine.filter(|note| note.kind.is_a_decision()) { notes.insert(NoteKey::Mine, note); } for (id, note) in file.places { if note.kind.is_a_decision() { notes.insert( NoteKey::Place(id), DeviceRefusal { erase: false, ..note }, ); } } notes } #[cfg(test)] #[path = "refusal_tests.rs"] mod tests;