Cotton code
551 lines · 24.2 KB · RustRaw
//! **The process identity — CottonDB, Cotton Dev or a manifest business — declared once.**//!//! One source tree builds two apps that sit side by side on one iPhone and one//! Mac: the real CottonDB, whose identity is frozen, and Cotton Dev, which//! every local build, test and simulator run produces. They must never touch//! each other's data, so everything that names a place the data lives or a//! household it reaches is a function of the flavor://!//! - the Mac's data folder — `~/CottonDB` or `~/CottonDev`;//! - the port a fresh data folder's server listens on;//! - which relay names a build may claim, dial or join — a Cotton Dev name//!   ends in [`DEV_RELAY_NAME_SUFFIX`] and a real one never does, so the two//!   namespaces are disjoint by construction and a dev build cannot address//!   the real household by typing its name;//! - what a server says it is, so a client refuses a server of the other app.//!//! The bundle ids, app groups, keychain services and URL schemes are the//! build's and Swift's (`apps/cotton/project.yml`, `AppFlavor.swift`,//! `scripts/build-app.sh`); this module holds what the Rust core decides.//!//! **Undeclared is dev.** A process learns its flavor from the app//! (`CottonFlavor` in its Info.plist, handed to the core at open) or from//! `COTTON_FLAVOR` (the session host, the headless binary). Anything that does//! not say `real` or `business` is Cotton Dev: the real flavor is built only by an explicit//! release, and a build that forgot to say which it is must land on the side//! that cannot reach the real household. The one exception is [`current`],//! which answers `None` in a process that has declared nothing — a crate's//! unit test — so the relay-name rule does not fire in tests that never asked//! for it.use std::path::{Path, PathBuf};use std::sync::OnceLock;/// App identities built from one source tree.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub enum Flavor {    /// CottonDB — the owner's household. Frozen identity.    Real,    /// Cotton Dev — every development build.    Dev,    /// A single database app configured by a bundled manifest.    Business,}/// The environment variable a helper process reads its flavor from.pub const FLAVOR_ENV: &str = "COTTON_FLAVOR";/// The flavor of the app SERVING a CI runner, as every job under that runner/// sees it. Deliberately not [`FLAVOR_ENV`]: to a build script `COTTON_FLAVOR`/// means "the app to build", and a job that inherited the server's would build/// (or refuse to build) whatever the serving app happens to be — the run-5251/// refusal, `COTTON_FLAVOR=real is exported but this lane was asked for flavor/// dev`. A job that needs to know which server it runs under (`scripts/ci//// serving-mac.sh`) reads this one.pub const SERVING_FLAVOR_ENV: &str = "COTTON_SERVING_FLAVOR";/// Every Cotton Dev relay name ends in this; no real one does.pub const DEV_RELAY_NAME_SUFFIX: &str = "-dev";impl Flavor {    /// Every identity, for guards that walk them.    pub const ALL: [Flavor; 3] = [Flavor::Real, Flavor::Dev, Flavor::Business];    /// The wire and Info.plist spelling.    pub const fn as_str(self) -> &'static str {        match self {            Flavor::Real => "real",            Flavor::Dev => "dev",            Flavor::Business => "business",        }    }    /// Exact `real` and `business` declarations opt in; every other value is Dev.    pub fn from_declared(value: Option<&str>) -> Flavor {        match value.map(str::trim) {            Some("real") => Flavor::Real,            Some("business") => Flavor::Business,            _ => Flavor::Dev,        }    }    /// Read `COTTON_FLAVOR` off a variable lookup.    pub fn from_env(vars: &dyn Fn(&str) -> Option<String>) -> Flavor {        Flavor::from_declared(vars(FLAVOR_ENV).as_deref())    }    /// The Mac's data folder's own name, under the person's home.    pub const fn data_dir_name(self) -> &'static str {        match self {            Flavor::Real => "CottonDB",            Flavor::Dev => "CottonDev",            Flavor::Business => "CottonBusiness",        }    }    /// `<home>/CottonDB` or `<home>/CottonDev`.    pub fn home_data_dir(self, home: impl AsRef<Path>) -> PathBuf {        home.as_ref().join(self.data_dir_name())    }    /// The port a fresh data folder's server is given. Different, so both    /// apps can serve on one Mac at once.    pub const fn default_port(self) -> u16 {        match self {            Flavor::Real => 8790,            Flavor::Dev => 8791,            Flavor::Business => 8792,        }    }    /// The other app.    pub const fn other(self) -> Flavor {        match self {            Flavor::Real => Flavor::Dev,            Flavor::Dev => Flavor::Real,            Flavor::Business => Flavor::Real,        }    }    /// The URL scheme every deep link of this app carries — an invite link    /// (`crate::invite_link`) opens in the app whose scheme it bears and no    /// other. The Swift twin is `AppFlavor.urlScheme`    /// (`apps/cotton/Sources/CottonMailbox/AppFlavor.swift`), held to these two    /// literals by `scripts/__tests__/swift-mac.test.ts`.    pub fn url_scheme(self) -> &'static str {        match self {            Flavor::Real => "tinmen-cotton",            Flavor::Dev => "cottondev",            Flavor::Business => business_manifest().ok().and_then(|manifest|manifest.flavour.as_deref()).unwrap_or("cottonbusiness"),        }    }    /// The name a person reads for this app.    pub const fn display_name(self) -> &'static str {        match self {            Flavor::Real => "CottonDB",            Flavor::Dev => "Cotton Dev",            Flavor::Business => "Business",        }    }    /// Whether this app may claim, dial or join a relay name.    ///    /// Cotton Dev only ever uses names ending in `-dev`; the real app never    /// does; a business app dials its Worker and uses no relay name. The shape rule (`device::pairing::matches_relay_name_pattern`)    /// is the caller's — this only answers which app a name belongs to.    pub fn admits_relay_name(self, name: &str) -> bool {        let is_dev_name = name.trim().ends_with(DEV_RELAY_NAME_SUFFIX);        match self {            Flavor::Real => !is_dev_name,            Flavor::Dev => is_dev_name,            Flavor::Business => false,        }    }    /// Why a data folder is the other app's, or `None` when it is not.    ///    /// The other app's folder AND anything inside it, compared in every form    /// the path can take ([`path_forms`]): as given, made absolute with `.` and    /// `..` resolved lexically, with its deepest existing ancestor    /// canonicalised (so a symlink to the real folder, or to somewhere inside    /// it, is caught even when the rest of the path does not exist yet), and    /// case-folded, because the Mac's disk is case-insensitive and    /// `~/cottondb` IS `~/CottonDB`. A hit in any form refuses — refusing a    /// strange spelling of a harmless folder costs a sentence; admitting a    /// strange spelling of the real one costs the household. The legacy    /// `~/Library/Application Support/CottonDB` is the real app's as well.    pub fn refusal_for_data_dir(self, home: impl AsRef<Path>, data_dir: &Path) -> Option<String> {        let home = home.as_ref();        let other = self.other();        let mut foreign = vec![other.home_data_dir(home)];        if self == Flavor::Business { foreign.push(Flavor::Dev.home_data_dir(home)); } else { foreign.push(Flavor::Business.home_data_dir(home)); }        if other == Flavor::Real {            foreign.push(                home.join("Library")                    .join("Application Support")                    .join(other.data_dir_name()),            );        }        let given = path_forms(data_dir);        let hit = foreign.iter().flat_map(|candidate| path_forms(candidate)).any(|candidate| {            given.iter().any(|form| form.starts_with(&candidate))        });        hit.then(|| match self {            Flavor::Business => format!("Business will not open {} — another app owns that folder.", data_dir.display()),            Flavor::Dev => format!(                "Cotton Dev will not open {} — that folder is Cotton's, the real household's database. Cotton Dev keeps its own data in ~/{}.",                data_dir.display(),                Flavor::Dev.data_dir_name()            ),            Flavor::Real => format!(                "Cotton will not open {} — that folder is Cotton Dev's. Cotton keeps its data in ~/{}.",                data_dir.display(),                Flavor::Real.data_dir_name()            ),        })    }    /// Why a relay name is the other app's, or `None` when this app may use it.    pub fn refusal_for_relay_name(self, name: &str) -> Option<String> {        if self.admits_relay_name(name) {            return None;        }        Some(match self {            Flavor::Business => "Business uses no relay name — it dials its object on the Worker.".to_string(),            Flavor::Dev => format!(                "Cotton Dev only uses names ending in \"{DEV_RELAY_NAME_SUFFIX}\" — \"{}\" belongs to CottonDB, the real household.",                name.trim()            ),            Flavor::Real => format!(                "\"{}\" is a Cotton Dev name — CottonDB never uses a name ending in \"{DEV_RELAY_NAME_SUFFIX}\".",                name.trim()            ),        })    }    /// Why a server that declared `declared` (its `flavor` field, `None` when    /// it said nothing) is not one this app may join, or `None` when it is.    ///    /// A server that says nothing is a build from before flavors — which is    /// the frozen real household — so Cotton Dev refuses it and the real app    /// accepts it.    pub fn refusal_for_server(self, declared: Option<&str>) -> Option<String> {        let server = match declared.map(str::trim) {            Some("dev") => Flavor::Dev,            Some("business") => Flavor::Business,            Some("real") | None => Flavor::Real,            Some(_) => return Some("That server did not say which Cotton it is, so this app will not join it.".to_string()),        };        if server == Flavor::Business && self != Flavor::Business {            return Some("That server is a business app — this Cotton does not join it.".into());        }        (server != self).then(|| match self {            Flavor::Business => "Business only joins a business server.".to_string(),            Flavor::Dev => "That server is CottonDB, the real household — Cotton Dev only joins a Cotton Dev server.".to_string(),            Flavor::Real => "That server is Cotton Dev — CottonDB never joins a development server.".to_string(),        })    }}/// Every form a folder's path can take, case-folded — what/// [`Flavor::refusal_for_data_dir`] compares (its doc says why each).fn path_forms(path: &Path) -> Vec<PathBuf> {    let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());    let lexical = lexical(&absolute);    let mut forms = vec![lexical.clone()];    forms.extend(canonical_prefix(&lexical));    forms.extend(std::fs::canonicalize(path).ok());    forms        .iter()        .map(|form| PathBuf::from(form.to_string_lossy().to_lowercase()))        .collect()}/// `a/b/`, `a/b/.` and `a/c/../b` are `a/b` — by the letters alone.fn lexical(path: &Path) -> PathBuf {    use std::path::Component;    let mut out = PathBuf::new();    for component in path.components() {        match component {            Component::CurDir => {}            Component::ParentDir => {                if !out.pop() {                    out.push(component);                }            }            other => out.push(other),        }    }    out}/// The path with its deepest EXISTING ancestor canonicalised and the rest/// put back, so a link to the real folder is followed even when what is/// asked for under it does not exist yet. `None` when no ancestor exists.fn canonical_prefix(path: &Path) -> Option<PathBuf> {    let mut rest = Vec::new();    let mut at = path;    loop {        if let Ok(found) = std::fs::canonicalize(at) {            return Some(rest.iter().rev().fold(found, |acc: PathBuf, part| acc.join(part)));        }        rest.push(at.file_name()?.to_os_string());        at = at.parent()?;    }}static CURRENT: OnceLock<Flavor> = OnceLock::new();/// Declare this process's flavor. Once: a second declaration of the SAME/// flavor is fine (a reopen), a different one is refused — one process is one/// app.pub fn declare(flavor: Flavor) -> Result<(), String> {    if flavor == Flavor::Business {        business_manifest()?;    }    let held = *CURRENT.get_or_init(|| flavor);    if held == flavor {        Ok(())    } else {        Err(format!(            "this process is already {} and cannot become {}",            held.as_str(),            flavor.as_str()        ))    }}/// This process's declared flavor, or `None` when nothing declared one (a/// unit test). Every app process declares at open.pub fn current() -> Option<Flavor> {    CURRENT.get().copied()}/// The relay-name rule against this process's flavor. A process that declared/// nothing has no rule to apply.pub fn refusal_for_relay_name_here(name: &str) -> Option<String> {    current().and_then(|flavor| flavor.refusal_for_relay_name(name))}#[cfg(test)]#[path = "flavor_tests.rs"]mod tests;fn is_false(value: &bool) -> bool { !*value }/// Where a business's object answers: the Worker (`https://…workers.dev` in/// development, the business's own host once named) and the slug that names/// the business on it.#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]#[serde(deny_unknown_fields)]pub struct BusinessObject {    pub server: String,    pub slug: String,}impl BusinessObject {    pub fn validate(&self) -> Result<(), String> {        if !(self.server.starts_with("https://") || self.server.starts_with("http://")) {            return Err("business.server is the Worker's https address".into());        }        if self.slug.is_empty() || !self.slug.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') {            return Err("business.slug is lowercase letters, digits and dashes".into());        }        Ok(())    }}/// JSON shipped in the app bundle. Tools are built-in package keys, never table names.#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]#[serde(deny_unknown_fields)]pub struct BusinessManifest {    /// Operator-only disposable development data; never inferred from a name.    #[serde(default, skip_serializing_if = "is_false")]    pub development: bool,    #[serde(default)]    pub genesis: crate::genesis::Genesis,    /// Which of Cotton's own cards the dial holds beside the tools: absent,    /// Home and Tools, as in Cotton; Rigby names    /// `{"home": false, "tools": false, "settings": true}`.    #[serde(default, skip_serializing_if = "FanCards::is_cottons")]    pub fan: FanCards,    /// Whether this app syncs at all: absent is true, as in Cotton. Rigby says    /// false — one device, no Mac — so This Device says the database lives    /// here alone and shows no serving, pairing or queue facts (architect,    /// 22 Oct 2026).    #[serde(default = "yes", skip_serializing_if = "is_true")]    pub sync: bool,    pub name: String,    pub icon: String,    pub theme: String,    pub single_database: bool,    pub tools: Vec<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub flavour: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub home: Option<serde_json::Value>,    /// The business's object on Cloudflare: the Worker's address and the    /// business's slug there (`apps/business`); the phone's business shell    /// speaks to it alone (owner, 24 Oct 2026).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub business: Option<BusinessObject>,    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]    pub public_views: std::collections::BTreeMap<String, Vec<String>>,    /// Which database the app shows — `"personal"` or `{"id", "host", "named"}`; read    /// by the phone core (`cotton_ffi::shell::scope`), absent for every one.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub database: Option<serde_json::Value>,}/// The manifest's `fan`: whether the dial holds the Home card, the Tools card/// and a Settings card (the settings list, last, where Tools is not) beside/// the tools. Each absent key is Cotton's own answer: Home and Tools, no/// Settings card.#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]#[serde(deny_unknown_fields)]pub struct FanCards {    #[serde(default = "yes")]    pub home: bool,    #[serde(default = "yes")]    pub tools: bool,    #[serde(default)]    pub settings: bool,    /// The tool the dial opens on where it holds no Home card; absent, its    /// first card.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub opens: Option<String>,    /// The app's face is ONE STREAM of the conversations of the tool it    /// opens on (Cotton Messages, 14 Nov 2026): the shell draws no fan and    /// no hub, and pages the chats `shell.stream` names. Absent, the fan.    #[serde(default, skip_serializing_if = "std::ops::Not::not")]    pub stream: bool,}impl Default for FanCards {    fn default() -> Self { Self { home: true, tools: true, settings: false, opens: None, stream: false } }}impl FanCards {    fn is_cottons(&self) -> bool { *self == Self::default() }    /// The dial a manifest names (`fan`): absent, Cotton's own; a `fan` that    /// does not read is a broken manifest, said at open.    pub fn of(manifest: Option<&serde_json::Value>) -> Result<FanCards, String> {        match manifest.and_then(|manifest| manifest.get("fan")) {            None => Ok(FanCards::default()),            Some(fan) => serde_json::from_value(fan.clone()).map_err(|error| format!("the manifest's fan does not read: {error}")),        }    }}fn yes() -> bool { true }fn is_true(value: &bool) -> bool { *value }/// Whether this process's app is served — has a serving Mac to sync with —/// for whatever a definition shows only then (a settings row's/// `needs: "serving"`). Process-wide, declared at open from the manifest's/// `sync` ([`declare_serving`]); undeclared is true, as in Cotton.static SERVING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);/// Declare, at open, whether this process's app is served: the manifest's/// `sync` (architect, 22 Oct 2026: serving = sync != false).pub fn declare_serving(serving: bool) {    SERVING.store(serving, std::sync::atomic::Ordering::SeqCst);}/// Whether this process's app is served ([`declare_serving`]).pub fn serving() -> bool {    SERVING.load(std::sync::atomic::Ordering::SeqCst)}/// Whether the manifest's database is the owner's personal object: a/// `business` address beside a `personal` genesis, as the app reads it/// (`FlavourManifest.personalObject`). Such an app's phone reaches its/// database only through `personal.connect` — never a Mac, never the relay.pub fn on_personal_object(manifest: Option<&serde_json::Value>) -> bool {    manifest.is_some_and(|manifest| {        manifest.get("business").is_some() && manifest.get("genesis").and_then(serde_json::Value::as_str) == Some("personal")    })}/// The manifest's `sync`: absent is true (Cotton syncs); an explicit word/// that is not true or false is a broken manifest, said at open.pub fn syncs(manifest: Option<&serde_json::Value>) -> Result<bool, String> {    match manifest.and_then(|manifest| manifest.get("sync")) {        None => Ok(true),        Some(serde_json::Value::Bool(syncs)) => Ok(*syncs),        Some(_) => Err("a manifest's sync is true or false".into()),    }}impl BusinessManifest {    /// App identity can be advertised; a development build's own facts cannot.    pub fn for_clients(&self) -> Self {        let mut manifest = self.clone();        manifest.development = false;        manifest    }    pub fn from_json(json: &str) -> Result<Self, String> {        let mut value: serde_json::Value = serde_json::from_str(json).map_err(|e| e.to_string())?;        if let Some(object) = value.as_object_mut() {            if let Some(databases) = object.remove("databases") {                if databases.as_str() != Some("single") || object.get("single_database").is_some_and(|v|v != &serde_json::Value::Bool(true)) {                    return Err("a business manifest names one database".into());                }                object.insert("single_database".into(), true.into());                let icon = object.get("flavour").and_then(|v|v.as_str()).unwrap_or("business").to_string();                object.entry("icon").or_insert(icon.into());                object.entry("theme").or_insert("plain".into());            }        }        let manifest: Self = serde_json::from_value(value).map_err(|e| e.to_string())?;        manifest.validate()?;        Ok(manifest)    }    pub fn validate(&self) -> Result<(), String> {        if self.flavour.as_ref().is_some_and(|id| !id.as_bytes().first().is_some_and(u8::is_ascii_lowercase)            || !id.bytes().all(|b|b.is_ascii_lowercase()||b.is_ascii_digit()||b"+-.".contains(&b))) {            return Err("the business flavour must name its own lowercase URL scheme".into());        }        if !self.single_database || [&self.name, &self.icon, &self.theme].iter().any(|s| s.trim().is_empty()) {            return Err("a business manifest needs name, icon, theme and single_database: true".into());        }        let mut seen = std::collections::BTreeSet::new();        let carried = crate::toolkits::shipped_kit_tools();        for key in &self.tools {            let known = crate::kit::ids().contains(&key.as_str()) || carried.iter().any(|package| &package.tool.id == key);            if !known || !seen.insert(key) {                return Err(format!("unknown or duplicate business tool {key:?}"));            }        }        // The tables this business's packages bring: a package that carries        // no table (a kitchen's Plans) reads them.        let brought: Vec<crate::definitions::TableDefinition> = carried.iter()            .filter(|package| self.tools.contains(&package.tool.id))            .flat_map(|package| package.tables.iter().cloned())            .collect();        for (tool, views) in &self.public_views {            let package = carried.iter().find(|p| &p.tool.id == tool && self.tools.contains(tool))                .ok_or_else(|| "public views must belong to a carried business tool".to_string())?;            let tables = if package.tables.is_empty() { &brought } else { &package.tables };            crate::definitions::tool_views::validate_public_reads(&package.tool.views, tables).map_err(|e|e.to_string())?;            for id in views {                if !package.tool.views.iter().any(|v| &v.id == id && v.visibility == "public") {                    return Err("the manifest must name public views of its tool".into());                }            }        }        if let Some(business) = &self.business {            business.validate()?;        }        Ok(())    }}static BUSINESS: OnceLock<BusinessManifest> = OnceLock::new();/// The embedder calls this with its bundle's business.json before declaring its flavor.pub fn declare_business(manifest: BusinessManifest) -> Result<(), String> {    manifest.validate()?;    if BUSINESS.get_or_init(|| manifest.clone()) != &manifest {        return Err("this process already holds a different business manifest".into());    }    declare(Flavor::Business)}/// Headless servers set COTTON_BUSINESS_MANIFEST to the bundle's JSON path.pub fn business_manifest() -> Result<&'static BusinessManifest, String> {    if let Some(manifest) = BUSINESS.get() { return Ok(manifest); }    let path = std::env::var_os("COTTON_BUSINESS_MANIFEST")        .ok_or("business flavor requires COTTON_BUSINESS_MANIFEST or declare_business")?;    let text = std::fs::read_to_string(path).map_err(|e| e.to_string())?;    let manifest = BusinessManifest::from_json(&text)?;    Ok(BUSINESS.get_or_init(|| manifest))}pub fn single_database() -> bool { current() == Some(Flavor::Business) }