Cotton code
973 lines · 44.4 KB · RustRaw
//! The device row, in the person's own database.//!//! **In `cotton-tools` because the phone links it.** It lived in//! `cotton-server` while a server was the only thing that ever wrote a device//! row; a phone that starts a database alone writes the first one itself//! (`cotton_client::start_local`), and a phone links no server. `cotton-server`//! re-exports this module at its old address, so every caller there reads//! exactly the same writer.//!//! WHO MAY OPEN THIS FILE IS A FACT OF THE FILE. It used to be a row in each//! server's `registry.db`, which was true while exactly one machine ever served//! a life. A household of Macs breaks that: the FILE travels between them and//! the registry does not, so two Macs would hold two answers to "is this phone//! admitted" and the one the phone happened to reach would decide. Version 9 of//! the store put `cotton_devices` in the file for that reason, and this module//! is what reads and writes it.//!//! EVERY WRITE REPLICATES. A row written here goes through//! [`crate::mcp::writer::Writer`] — the same path an assistant's edit//! takes — so it is minted as an op, stamped by this file's author, and//! handed to every other device on the next exchange.//! A row written straight into the table with `INSERT` would be a row only the//! Mac that wrote it ever sees, which is the failure this whole move exists to//! end.//!//! A REVOCATION IS NOT UNDONE BY A PATCH. A revocation is a fact in//! `cotton_revocations` with the row's `revoked_at` as its mirror, both//! written by the one writer (`cotton_store::revocation::revoke`), and the//! fold refuses an op that nulls the mirror (`no_un_revocation`). So//! admitting a key again is a NEW ROW at a new id ([`approval_row_id`]), and//! the revoked row stays beside it as history — a key holds one row per//! APPROVAL (store version 41).//!//! It used to be a delete and a recreation AT THE SAME ID, and that could not//! survive the trip between Macs: a recreation erases its own tombstone, so//! the re-approval reached a Mac still holding the revoked life as a bare//! patch, which `no_un_revocation` refused. On 27 Sep 2026 one approval of//! one Mac left the household's three Macs with three answers. Two approvals//! never share a row.//!//! WHAT STAYED IN `registry.db`: the pairing queue, the nonces, `last_seen_at`//! and the pull cursor. They are facts about ONE machine's traffic, written on//! every request, and a column that rewrites itself per request would put the//! whole household's traffic on the wire. `devices/registry.rs` holds them.use cotton_store::revocation::REPLACED_BY_OF_ROW;use std::sync::Arc;use chrono::{DateTime, Utc};use cotton_store::protocol::derived_id::derived_id;use cotton_store::{Driver, Row};use cotton_core::device::pairing::DevicePlatform;use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use crate::clock::iso;use crate::mcp::writer::Writer;use crate::random::Random;/// The job a device row is written as.const DEVICES_JOB: &str = "devices";/// The `approved_by_device` of the row a server writes for itself at boot.pub const SELF_APPROVER: &str = "self";/// The `approved_by_device` of the row `restore --take-over` writes for the/// Mac it makes the server (architect, 15 Oct 2026): the recovery kit, the/// relay name's rebind and the owner's confirmation are the approval, never the/// Mac itself. Like [`SELF_APPROVER`], the server's own row.pub const RECOVERY_KIT_APPROVER: &str = "recovery-kit";/// The id of ONE APPROVAL of a key — every approval, the first included.////// Derived from the approval's own moment, so each life of a key is its own/// row and a revocation can only ever reach the life it was written about. A/// first approval is not a special id: a re-pair on a Mac that never saw an/// earlier approval must not land on that approval's row, which may be/// revoked where this Mac cannot see it. The OAuth grant's re-consent is the/// same shape (`grant_row_id` derives from `created_at`).pub fn approval_row_id(workspace_id: &str, device_id: &str, approved_at: &str) -> String {    derived_id("cotton_devices", &[workspace_id, device_id, approved_at])}/// Where a new approval of `row`'s key is written: always an id of its own.fn new_life_id(row: &NewDeviceRow) -> String {    approval_row_id(&row.workspace_id, &row.device_id, &row.approved_at)}/// A device revocation's reason as the one writer takes it: the fact's/// `reason` and, for a supersede, the successor it names. The mirror's/// `revoked_reason` is the word itself, or `superseded by <successor>`.fn fact_reason(reason: &str) -> cotton_store::Result<(&str, Option<&str>)> {    if let Some(successor) = reason.strip_prefix("superseded by ") {        return Ok((cotton_store::revocation::SUCCEEDED, Some(successor)));    }    if reason != cotton_store::revocation::SUCCEEDED        && cotton_store::revocation::REASONS.contains(&reason)    {        return Ok((reason, None));    }    Err(cotton_store::StoreError::refused(format!(        "`{reason}` is not a reason a device is revoked for — revoked, erased, lost, stolen, restored, or superseded by <device>"    )))}/// How long the owner's order to make a Mac a runner stands.pub const RUNNER_ORDER_HOURS: i64 = 24;/// One row of `cotton_devices`.////// NO `scope` field: what a device's own key may sign is read on its own by/// [`FileDevices::scope_for`] ([`DeviceScope`]), by the one check that asks.////// NO `last_seen_at` either — it is machine-local and lives in `device_local`./// The two listings that draw it ask [`super::registry::DeviceStore::last_seen`]/// and merge, so nothing can mistake a column of this row for a fact that/// travelled.#[derive(Debug, Clone, PartialEq, Eq)]pub struct DeviceRow {    /// The row's own id — ONE APPROVAL of the key. Every write about a device    /// addresses this, never an id recomputed from the key: a key that was    /// re-approved holds its live row at a different id from its first.    pub id: String,    pub device_id: String,    pub workspace_id: String,    pub name: String,    pub platform: Option<DevicePlatform>,    pub app_version: Option<String>,    pub approved_at: String,    /// Another device's id, or `"self"` for the root row a server writes at    /// boot.    pub approved_by: String,    pub revoked_at: Option<String>,    pub revoked_by: Option<String>,    pub revoked_reason: Option<String>,    /// When the Mac showed the person its recovery key (N-D5) — set on the    /// root row only. `None` everywhere else.    pub recovery_key_shown_at: Option<String>,    /// A MAC's relay identity public key, base64url — the key the household's    /// relay admits it under. `None` on a phone, and on a Mac approved by a    /// build that did not present one.    pub relay_identity_key: Option<String>,    /// WHOSE DEVICE THIS IS (keys, KS0/KS11): `None` is a device of the    /// database's owner; a person key names a member the owner admitted. Written    /// once, by the serving Mac's Admit (KS4); the chokepoint reads it to name    /// the caller `Owner` or `Member`.    pub person_key: Option<String>,}impl DeviceRow {}/// Whether an approval of this row takes a place in the SERVING ORDER.////// Every Mac does, in the order it was approved — the owner's decision is that/// every Mac is a full standby, and a standby with no rank is one the relay/// reads as LAST behind every other, so the order of takeover among them was/// undefined (28 Sep 2026: only the first Mac had a rank). A Mac that did not/// say its platform but presented a relay identity is a Mac too.////// A LINUX server never does: it advertises the reserved fallback slot on every/// AUTH (`methods::tunnel::serving_rank`), so a number written for it would be/// read by nothing and would place it on the owner's screen ahead of Macs that/// in fact serve before it. A phone cannot serve at all.pub fn takes_serving_rank(platform: Option<DevicePlatform>, relay_identity_key: Option<&str>) -> bool {    match platform {        Some(DevicePlatform::Mac) => true,        None => relay_identity_key.is_some(),        Some(_) => false,    }}/// WHAT A DEVICE'S OWN KEY MAY SIGN (`cotton_devices.scope`, design note 9.2).////// `Full` is every device the owner pairs. `Runner` is a machine that only/// runs CI jobs (the Linux runner): it is carried `Live` so it can be revoked/// like any device, and its runner credential stands by its standing, but its/// own key signs nothing that is admitted — no exchange, snapshot, media or/// pairing. Written once, at the row's create; a change of scope is a revoke/// and a re-pairing, whose new approval carries its own.pub use cotton_core::device::scope::{DeviceScope, DeviceAdmission};/// What [`insert`] and [`approve`] are handed: a row with none of the columns a/// later act writes.#[derive(Debug, Clone, PartialEq, Eq)]pub struct NewDeviceRow {    pub device_id: String,    pub workspace_id: String,    pub name: String,    pub platform: Option<DevicePlatform>,    pub app_version: Option<String>,    pub approved_at: String,    pub approved_by: String,    /// Carried from the pending row: see [`DeviceRow::relay_identity_key`].    pub relay_identity_key: Option<String>,}/// Why a write refused. The store speaks no HTTP: the engine maps/// `DeviceElsewhere` to a plain 409 that carries nothing of the other row.#[derive(Debug, thiserror::Error)]pub enum DeviceStoreError {    #[error("device_elsewhere")]    DeviceElsewhere,    /// A key carrying the SERVING Mac's hardware identity, without the serving    /// key's signature over its succession: a second build, a cotton-headless    /// or anything else on the serving machine would replace the Mac that    /// serves. The one legitimate twin is the app's own re-key    /// ([`DeviceWrite::approve_succession`]).    #[error("{}", SERVING_TWIN_REASON)]    ServingTwin,    #[error(transparent)]    Store(#[from] cotton_store::StoreError),}fn to_device(row: &Row) -> DeviceRow {    DeviceRow {        id: row.text("id").unwrap_or_default().to_string(),        device_id: row.text("device_id").unwrap_or_default().to_string(),        workspace_id: row.text("workspace_id").unwrap_or_default().to_string(),        name: row.text("name").unwrap_or_default().to_string(),        platform: row.text("platform").and_then(DevicePlatform::parse),        app_version: row.text("app_version").map(str::to_string),        approved_at: row.text("approved_at").unwrap_or_default().to_string(),        approved_by: row            .text("approved_by_device")            .unwrap_or_default()            .to_string(),        revoked_at: row.text("revoked_at").map(str::to_string),        revoked_by: row.text("revoked_by_device").map(str::to_string),        revoked_reason: cotton_store::revocation::device_reason(row),        recovery_key_shown_at: row.text("recovery_key_shown_at").map(str::to_string),        // The key every reader takes (`RELAY_KEY_OF_ROW`) when the query        // asked for it; a bare row's own column otherwise.        relay_identity_key: row            .text("relay_key_of_row")            .or_else(|| row.text("relay_identity_key"))            .map(str::to_string),        person_key: row.text("person_key").map(str::to_string),    }}fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}/// The order that answers "the row for this key" wherever a key can match/// several rows: the live approval first, then the newest, then the id./// Written once so every reader of the table picks the SAME row.pub const KEY_ORDER: &str = "ORDER BY (revoked_at IS NULL) DESC, approved_at DESC, id ASC";/// A device's relay identity key as every reader takes it (architect, 12 Oct/// 2026): its row's own write-once column when set, else the key the serving/// Mac KEPT for it in `cotton_device_relay_keys` at the LOWEST epoch — a pure/// function of the set, so every device reads the same key whatever order the/// kept rows arrived in. An SQL expression over a `cotton_devices` row.pub const RELAY_KEY_OF_ROW: &str = "COALESCE(cotton_devices.relay_identity_key, \     (SELECT k.relay_identity_key FROM cotton_device_relay_keys k \      WHERE k.device_id = cotton_devices.device_id AND k.workspace_id = cotton_devices.workspace_id \      ORDER BY k.epoch ASC, k.id ASC LIMIT 1))";/// WHETHER A DEVICE KEY IS A LIVE DEVICE OF THE OWNER'S in this file, asked/// of a copy as readily as of a served file: the row [`FileDevices::row_for`] answers is the owner's (no person/// key), its approval is not a runner's, and its standing is live. A/// stranger's key, a member's, a runner's and a revoked or succeeded one are/// all `false`.pub fn owners_live_device(db: &Driver, device_id: &str) -> cotton_store::Result<bool> {    let devices = FileDevices::new(db);    let Some(row) = devices.row_for(device_id)? else {        return Ok(false);    };    if row.person_key.as_deref().map(str::trim).is_some_and(|key| !key.is_empty()) {        return Ok(false);    }    if !devices.admission_for(device_id)?.is_some_and(|admission| admission.scope == DeviceScope::Full) {        return Ok(false);    }    Ok(cotton_store::revocation::device_standing(db, device_id)? == cotton_store::revocation::Standing::Live)}/// When this device KEY first rang the owner through its own sender, on any/// approval it has held — a Mac re-paired after a revocation is the same Mac,/// and its first push is not owed again.pub fn first_pushed_at(db: &Driver, device_id: &str) -> cotton_store::Result<Option<String>> {    Ok(db        .get(            "SELECT min(pushed_first_at) AS at FROM cotton_devices WHERE device_id = ?",            &[SqlValue::Text(device_id.to_string())],        )?        .and_then(|row| row.text("at").map(str::to_string)))}/// The owner's daily cap for this Mac's Anthropic work, in USD, off its live/// row — `None` when the owner set none (the $5 default is the server's).pub fn ai_day_cap_usd(db: &Driver, device_id: &str) -> cotton_store::Result<Option<f64>> {    Ok(db        .get(            "SELECT ai_day_cap_usd FROM cotton_devices WHERE device_id = ? AND revoked_at IS NULL \             ORDER BY approved_at DESC LIMIT 1",            &[SqlValue::Text(device_id.to_string())],        )?        .and_then(|row| row.real("ai_day_cap_usd")))}/// Its plain reason, the same line on every door a twin can try.pub const SERVING_TWIN_REASON: &str = "this Mac already serves; re-key from the app";pub struct FileDevices<'a> {    db: &'a Driver,}impl<'a> FileDevices<'a> {    pub fn new(db: &'a Driver) -> FileDevices<'a> {        FileDevices { db }    }    /// The row for this key: its LIVE approval if it has one, else its most    /// recent revoked one — `None` for a stranger.    ///    /// A key holds one row per approval (version 41), at most one of them    /// live, so "the row for this key" is an ORDER, not a lookup: live first,    /// then the newest approval, then the id so two readers of one file agree.    /// Every question asked of a key — is it admitted, what is it called, which    /// row does a write address — is asked of this row.    /// The SERVING key's, when `hardware_id` is the machine the serving fact's    /// live key runs on and `device_id` is another key: a join or a    /// registration that would twin the serving Mac. `succeeds` names the key a    /// proven re-key replaces; a re-key of the serving key is no twin.    pub fn serving_twin(        &self,        workspace_id: &str,        device_id: &str,        hardware_id: Option<&str>,        succeeds: Option<&str>,    ) -> cotton_store::Result<Option<String>> {        let Some(hardware_id) = hardware_id.map(str::trim).filter(|id| !id.is_empty()) else {            return Ok(None);        };        let Some(fact) = cotton_store::serving::serving_fact(self.db, workspace_id)? else {            return Ok(None);        };        let serving = fact.device_credential_id;        if serving == device_id || Some(serving.as_str()) == succeeds {            return Ok(None);        }        let twin = self.db.get(            "SELECT 1 FROM cotton_devices WHERE workspace_id = ? AND device_id = ? AND hardware_id = ? AND revoked_at IS NULL",            &[text(workspace_id), text(&serving), text(hardware_id)],        )?;        Ok(twin.map(|_| serving))    }    pub fn row_for(&self, device_id: &str) -> cotton_store::Result<Option<DeviceRow>> {        Ok(self            .db            .get(                &format!(                    "SELECT *, {RELAY_KEY_OF_ROW} AS relay_key_of_row, {REPLACED_BY_OF_ROW} AS replaced_by FROM cotton_devices \                     WHERE device_id = ? {KEY_ORDER} LIMIT 1"                ),                &[text(device_id)],            )?            .as_ref()            .map(to_device))    }    /// Every row of the workspace, revoked included, newest approval first —    /// the audit the person reads.    pub fn list(&self, workspace_id: &str) -> cotton_store::Result<Vec<DeviceRow>> {        Ok(self            .db            .all(                &format!(                    "SELECT *, {RELAY_KEY_OF_ROW} AS relay_key_of_row, {REPLACED_BY_OF_ROW} AS replaced_by FROM cotton_devices \                     WHERE workspace_id = ? ORDER BY approved_at DESC"                ),                &[text(workspace_id)],            )?            .iter()            .map(to_device)            .collect())    }    /// Has this workspace ever admitted a device other than the server's own    /// root row? ONE-WAY: a revoked row still counts.    ///    /// `revoked_at` is deliberately absent from the WHERE. Counting live rows    /// only would mean that revoking the one phone made the workspace unarmed    /// again, and arming is what `POST /v1/me` reports as `deviceStatus`.    /// The place after the last one taken: one past the highest rank a live    /// device of this workspace holds, or first when nobody holds one.    pub fn next_serving_rank(&self, workspace_id: &str) -> cotton_store::Result<i64> {        Ok(self            .db            .get(                "SELECT MAX(serving_rank) AS top FROM cotton_devices \                 WHERE workspace_id = ? AND revoked_at IS NULL",                &[text(workspace_id)],            )?            .and_then(|row| row.int("top"))            .map_or(0, |top| top + 1))    }    pub fn armed(&self, workspace_id: &str) -> cotton_store::Result<bool> {        Ok(self            .db            .get(                "SELECT 1 AS n FROM cotton_devices \                 WHERE workspace_id = ? AND approved_by_device NOT IN (?, ?) LIMIT 1",                &[text(workspace_id), text(SELF_APPROVER), text(RECOVERY_KIT_APPROVER)],            )?            .is_some())    }    /// The scope of the approval [`Self::row_for`] answers for this key —    /// `None` for a stranger. The scope check reads the SAME row the standing    /// does, so a re-pairing's new approval is the one that counts.    pub fn scope_for(&self, device_id: &str) -> cotton_store::Result<Option<DeviceScope>> {        self            .db            .get(                &format!("SELECT scope FROM cotton_devices WHERE device_id = ? {KEY_ORDER} LIMIT 1"),                &[text(device_id)],            )?            .map(|row| DeviceScope::parse(row.text("scope")).map_err(cotton_store::StoreError::refused)).transpose()    }    /// The permanent row admission pair (schema 137). Reading an unknown pair    /// fails closed; the placement grant exists only on runner rows.    pub fn admission_for(&self, device_id: &str) -> cotton_store::Result<Option<DeviceAdmission>> {        self.db.get(&format!("SELECT scope, takes_placements FROM cotton_devices WHERE device_id = ? {KEY_ORDER} LIMIT 1"), &[text(device_id)])?            .map(|row| {                let scope = row.text("scope").ok_or_else(|| cotton_store::StoreError::refused("device scope must be text"))?;                let takes = row.int("takes_placements").ok_or_else(|| cotton_store::StoreError::refused("placement grant must be 0 or 1"))?;                DeviceScope::from_pair(Some(scope), Some(takes)).map_err(cotton_store::StoreError::refused)            }).transpose()    }}// ─── the writes, every one of them replicating ──────────────────────────────/// What a write needs beside the row: the file, whose life it is, and the two/// seams a decision needs to write like a phone does.////// A struct rather than six positional arguments, because every write here/// takes the same six and a caller that swapped two strings would write a/// perfectly valid row about the wrong machine.pub struct DeviceWrite<'a> {    pub db: &'a Driver,    pub workspace_id: &'a str,    /// The file's owner id — what the writer is told it is acting for. Never a    /// credential and never read back out of a device row.    pub owner_id: &'a str,    pub now: DateTime<Utc>,    pub random: Arc<dyn Random>,}impl DeviceWrite<'_> {    /// Device rows are the `devices` job's, on a file this process SERVES: the    /// server's own, and a Mac's own database at birth    /// (`cotton_client::start`).    fn writer(&self) -> Writer<'_> {        Writer::acting(            self.db,            self.workspace_id,            self.owner_id,            crate::mcp::writer::job(DEVICES_JOB),            cotton_store::mint::Held::Served,            self.now,            Arc::clone(&self.random),        )    }    /// The reads, over the same open file — so a caller that has just written    /// can read its own row back without opening anything.    pub fn devices(&self) -> FileDevices<'_> {        FileDevices::new(self.db)    }    fn stamp(&self) -> String {        iso(self.now)    }    /// The whole row as a patch — every column a birth carries.    fn birth_patch(&self, row: &NewDeviceRow) -> Map<String, Value> {        let mut patch = Map::new();        patch.insert("workspace_id".into(), Value::from(row.workspace_id.clone()));        patch.insert("device_id".into(), Value::from(row.device_id.clone()));        patch.insert("name".into(), Value::from(row.name.clone()));        patch.insert(            "platform".into(),            match row.platform {                Some(platform) => Value::from(platform.as_str()),                None => Value::Null,            },        );        patch.insert(            "app_version".into(),            match &row.app_version {                Some(version) => Value::from(version.clone()),                None => Value::Null,            },        );        patch.insert(            "relay_identity_key".into(),            match &row.relay_identity_key {                Some(key) => Value::from(key.clone()),                None => Value::Null,            },        );        patch.insert("approved_at".into(), Value::from(row.approved_at.clone()));        patch.insert(            "approved_by_device".into(),            Value::from(row.approved_by.clone()),        );        patch.insert("revoked_at".into(), Value::Null);        patch.insert("revoked_by_device".into(), Value::Null);        patch.insert("revoked_reason".into(), Value::Null);        patch.insert("recovery_key_shown_at".into(), Value::Null);        patch.insert("created_at".into(), Value::from(self.stamp()));        patch.insert("updated_at".into(), Value::from(self.stamp()));        patch    }    /// Write a row for a key this file has never admitted.    ///    /// Loud rather than idempotent when the row is already there: the one    /// caller is `ensure_self_device`, which has already looked, and an    /// `INSERT OR IGNORE` here would let a second boot silently keep a row it    /// believed it had just written.    ///    /// A key that holds only REVOKED rows — a restore naming a key this file    /// once cut off — is written a new row beside them at [`approval_row_id`],    /// never a patch onto one of them (which the fold would refuse as an    /// un-revocation).    pub fn insert(&self, row: &NewDeviceRow) -> cotton_store::Result<DeviceRow> {        let id = new_life_id(row);        let patch = self.ranked(row, self.birth_patch(row))?;        let mut writer = self.writer();        writer.upsert("cotton_devices", &id, patch);        writer.commit()?;        self.read_back(&row.device_id)    }    /// Queue an admission and its hardware replacement in the caller's act.    pub fn queue_approval_hardware(        &self, writer: &mut Writer<'_>, row: &NewDeviceRow,        person_key: Option<&str>, hardware_id: Option<&str>,    ) -> Result<Option<String>, DeviceStoreError> {        if let Some(found) = self.devices().row_for(&row.device_id)? {            if found.workspace_id != row.workspace_id {                return Err(DeviceStoreError::DeviceElsewhere);            }            if found.revoked_at.is_none() {                return Ok(None);            }        }        let id = new_life_id(row);        let mut patch = self.ranked(row, self.birth_patch(row))?;        if let Some(person_key) = person_key {            patch.insert("person_key".into(), Value::from(person_key));        }        Self::birth_hardware(&mut patch, row.platform, hardware_id);        writer.upsert("cotton_devices", &id, patch);        self.queue_hardware(writer, row, &id, hardware_id, person_key)?;        Ok(Some(id))    }    /// An approval that may land on a key this file has seen before.    ///    /// A LIVE row of this workspace is left exactly as it is and answered — a    /// second approval of an admitted device changes nothing. A key whose rows    /// are all REVOKED gets a NEW row at [`approval_row_id`], and the revoked    /// ones stay as they are: a revocation is a fact that is never undone and the fold    /// rejects a patch that nulls it, so a row that carries one is revoked for    /// good, and a new approval is a new life with a column of its own.    ///    /// A refusal keeps an approval inside its own life:    ///   `DeviceElsewhere` — the key holds a row of ANOTHER workspace in this    ///                       file; nothing is written and nothing of that row    ///                       is answered.    pub fn approve(&self, row: &NewDeviceRow) -> Result<DeviceRow, DeviceStoreError> {        self.approve_scoped(row, DeviceScope::Full)    }    /// [`Self::approve`] with the scope the new approval carries. Pairing is    /// `Full`, which writes nothing (the column's default); `Runner` is    /// written into the create, the only write that ever names the scope.    pub fn approve_scoped(        &self,        row: &NewDeviceRow,        scope: DeviceScope,    ) -> Result<DeviceRow, DeviceStoreError> {        self.approve_scoped_hardware(row, scope, None)    }    pub fn approve_scoped_hardware(        &self,        row: &NewDeviceRow,        scope: DeviceScope,        hardware_id: Option<&str>,    ) -> Result<DeviceRow, DeviceStoreError> {        self.approve_admitted_hardware(row, DeviceAdmission { scope, takes_placements: false }, hardware_id)    }    pub fn approve_admitted_hardware(&self, row: &NewDeviceRow, admission: DeviceAdmission, hardware_id: Option<&str>) -> Result<DeviceRow, DeviceStoreError> {        // Constructing the pair directly cannot bypass the shared vocabulary.        let admission = DeviceScope::from_pair(Some(admission.scope.as_str()), Some(i64::from(admission.takes_placements)))            .map_err(|reason| DeviceStoreError::Store(cotton_store::StoreError::refused(reason)))?;        let scope = admission.scope;        let existing = self.devices().row_for(&row.device_id)?;        if let Some(found) = existing.as_ref() {            if found.workspace_id != row.workspace_id {                return Err(DeviceStoreError::DeviceElsewhere);            }            if found.revoked_at.is_none() {                if self.devices().admission_for(&row.device_id)?.is_some_and(|held| held.scope != admission.scope) {                    return Err(DeviceStoreError::Store(cotton_store::StoreError::refused("revoke and re-pair a device to change its scope")));                }                let mut writer = self.writer();                self.queue_hardware(&mut writer, row, &found.id, hardware_id, found.person_key.as_deref())?;                writer.upsert("cotton_devices", &found.id, Map::from_iter([("takes_placements".into(), Value::from(admission.takes_placements))]));                writer.commit()?;                return Ok(found.clone());            }        }        // A key this file has never seen takes its first id; a key whose        // every row is revoked takes one of its own for this approval. NEVER a        // delete and a recreation at the revoked row's id: the recreation        // erases its tombstone, so another Mac would receive it as a patch on        // the revoked row and refuse it, and a late copy of the old        // revocation would cut the new life off wherever it landed second.        let id = new_life_id(row);        let mut patch = self.ranked(row, self.birth_patch(row))?;        if scope != DeviceScope::Full {            patch.insert("scope".into(), Value::from(scope.as_str()));        }        patch.insert("takes_placements".into(), Value::from(admission.takes_placements));        let mut writer = self.writer();        Self::birth_hardware(&mut patch, row.platform, hardware_id);        writer.upsert("cotton_devices", &id, patch);        self.queue_hardware(&mut writer, row, &id, hardware_id, None)?;        writer.commit()?;        Ok(self.read_back(&row.device_id)?)    }    fn birth_hardware(patch: &mut Map<String, Value>, platform: Option<DevicePlatform>, hardware_id: Option<&str>) {        if matches!(platform, Some(DevicePlatform::Mac | DevicePlatform::Ios)) {            if let Some(id) = hardware_id.map(str::trim).filter(|id| !id.is_empty()) {                patch.insert("hardware_id".into(), Value::from(id));            }        }    }    fn queue_hardware(        &self,        writer: &mut Writer<'_>,        row: &NewDeviceRow,        id: &str,        hardware_id: Option<&str>,        person_key: Option<&str>,    ) -> Result<(), DeviceStoreError> {        self.queue_hardware_except(writer, row, id, hardware_id, person_key, None)    }    /// [`Self::queue_hardware`], leaving `succeeded` alone — the key a re-key    /// already ended as a succession in this act.    fn queue_hardware_except(        &self,        writer: &mut Writer<'_>,        row: &NewDeviceRow,        id: &str,        hardware_id: Option<&str>,        person_key: Option<&str>,        succeeded: Option<&str>,    ) -> Result<(), DeviceStoreError> {        // THE SERVING MAC IS REPLACED ONLY BY ITS OWN RE-KEY. Before the        // platform test: a key claiming another platform is still a key on        // the serving machine.        if self.devices().serving_twin(&row.workspace_id, &row.device_id, hardware_id, succeeded)?.is_some() {            return Err(DeviceStoreError::ServingTwin);        }        let Some(platform @ (DevicePlatform::Mac | DevicePlatform::Ios)) = row.platform else {            return Ok(());        };        let Some(hardware_id) = hardware_id.map(str::trim).filter(|id| !id.is_empty()) else {            return Ok(());        };        let stored = self.db.get(            "SELECT hardware_id FROM cotton_devices WHERE id = ?",            &[text(id)],        )?;        if stored.as_ref().is_some_and(|row| row.text("hardware_id") != Some(hardware_id)) {            let mut patch = Map::new();            patch.insert("hardware_id".into(), Value::from(hardware_id));            writer.upsert("cotton_devices", id, patch);        }        let twins = self.db.all(            "SELECT DISTINCT device_id FROM cotton_devices WHERE workspace_id = ? AND platform = ? AND hardware_id = ? AND device_id <> ? AND revoked_at IS NULL AND person_key IS ?",            &[text(&row.workspace_id), text(platform.as_str()), text(hardware_id), text(&row.device_id), person_key.map_or(SqlValue::Null, text)],        )?;        for twin in twins {            let twin = twin.text("device_id").unwrap();            if Some(twin) == succeeded {                continue;            }            writer.replace_device(twin, &row.device_id, &row.approved_by)?;        }        Ok(())    }    /// A birth patch with the device's place in the serving order, when it    /// takes one ([`takes_serving_rank`]): the next place after the last one    /// taken, so Macs line up in the order they were approved.    fn ranked(        &self,        row: &NewDeviceRow,        mut patch: Map<String, Value>,    ) -> cotton_store::Result<Map<String, Value>> {        if takes_serving_rank(row.platform, row.relay_identity_key.as_deref()) {            let next = self.devices().next_serving_rank(&row.workspace_id)?;            patch.insert("serving_rank".into(), Value::from(next));        }        Ok(patch)    }    /// Rename one device of THIS workspace — a name given here never rewrites    /// the key's row in another life.    pub fn rename(&self, device_id: &str, name: &str) -> cotton_store::Result<bool> {        let Some(row) = self.devices().row_for(device_id)? else {            return Ok(false);        };        if row.workspace_id != self.workspace_id {            return Ok(false);        }        let mut patch = Map::new();        patch.insert("name".into(), Value::from(name.to_string()));        patch.insert("updated_at".into(), Value::from(self.stamp()));        let mut writer = self.writer();        writer.upsert(            "cotton_devices",            &row.id,            patch,        );        writer.commit()?;        Ok(true)    }    /// The key's live row in THIS workspace, or `None`.    fn live_row(&self, device_id: &str) -> cotton_store::Result<Option<DeviceRow>> {        Ok(self            .devices()            .row_for(device_id)?            .filter(|row| row.workspace_id == self.workspace_id && row.revoked_at.is_none()))    }    /// When this device's live row says it first rang the owner, if it has.    pub fn first_pushed_at(&self, device_id: &str) -> cotton_store::Result<Option<String>> {        first_pushed_at(self.db, device_id)    }    /// THE MAC BECOMES A RUNNER, in the personal database: its full row is    /// revoked and a new row for the same key is approved at scope `runner`    /// with the placement grant. Only on the owner's order (`runner_ordered_at`,    /// written at an owner's own screen, no older than [`RUNNER_ORDER_HOURS`])    /// and only after this serving Mac confirmed it holds everything the Mac's    /// copy held (`runner_confirmed_at` at or after the order, no problem    /// standing). Anything else is refused by name and nothing is written.    pub fn become_runner(&self, device_id: &str, by: &str) -> Result<DeviceRow, String> {        let row = self            .live_row(device_id)            .map_err(|error| error.to_string())?            .ok_or("this Mac has no live row here")?;        if row.platform != Some(DevicePlatform::Mac) {            return Err("only a Mac becomes a runner".into());        }        if row.person_key.is_some() {            return Err("a member's Mac is not the owner's to make a runner".into());        }        let admission = self.devices().admission_for(device_id).map_err(|error| error.to_string())?;        if admission.is_some_and(|held| held.scope != DeviceScope::Full) {            return Err("this Mac is a runner already".into());        }        let stored = self            .db            .get(                "SELECT runner_ordered_at, runner_confirmed_at, runner_problem, hardware_id FROM cotton_devices WHERE id = ?",                &[text(&row.id)],            )            .map_err(|error| error.to_string())?            .ok_or("this Mac has no live row here")?;        let ordered = stored.text("runner_ordered_at").ok_or("the owner has not ordered this Mac to become a runner")?;        let ordered_at = chrono::DateTime::parse_from_rfc3339(ordered).map_err(|_| "the order's time is not one")?;        if self.now.signed_duration_since(ordered_at) > chrono::Duration::hours(RUNNER_ORDER_HOURS) {            return Err("the owner's order is older than a day; it is asked again".into());        }        let confirmed = stored.text("runner_confirmed_at").is_some_and(|at| at >= ordered);        if !confirmed || stored.text("runner_problem").is_some() {            return Err("the serving Mac has not confirmed it holds everything this Mac holds".into());        }        let hardware = stored.text("hardware_id").map(str::to_string);        self.revoke(device_id, by, "revoked").map_err(|error| error.to_string())?;        let new = NewDeviceRow {            device_id: device_id.to_string(),            workspace_id: row.workspace_id.clone(),            name: row.name.clone(),            platform: row.platform,            app_version: row.app_version.clone(),            approved_at: self.stamp(),            approved_by: by.to_string(),            relay_identity_key: None,        };        self.approve_admitted_hardware(            &new,            DeviceAdmission { scope: DeviceScope::Runner, takes_placements: true },            hardware.as_deref(),        )        .map_err(|error| error.to_string())    }    /// True only when this call is the one that revoked the device.    ///    /// EVERY LIVE APPROVAL OF THE KEY, IN ONE ACT. A key can hold two live    /// approvals (a re-pair on a Mac that never saw the first), the relay    /// roster admits a key while any approval is live, and a standing is read    /// from the row `KEY_ORDER` puts first — so a fact on one approval alone    /// leaves the device in, or reads a superseded twin as cut off. Each row    /// gets its fact and its mirror through the one revocation writer.    ///    /// THE DEVICE ROWS ALONE: what the device holds or minted (credentials,    /// consents) is the owner's revoke's to end, in `devices/pairing.rs`. A    /// supersede and a restore come through here and end nothing else.    ///    /// The live check is the guard: two revocations of one key must not both    /// come away believing they did it, because the notification hangs on it.    pub fn revoke(        &self,        device_id: &str,        by: &str,        reason: &str,    ) -> cotton_store::Result<bool> {        let (reason, successor) = fact_reason(reason)?;        let mut writer = self.writer().about("revoke");        let ended = writer.revoke(            cotton_store::revocation::DEVICE_KEY_SUBJECT,            device_id,            reason,            successor,            None,            by,        )?;        if ended == 0 {            return Ok(false);        }        writer.commit()?;        Ok(true)    }    /// THE PLACEMENTS FOLLOW THE MACHINE: every placement addressed to `from`    /// — a key this machine held before the one it holds now — is addressed    /// to `to`, its successor, and marked not yet applied, so the machine    /// writes the files under the key it can open the vault with. A path `to`    /// already has a placement for keeps that one. Answers how many moved.    ///    /// Only for a SUPERSEDE (`superseded.rs`): the same machine under a new    /// key. One Mac, 11 Oct 2026: its 41 placements stayed on its 3 Oct key, which    /// no machine holds, so its new key had none to write.    pub fn carry_placements(&self, from: &str, to: &str) -> cotton_store::Result<usize> {        let taken: std::collections::BTreeSet<String> = self            .db            .all(                "SELECT path FROM cotton_secret_placements WHERE workspace_id = ? AND device_id = ?",                &[                    SqlValue::Text(self.workspace_id.to_string()),                    SqlValue::Text(to.to_string()),                ],            )?            .iter()            .filter_map(|row| row.text("path").map(str::to_string))            .collect();        let moving: Vec<String> = self            .db            .all(                "SELECT id, path FROM cotton_secret_placements WHERE workspace_id = ? AND device_id = ?",                &[                    SqlValue::Text(self.workspace_id.to_string()),                    SqlValue::Text(from.to_string()),                ],            )?            .iter()            .filter(|row| row.text("path").is_some_and(|path| !taken.contains(path)))            .filter_map(|row| row.text("id").map(str::to_string))            .collect();        if moving.is_empty() {            return Ok(0);        }        let mut writer = self.writer().about("carry placements");        for id in &moving {            let mut patch = Map::new();            patch.insert("device_id".into(), Value::from(to));            patch.insert("applied_at".into(), Value::Null);            patch.insert("applied_hash".into(), Value::Null);            patch.insert("apply_problem".into(), Value::Null);            patch.insert("updated_at".into(), Value::from(self.stamp()));            writer.upsert("cotton_secret_placements", id, patch);        }        writer.commit()?;        Ok(moving.len())    }    fn read_back(&self, device_id: &str) -> cotton_store::Result<DeviceRow> {        self.devices().row_for(device_id)?.ok_or_else(|| {            cotton_store::StoreError::refused(format!(                "cotton-server: the device row for {device_id} vanished mid-write"            ))        })    }}#[cfg(test)]mod scope_tests {    use super::*;    /// RULE: Reading an unknown device scope fails closed instead of granting Full; the code vocabulary governs access even when a file was written by a newer build.    #[test]    fn an_unknown_stored_scope_is_refused_on_read() {        let db = Driver::open_in_memory().unwrap();        db.exec("CREATE TABLE cotton_devices (id TEXT, device_id TEXT, scope TEXT, revoked_at TEXT, approved_at TEXT)").unwrap();        db.run("INSERT INTO cotton_devices VALUES ('approval', 'synthetic-device', 'future-scope', NULL, '2026-10-13')", &[]).unwrap();        assert!(FileDevices::new(&db).scope_for("synthetic-device").is_err());        db.run("UPDATE cotton_devices SET scope = 'runner'", &[]).unwrap();        assert_eq!(FileDevices::new(&db).scope_for("synthetic-device").unwrap(), Some(DeviceScope::Runner));    }    /// RULE: A schema-138 server must refuse scopes outside its vocabulary,    /// including reader, rather than upgrading an unfamiliar device to Full.    /// Freeze that server's admission vocabulary in a test double so adding    /// future scopes cannot quietly change what an older server recognises.    #[test]    fn a_schema138_server_does_not_approve_reader_or_unknown_scopes() {        struct Schema138Server;        impl Schema138Server {            fn approves(&self, scope: &str, takes_placements: i64) -> bool {                matches!((scope, takes_placements), ("full", 0) | ("runner", 0 | 1))            }        }        let old = Schema138Server;        assert!(old.approves("full", 0));        assert!(old.approves("runner", 1));        for scope in ["reader", "future-scope", ""] {            assert!(!old.approves(scope, 0));        }        // Today's durable reader likewise fails closed for an unknown scope.        // This deliberately unconstrained table models rows from a newer peer.        let db = Driver::open_in_memory().unwrap();        db.exec("CREATE TABLE cotton_devices (id TEXT, device_id TEXT, scope TEXT, takes_placements INTEGER, revoked_at TEXT, approved_at TEXT)").unwrap();        db.exec("INSERT INTO cotton_devices VALUES ('approval', 'synthetic-device', 'future-scope', 0, NULL, '2026-10-16')").unwrap();        assert!(FileDevices::new(&db).admission_for("synthetic-device").is_err());    }    /// RULE: A (full, 1) row and invalid grants are refused when read; placement permission is separate from scope and belongs only to runners.    #[test]    fn forbidden_scope_grant_pair_is_refused_on_read() {        let db = Driver::open_in_memory().unwrap();        db.exec("CREATE TABLE cotton_devices (id TEXT, device_id TEXT, scope TEXT, takes_placements INTEGER, revoked_at TEXT, approved_at TEXT)").unwrap();        db.run("INSERT INTO cotton_devices VALUES ('approval', 'synthetic-device', 'full', 1, NULL, '2026-10-13')", &[]).unwrap();        assert!(FileDevices::new(&db).admission_for("synthetic-device").is_err());        db.run("UPDATE cotton_devices SET scope = 'runner'", &[]).unwrap();        assert!(FileDevices::new(&db).admission_for("synthetic-device").unwrap().unwrap().placement_runner());        db.run("UPDATE cotton_devices SET takes_placements = 2", &[]).unwrap();        assert!(FileDevices::new(&db).admission_for("synthetic-device").is_err());    }}