Cotton code
259 lines · 10.1 KB · RustRaw
//! The pairing grammar the phone reads and shows. The port of//! `packages/core/src/device/pairing.ts`.//!//! Relay origins, the consent page's user code, and the ONE QR payload left//! (P-D6, N-D2, N-D3, N-D8).//!//! A `cotton-oauth:` payload names a SERVER, and the phone will sign to it — so//! the only server it accepts is `https://<name>.relay.cottondb.com` with a//! name the relay itself would accept. A plain-http address, a path, a foreign//! host: not a payload, just text (finding 10). Loopback, a home-network//! address and a `*.local` name are the phone TRANSPORT's decision//! (`cotton-client`'s `normalize_server_url`), not this grammar's.//!//! **`cotton-pair:` is gone, and so is the eight-character pairing code it//! carried.** A join no longer begins with a secret: the joining device//! presents its key, the server answers six digits, and the person compares//! them with the ones that arrive on a device they already have//! (Cotton note "Devices — how a machine is admitted to your database"). Nothing mints a code, so nothing folds one —//! `normalize_user_code` below is the OAuth consent page's `XXXX-XXXX` and is//! the only survivor of that alphabet.//!//! **`cotton-device:` is gone too**, and with it the second direction: a phone//! used to SHOW its own key as a symbol for an admitted device to scan and//! approve. Nothing scans it any more — a join is a request the server answers//! with six digits, and the approving device reads them off its own pending//! list — so the payload, its parser and the route behind it (`POST//! /v1/devices/approve`) went together. `cotton-oauth:` is the one payload//! left, and `PairingScanner` reads only that.use serde::{Deserialize, Serialize};use serde_json::{Map, Value};use cotton_store::protocol::js::{is_js_whitespace, json_stringify};use crate::relay_address::RelayAddress;/// The relay's own rule for a name (`packages/relay/src/protocol/names.ts`,/// `NAME_PATTERN`), restated: core cannot import the relay.////// The pattern's SOURCE TEXT lives in [`crate::handles::RELAY_NAME_PATTERN_SOURCE`],/// where a test reads the relay's file BY PATH and holds the two byte-equal —/// this is the predicate that pattern describes, spelled out.////// It is deliberately NOT [`crate::handles::is_relay_name`]: that one is the/// STORE's `isRelayName`, which additionally refuses an all-digits name. A/// pairing QR is read against the relay's own grammar, and `12` is a name the/// relay would accept.pub fn matches_relay_name_pattern(name: &str) -> bool {    let bytes = name.as_bytes();    // `^[a-z0-9][a-z0-9-]{1,30}$` — two to thirty-one characters.    if bytes.len() < 2 || bytes.len() > 31 {        return false;    }    let Some((first, rest)) = bytes.split_first() else {        return false;    };    if !first.is_ascii_lowercase() && !first.is_ascii_digit() {        return false;    }    rest.iter()        .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')}/// The https origin a relay name names, or `None` when the name is not one.pub fn relay_origin_for_name(name: &str) -> Option<String> {    matches_relay_name_pattern(name).then(|| RelayAddress::cotton().origin(name))}/// Is this host under the relay domain — somebody's Cotton, the relay's own/// apex included? A git host never is.pub fn is_relay_host(host: &str) -> bool {    RelayAddress::cotton().holds(&host.to_ascii_lowercase())}/// The relay name a host under the relay domain carries, or `None` for a host/// that is not exactly `<name>.relay.cottondb.com`. Case is the caller's to/// fold.pub fn relay_name_of_host(host: &str) -> Option<&str> {    let name = RelayAddress::cotton().label_of_host(host)?;    matches_relay_name_pattern(name).then_some(name)}/// The name of a relay origin, or `None` for anything that is not exactly one.////// The TypeScript's `/^https:\/\/([a-z0-9-]+)\.relay\.cottondb\.com$/` anchors/// at both ends, so a path (`…/x`, and even a bare trailing `/`), a plain-http/// scheme, an upper-case host and `…cottondb.com.evil.com` are all refused./// The captured group cannot contain a dot, which is why/// `https://a.b.relay.cottondb.com` is not a relay origin either.pub fn relay_name_of(origin: &str) -> Option<&str> {    let name = RelayAddress::cotton().label_of_host(origin.strip_prefix("https://")?)?;    // The regex's `[a-z0-9-]+` group is subsumed by the name pattern, which    // admits nothing else — including no dot, so a deeper subdomain is out.    matches_relay_name_pattern(name).then_some(name)}/// Crockford base32: no I, L, O, U — the alphabet the Mac mints codes from.const CROCKFORD: &str = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";/// Upper-case, drop spaces and hyphens, fold the confusables; `None`/// off-alphabet.////// The upper-casing is JavaScript's `toUpperCase()`, which is the full Unicode/// mapping and can LENGTHEN a string (`ß` becomes `SS`) — Rust's/// `str::to_uppercase` is the same mapping, so a code typed with one keeps the/// same length on both sides.fn crockford(raw: &str) -> Option<String> {    let mut folded = String::with_capacity(raw.len());    for char in raw.to_uppercase().chars() {        match char {            c if is_js_whitespace(c) || c == '-' => continue,            'I' | 'L' => folded.push('1'),            'O' => folded.push('0'),            c => folded.push(c),        }    }    folded        .chars()        .all(|char| CROCKFORD.contains(char))        .then_some(folded)}/// The consent page's user code as `XXXX-XXXX`, or `None`.////// The ONE caller of [`crockford`] now that the pairing code is retired. It/// used to fold through a public `normalize_pairing_code`, which the join form/// and `cotton-pair:` both called; a join carries no code any more, and a/// second public entry point into this alphabet would be a shape somebody/// re-grows a typed-code join out of.pub fn normalize_user_code(raw: &str) -> Option<String> {    let code = crockford(raw).filter(|code| code.len() == 8)?;    Some(format!("{}-{}", &code[..4], &code[4..]))}/// What a device is — the server's own three (`DeviceRow.platform`).////// Declared here rather than in [`crate::constants`] because the TypeScript/// declares it here too: `DEVICE_PLATFORMS` is this module's own list, not one/// of `constants.ts`'s string unions.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum DevicePlatform {    #[serde(rename = "ios")]    Ios,    #[serde(rename = "android")]    Android,    #[serde(rename = "mac")]    Mac,    #[serde(rename = "linux")]    Linux,}impl DevicePlatform {    pub const fn as_str(self) -> &'static str {        match self {            Self::Ios => "ios",            Self::Android => "android",            Self::Mac => "mac",            Self::Linux => "linux",        }    }    /// In the TypeScript's declared order.    pub const ALL: [DevicePlatform; 4] = [Self::Ios, Self::Android, Self::Mac, Self::Linux];    pub fn parse(value: &str) -> Option<Self> {        Self::ALL.into_iter().find(|kind| kind.as_str() == value)    }}impl std::fmt::Display for DevicePlatform {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.write_str(self.as_str())    }}/// The version every payload carries, and the only one any of them parses.////// The TypeScript types the field as the literal `1`; the port keeps it off the/// structs for the same reason — a caller cannot build a `v: 2` payload, and a/// reader refuses one.pub const PAYLOAD_VERSION: u64 = 1;/// `cotton-oauth:` — a server plus the consent page's `XXXX-XXXX` user code.#[derive(Debug, Clone, PartialEq, Eq)]pub struct OauthPayload {    pub server: String,    pub code: String,}const OAUTH: &str = "cotton-oauth:";/// The JSON after a prefix, as an object.////// `None` when the prefix is absent, when the text is not JSON, or when it is/// not an object. A JSON array is `typeof "object"` in JavaScript and reaches/// the field checks, which then refuse it for having no `v`; here it stops one/// step earlier and the answer is the same refusal.fn json_after(prefix: &str, raw: &str) -> Option<Map<String, Value>> {    let body = raw.strip_prefix(prefix)?;    match serde_json::from_str::<Value>(body).ok()? {        Value::Object(fields) => Some(fields),        _ => None,    }}/// `o.v !== 1` — a JSON `1.0` is the same Number as `1` in JavaScript, so both/// pass; the string `"1"` does not.fn version_is_one(fields: &Map<String, Value>) -> bool {    fields.get("v").and_then(Value::as_f64) == Some(PAYLOAD_VERSION as f64)}fn string_field<'a>(fields: &'a Map<String, Value>, key: &str) -> Option<&'a str> {    fields.get(key).and_then(Value::as_str)}/// `JSON.stringify` over the payload, in the key order the TypeScript writes.////// The order is observable — these strings are what a QR symbol carries and/// what the tests pin — so the object is built as an ordered map (the/// workspace turns on serde_json's `preserve_order`) and rendered through the/// store's `json_stringify`, which is JavaScript's escaping rather than/// serde's number formatting.fn payload_json(prefix: &str, fields: Vec<(&str, Value)>) -> String {    let mut object = Map::new();    object.insert("v".to_string(), Value::from(PAYLOAD_VERSION));    for (key, value) in fields {        object.insert(key.to_string(), value);    }    format!("{prefix}{}", json_stringify(&Value::Object(object)))}pub fn build_oauth_payload(payload: &OauthPayload) -> String {    payload_json(        OAUTH,        vec![            ("server", Value::from(payload.server.as_str())),            ("code", Value::from(payload.code.as_str())),        ],    )}pub fn parse_oauth_payload(raw: &str) -> Option<OauthPayload> {    let fields = json_after(OAUTH, raw)?;    if !version_is_one(&fields) {        return None;    }    let server = string_field(&fields, "server")?;    let code = string_field(&fields, "code")?;    relay_name_of(server)?;    Some(OauthPayload {        server: server.to_string(),        code: normalize_user_code(code)?,    })}#[cfg(test)]#[path = "pairing_tests.rs"]mod tests;