Cotton code
240 lines · 9.1 KB · RustRaw
//! Where a household's relay is: the domain its name lives under, and the//! host its Macs dial.//!//! A household is reached at `https://<name>.<domain>`, and a serving Mac//! holds a line open to `wss://<tunnel>/tunnel/v1`. Those two values ARE the//! relay as far as any device is concerned — the relay forwards bytes it//! cannot read (`packages/relay/__tests__/blindRelay.test.ts`), so nothing//! else about it is anybody's business — and a household may run its own//! (`packages/relay/README.md`). So they are a VALUE that is passed, never a//! string a caller writes: every address in the tree is made by a method here,//! from an address somebody handed over.//!//! [`RelayAddress::cotton`] is Cotton's own relay, and this file is the only//! one that spells it (`scripts/__tests__/no-relay-host-literal.test.ts`). It//! is a DEFAULT, not a fact: it is what a household that never chose gets, and//! what the three callers that run before any household file exists have to//! use — a phone resolving a typed name, the Mac's first-run free-check, and a//! take-over reading the directory.use std::borrow::Cow;/// The domain of Cotton's own relay: a household there is `<name>.<this>`.pub const DEFAULT_RELAY_DOMAIN: &str = "relay.cottondb.com";/// Where a Mac dials Cotton's own relay. Not under the domain, so it cannot be/// derived from it — which is why an address is two values and not one.pub const DEFAULT_TUNNEL_HOST: &str = "tunnel.cottondb.com";/// A relay, as a device needs to know it.#[derive(Debug, Clone, PartialEq, Eq)]pub struct RelayAddress {    domain: Cow<'static, str>,    tunnel: Cow<'static, str>,}/// Why two strings are not a relay's address.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum RelayAddressRefusal {    /// The domain is not a lower-case hostname of at least two labels.    Domain,    /// The tunnel host is not a lower-case hostname of at least two labels.    Tunnel,}impl std::fmt::Display for RelayAddressRefusal {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.write_str(match self {            RelayAddressRefusal::Domain => {                "the relay's domain is a hostname such as relay.example.org — lower-case, no scheme, no path"            }            RelayAddressRefusal::Tunnel => {                "the relay's tunnel host is a hostname such as tunnel.example.org — lower-case, no scheme, no path"            }        })    }}impl RelayAddress {    /// Cotton's own relay — the default.    pub fn cotton() -> RelayAddress {        RelayAddress {            domain: Cow::Borrowed(DEFAULT_RELAY_DOMAIN),            tunnel: Cow::Borrowed(DEFAULT_TUNNEL_HOST),        }    }    /// A household's own relay. Both values are hostnames and nothing more: a    /// scheme, a port, a path or an upper-case letter is refused rather than    /// repaired, because this value is what every device of the household    /// goes on to dial and to sign.    pub fn new(domain: &str, tunnel: &str) -> Result<RelayAddress, RelayAddressRefusal> {        if !is_hostname(domain) {            return Err(RelayAddressRefusal::Domain);        }        if !is_hostname(tunnel) {            return Err(RelayAddressRefusal::Tunnel);        }        Ok(RelayAddress {            domain: Cow::Owned(domain.to_string()),            tunnel: Cow::Owned(tunnel.to_string()),        })    }    /// The relay a database's own row names — `cotton_workspaces.relay_domain`    /// and `relay_tunnel_host`, as they are stored.    ///    /// Both absent — every household that never chose — is Cotton's own relay.    /// Both present is the household's own. Anything else is `Err` with the    /// sentence, and is NEVER answered with Cotton's relay: a household that    /// chose its own front door must not be reached through ours because its    /// setting would not parse — its name there may be somebody else's.    pub fn from_stored(domain: Option<&str>, tunnel: Option<&str>) -> Result<RelayAddress, String> {        match (domain, tunnel) {            (None, None) => Ok(RelayAddress::cotton()),            (Some(domain), Some(tunnel)) => RelayAddress::new(domain, tunnel).map_err(|refusal| {                format!("this database names a relay that cannot be dialled: {refusal}")            }),            _ => Err(                "this database names half a relay — its domain and its tunnel host are set together"                    .to_string(),            ),        }    }    /// The domain a household's name is the first label under.    pub fn domain(&self) -> &str {        &self.domain    }    /// The host a serving Mac dials.    pub fn tunnel_host(&self) -> &str {        &self.tunnel    }    /// `<name>.<domain>` — the host a household answers on. The name is the    /// caller's to have checked (`device::pairing::matches_relay_name_pattern`).    pub fn host(&self, name: &str) -> String {        format!("{name}.{}", self.domain)    }    /// `https://<name>.<domain>` — the origin a household answers on.    pub fn origin(&self, name: &str) -> String {        format!("https://{name}.{}", self.domain)    }    /// Where the relay says which names are taken and which key holds one.    /// `directory` is a label no household can have (`relay_name`'s reserved    /// list), so this is never somebody's Cotton.    pub fn directory_origin(&self) -> String {        format!("https://directory.{}", self.domain)    }    /// What stands before `.<domain>` in a host, or `None` when the host is not    /// under the domain. NOT yet a household's name: it may be empty, reserved    /// or several labels deep, and the caller applies the name grammar.    pub fn label_of_host<'a>(&self, host: &'a str) -> Option<&'a str> {        host.strip_suffix(self.domain.as_ref())?.strip_suffix('.')    }    /// Is this host the relay's — a household's, a reserved label's, or the    /// domain itself?    pub fn holds(&self, host: &str) -> bool {        host == self.domain || self.label_of_host(host).is_some()    }}/// Where one household's Cotton answers: the relay it is reached through, and/// its name there.////// The two travel together because neither is an address alone — a name is a/// label under SOME relay's domain — and every reader that prints, parses or/// clones a household's address reads both off the same row/// (`cotton_workspaces`). A household nobody has named yet has a relay and no/// name: it recognises its relay's hosts and has no address of its own.#[derive(Debug, Clone, PartialEq, Eq)]pub struct HouseholdAddress {    relay: RelayAddress,    name: Option<String>,}impl HouseholdAddress {    /// `name` as the workspace row holds it: trimmed and folded to lower    /// case, and blank reads as none. Whether it is a relay NAME is the    /// reader's to check where it builds a host    /// (`device::pairing::matches_relay_name_pattern`).    pub fn new(relay: RelayAddress, name: Option<&str>) -> HouseholdAddress {        HouseholdAddress {            relay,            name: name                .map(|name| name.trim().to_ascii_lowercase())                .filter(|name| !name.is_empty()),        }    }    /// A household with no address anything could print: no name yet, or a    /// stored relay that cannot be used ([`RelayAddress::from_stored`]'s    /// `Err`). It still knows that a host under Cotton's own relay is    /// somebody's Cotton — that is true in every household — and it builds    /// nothing.    pub fn none() -> HouseholdAddress {        HouseholdAddress {            relay: RelayAddress::cotton(),            name: None,        }    }    /// [`Self::new`] off a workspace row's three columns. A stored relay that    /// cannot be used is [`Self::none`], NOT the name under Cotton's relay.    pub fn from_stored(        name: Option<&str>,        domain: Option<&str>,        tunnel: Option<&str>,    ) -> HouseholdAddress {        match RelayAddress::from_stored(domain, tunnel) {            Ok(relay) => HouseholdAddress::new(relay, name),            Err(_) => HouseholdAddress::none(),        }    }    pub fn relay(&self) -> &RelayAddress {        &self.relay    }    pub fn name(&self) -> Option<&str> {        self.name.as_deref()    }}impl Default for HouseholdAddress {    fn default() -> HouseholdAddress {        HouseholdAddress::none()    }}/// A lower-case DNS hostname of at least two labels, each of letters, digits/// and inner hyphens.pub(crate) fn is_hostname(value: &str) -> bool {    if value.is_empty() || value.len() > 253 {        return false;    }    let mut labels = 0;    for label in value.split('.') {        let bytes = label.as_bytes();        let inner = |b: &u8| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-';        if bytes.is_empty()            || bytes.len() > 63            || !bytes.iter().all(inner)            || bytes.first() == Some(&b'-')            || bytes.last() == Some(&b'-')        {            return false;        }        labels += 1;    }    labels >= 2}#[cfg(test)]#[path = "relay_address_tests.rs"]mod relay_address_tests;