Cotton code
294 lines · 11.5 KB · RustRaw
//! The owner's own server, asked from the phone — the ONE seam five method//! families share.//!//! ## Why these are methods at all//!//! Every route below is one a screen has to reach, and the Swift app has no//! `fetch` and must not grow one://! `apps/cotton/Sources/CottonUI/Join/JoinModel.swift` says *"every byte//! goes through Rust. There is no `URLSession` anywhere in this app"*, and a//! grep over `Sources/` finds that sentence and nothing else. So a screen//! reaches the server through a method here.//!//! They are not `read.*` and they are not `write`, and the reason is the same//! for all five families: **the answer is not in the person's file.** The device//! registry is `registry.db` on the server and deliberately never in the//! workspace (Cotton note "Devices — how a machine is admitted to your database"); an OAuth request lives for ninety//! seconds on the server and is never written down; Google's connection state is//! what the server's worker last saw. `read.*` answers from the replica. These//! cannot.//!//! ## The precedent, followed exactly//!//! `join.setName` (`phone/commands.rs`) is `PATCH /v1/me`: validate on this//! side for the keyboard's sake, one [`ClientRequest`], map the refusal's code//! and message into a [`MethodError`]. Everything here is that, factored so the//! five families cannot drift about what a refusal looks like.//!//! **One thing this adds to that precedent, deliberately**: the refusal carries//! the STATUS in its details. `useApprovedDevices` does not retry a 4xx//! (`queries/devices.ts`) — a 401 becomes a sentence rather than a permanent//! skeleton — and a `MethodError` that dropped the status would leave the app//! unable to tell a refusal it should stop asking about from one it should.//!//! ## What is NOT here//!//! The address. [`ClientRequest::path`] is "path and query, never an origin"//! and that is the whole reason `cotton_client::connection` exists: one owner//! of "which server this device talks to", with the device signature and the//! terminal refusal note under it. A family here//! that spelled an origin would be a second opinion about which server this is.//! The one call in this lane that legitimately names another origin — the city//! geocoder — is [`super::city`], over the plain wire, unsigned, and it says so.use cotton_client::transport::{ClientAnswer, ClientRequest, ServerFetch, ServerRefusal};use serde_json::{json, Map, Value};use crate::handle::CottonHandle;use crate::methods::MethodError;/// What a phone with no readable device key is told, in the words the three/// commands already use.pub const NO_DEVICE_IDENTITY: &str = "this phone has no device identity to sign with";/// The code a refusal wears when the server sent none of its own.////// Named rather than invented per call site: six families answering six/// different words for "the server said no with no code" is six sentences an/// app has to learn.pub const SERVER_REFUSED: &str = "server_refused";/// Run one owner call with the signed transport installed on the client, or/// refuse with `device_key_unreadable` when none is.pub fn with_fetch<T>(    handle: &CottonHandle,    work: impl FnOnce(&dyn ServerFetch) -> Result<T, MethodError>,) -> Result<T, MethodError> {    let Some(fetch) = handle.client().fetch() else {        return Err(MethodError::new(            "device_key_unreadable",            NO_DEVICE_IDENTITY,        ));    };    work(fetch.as_ref())}/// One call, answered as JSON.////// An empty body answers `null` rather than a parse failure: a `DELETE` answers/// `204` where a sibling answers `{ ok: true }`, and a caller that only wanted to/// know it worked should not have to care which.pub fn send(fetch: &dyn ServerFetch, request: ClientRequest) -> Result<Value, MethodError> {    let answer = fetch.call(request).map_err(refused)?;    read_json(&answer)}fn read_json(answer: &ClientAnswer) -> Result<Value, MethodError> {    if answer.body.iter().all(u8::is_ascii_whitespace) {        return Ok(Value::Null);    }    serde_json::from_slice(&answer.body).map_err(|error| {        MethodError::new(            "unreadable_answer",            format!("the server's answer could not be read: {error}"),        )    })}/// A server's refusal, as an app can draw it.////// The server's own `code` when it sent one, because that is what the screens/// branch on — the sharing screen's refusal map is CLOSED over those codes/// (`tools/sharing/lib/errors.ts`) and an invented word would fall through it/// to a generic toast.pub fn refused(refusal: ServerRefusal) -> MethodError {    let mut details = json!({ "status": refusal.status });    if refusal.status == 409 && refusal.code.as_deref() == Some("connection_exists") {        if let Some(id) = refusal            .existing_connection_id            .as_deref()            .map(str::trim)            .filter(|id| !id.is_empty())        {            details["id"] = json!(id);        }    }    if let Some(seconds) = refusal.retry_after_seconds {        details["retryAfterSeconds"] = json!(seconds);    }    let transport_prefix = format!("server {}: ", refusal.status);    let message = refusal        .message        .strip_prefix(&transport_prefix)        .unwrap_or(&refusal.message);    MethodError::new(refusal.code.as_deref().unwrap_or(SERVER_REFUSED), message)        .with_details(details)}// ── the arguments, checked on this side ───────────────────────────────────//// For the KEYBOARD's sake, exactly as `join.setName` says: the server's check// is the authority and this one is the field's, so a person sees the refusal// under what they typed rather than after a round trip./// A required, non-blank string argument.pub fn text(request: &Value, name: &str) -> Result<String, MethodError> {    optional_text(request, name)        .ok_or_else(|| MethodError::new("bad_request", format!("`{name}` is required")))}/// The same, when absence is a legitimate answer.pub fn optional_text(request: &Value, name: &str) -> Option<String> {    request        .get(name)        .and_then(Value::as_str)        .map(str::trim)        .filter(|value| !value.is_empty())        .map(str::to_string)}/// A `true`/`false` argument, absent reading as `false`.pub fn flag(request: &Value, name: &str) -> bool {    request.get(name) == Some(&Value::Bool(true))}/// The JSON body of a request, as bytes.pub fn body(value: &Value) -> Vec<u8> {    serde_json::to_vec(value).unwrap_or_else(|_| b"{}".to_vec())}/// A POST with a body — including the three routes whose body is an empty/// object.////// `{}` rather than nothing, and it matters: the signature hashes the bytes as/// sent, so a decline that sent no body would be signed over a different/// message than the one the server reads (`serverTransport.ts` sends `{}` for/// the decline and both invitation verbs).pub fn post(path: String, value: &Value) -> ClientRequest {    ClientRequest {        method: "POST",        path,        body: Some(body(value)),        content_type: Some("application/json"),        accept_encoding: None,        ceiling_ms: None,        range: None,    }}pub fn patch(path: String, value: &Value) -> ClientRequest {    ClientRequest {        method: "PATCH",        path,        body: Some(body(value)),        content_type: Some("application/json"),        accept_encoding: None,        ceiling_ms: None,        range: None,    }}pub fn put(path: String, value: &Value) -> ClientRequest {    ClientRequest {        method: "PUT",        path,        body: Some(body(value)),        content_type: Some("application/json"),        accept_encoding: None,        ceiling_ms: None,        range: None,    }}/// A DELETE with no body.pub fn delete(path: String) -> ClientRequest {    ClientRequest {        method: "DELETE",        path,        body: None,        content_type: None,        accept_encoding: None,        ceiling_ms: None,        range: None,    }}/// One path segment, escaped the way `encodeURIComponent` escapes it.////// An id that reaches a path here is not this code's to assume anything about —/// a device id, a Google account, an OAuth request. The signature is over the/// path AS SENT, so an unescaped character would be signed as one thing and/// routed as another.////// The unreserved set is `encodeURIComponent`'s exactly: the alphanumerics plus/// `- _ . ! ~ * ' ( )`. `/` is NOT in it, which is the point.pub fn segment(value: &str) -> String {    let mut escaped = String::with_capacity(value.len());    for byte in value.as_bytes() {        let keep = byte.is_ascii_alphanumeric()            || matches!(                byte,                b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')'            );        if keep {            escaped.push(*byte as char);        } else {            escaped.push_str(&format!("%{byte:02X}"));        }    }    escaped}/// A closed vocabulary, checked here rather than trusted.////// `parseMcpScopes` THROWS on an unknown word rather than dropping it/// (`packages/core/src/constants.ts`), and this keeps that shape: a token/// minted with a scope nobody declared is a grant nobody can reason about.pub fn one_of(value: &str, allowed: &[&str], name: &str) -> Result<String, MethodError> {    if allowed.contains(&value) {        return Ok(value.to_string());    }    Err(MethodError::new(        "bad_request",        format!("`{name}` is one of {}", allowed.join(", ")),    ))}/// An object argument, for a caller handing over a whole shape.pub fn object(request: &Value, name: &str) -> Option<Map<String, Value>> {    request.get(name).and_then(Value::as_object).cloned()}/// Send this device's edits first, then prove every home in the transfer has/// no queued, held, or parked push. The signed act runs outside file holds.pub(crate) fn with_sent_files<T>(    client: &crate::shell::client::ClientController,    files: impl FnOnce() -> Result<Vec<String>, MethodError>,    act: impl FnOnce() -> Result<T, MethodError>,) -> Result<T, MethodError> {    let sync_error = client.sync_now().err();    let held = client.databases().map_err(|e| MethodError::new("unreadable", e))?;    let mut checked = std::collections::BTreeSet::new();    for requested in files()? {        let matches: Vec<_> = match held.iter().find(|d| d.id == requested) {            Some(exact) => vec![exact],            None => held.iter().filter(|d| d.name == requested).collect(),        };        let [database] = matches.as_slice() else {            return Err(MethodError::new("database_not_found", "Choose one database held on this device."));        };        if !checked.insert(database.id.clone()) { continue; }        let pending = client.with_file_in(&database.id, |file| {            cotton_store::runner_change::claim_of(file.driver, file.workspace_id, file.device_id)                .map(|claim| claim.unsent).map_err(|e| e.to_string())        }).map_err(|e| MethodError::new("unreadable", e))?;        if pending > 0 {            return Err(MethodError::new("unsent_write", "This database still has edits to send. Sync them before filing or undoing the move.").with_details(json!({"database":database.id,"pending":pending})));        }    }    if checked.is_empty() {        return Err(MethodError::new("bad_request", "A transfer needs its record homes."));    }    if let Some(error) = sync_error { return Err(MethodError::new("send_first_failed", error)); }    act()}