Cotton code
405 lines · 21.5 KB · RustRaw
//! A personal object in memory, as the importer speaks to it: the served//! definitions, `GET /v1/sync` of some tables, the `import_rows` act and the//! plain writes, media by key. It keeps what it is sent exactly as sent, so//! a test can grep everything it holds and everything it heard.#![allow(dead_code)]use std::collections::BTreeMap;use std::sync::{Arc, Mutex};use serde_json::{json, Map, Value};use super::{Answer, Request, TestServer};#[derive(Debug, Clone, Default)]pub struct Held {    pub data: Map<String, Value>,    pub version: i64,    pub deleted: bool,    pub created_at: String,    pub updated_at: String,    pub blind: Vec<String>,}#[derive(Default)]pub struct State {    pub version: i64,    pub rows: BTreeMap<(String, String), Held>,    pub media: BTreeMap<String, Vec<u8>>,    /// The type each file was put as.    pub media_types: BTreeMap<String, String>,    pub tables: Vec<Value>,    pub business: Value,    /// Every `assistant_add` wrap the object took: (grant id, wrap), as the Worker's `agent_wrap` keeps them.    pub wraps: Vec<(String, String)>,    /// The next this many requests are answered `away_status`, whatever they ask.    pub away_for: usize,    pub away_status: u16,    /// The next writes (`create`, `update`, or an `import_rows` carrying a row of it) to this table, this many, answered 500 "the business did not    /// answer", as the object answered a write while it was busy (SYNC GAP, 25 Nov 2026).    pub busy_writes: Option<(String, usize)>,    /// Kind → the devices `GET /v1/media-plain` names as holding its reseal back (an app from before that reads it).    pub plain_waiting: BTreeMap<String, Vec<String>>,}/// The Worker's own limits on one `import_rows` call (apps/business/src/business.ts `IMPORT_ROWS`, seal.ts/// `BLIND_PER_CALL`): a fake that takes more says OK where the object refuses (FAKES AUDIT, 24 Nov 2026).pub const IMPORT_ROWS: usize = 500;pub const BLIND_PER_CALL: usize = 2_000;/// What a sealed row carries besides its clear columns (seal.ts `SEAL_FIELDS`).const SEAL_FIELDS: [&str; 3] = ["sealed_enc", "dek_enc", "seal_v"];impl State {    /// The object's refusal of a device's write of `data` to `table`, as `refuseDeviceClear` gives it: no such    /// table (404), a key the table has no column for (400 `bad_column`, refused, never dropped), or a sealed    /// column said in the clear (400 `sealed_in_clear`).    fn refuses(&self, table: &str, data: &Map<String, Value>) -> Option<Answer> {        let Some(def) = self.tables.iter().find(|t| t["id"] == json!(table)) else {            return Some(Answer::json(404, json!({ "code": "no_such_table", "message": format!("no table {table}") })));        };        let columns: Vec<&str> = def["columns"].as_array().into_iter().flatten().filter_map(|c| c["key"].as_str()).collect();        let sealed = def.get("seal").filter(|s| s.is_object());        if let Some(stray) = data.keys().find(|k| !columns.contains(&k.as_str()) && !(sealed.is_some() && SEAL_FIELDS.contains(&k.as_str()))) {            return Some(Answer::json(400, json!({ "code": "bad_column", "message": format!("{table} has no column {stray:?}") })));        }        if let Some(seal) = sealed {            let clear: Vec<&str> = seal["clear"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();            let said: Vec<&String> = data.keys().filter(|k| columns.contains(&k.as_str()) && !clear.contains(&k.as_str())).collect();            if !said.is_empty() {                return Some(Answer::json(400, json!({ "code": "sealed_in_clear", "message": format!("{table} keeps {said:?} sealed: a device sends them only inside sealed_enc") })));            }        }        None    }    pub fn live(&self, table: &str) -> Vec<(String, Held)> {        self.rows            .iter()            .filter(|((t, _), held)| t == table && !held.deleted)            .map(|((_, id), held)| (id.clone(), held.clone()))            .collect()    }    fn put(&mut self, table: &str, id: &str, data: &Map<String, Value>, blind: Option<&Value>, created: Option<&str>, updated: Option<&str>) {        self.version += 1;        let version = self.version;        let entry = self.rows.entry((table.to_string(), id.to_string())).or_default();        if entry.deleted || entry.version == 0 {            *entry = Held { created_at: created.unwrap_or("2026-11-11T00:00:00.000Z").to_string(), ..Held::default() };        }        for (key, value) in data {            entry.data.insert(key.clone(), value.clone());        }        entry.version = version;        entry.updated_at = updated.unwrap_or("2026-11-11T00:00:00.000Z").to_string();        if let Some(Value::Array(tokens)) = blind {            entry.blind = tokens.iter().filter_map(|t| t.as_str().map(str::to_string)).collect();        }    }    fn retract(&mut self, table: &str, id: &str) {        self.version += 1;        if let Some(entry) = self.rows.get_mut(&(table.to_string(), id.to_string())) {            entry.deleted = true;            entry.version = self.version;            entry.blind.clear();        }    }}pub struct FakeObject {    pub server: TestServer,    pub state: Arc<Mutex<State>>,}fn query(path: &str) -> BTreeMap<String, String> {    path.split_once('?')        .map(|(_, q)| url::form_urlencoded::parse(q.as_bytes()).into_owned().collect())        .unwrap_or_default()}fn answer(state: &Mutex<State>, request: &Request) -> Answer {    let mut state = state.lock().unwrap();    if state.away_for > 0 {        state.away_for -= 1;        let status = if state.away_status == 0 { 500 } else { state.away_status };        return Answer::json(status, json!({ "code": "internal_error", "message": "the business did not answer" }));    }    let route = request.path.split('?').next().unwrap_or("").to_string();    match (request.method.as_str(), route.as_str()) {        ("GET", "/v1/definitions") => Answer::json(200, json!({ "business": state.business, "tables": state.tables, "tools": [] })),        ("GET", "/v1/me") => Answer::json(200, json!({})),        ("GET", "/v1/sync") => {            let q = query(&request.path);            let since: i64 = q.get("since").and_then(|s| s.parse().ok()).unwrap_or(0);            let tables: Vec<String> = q.get("tables").map(|t| t.split(',').map(str::to_string).collect()).unwrap_or_default();            let rows: Vec<Value> = state                .rows                .iter()                .filter(|((t, _), held)| held.version > since && (tables.is_empty() || tables.contains(t)))                .map(|((t, id), held)| {                    let mut row = json!({ "table": t, "id": id, "data": held.data, "version": held.version, "created_at": held.created_at, "updated_at": held.updated_at });                    if held.deleted {                        row["deleted"] = json!(true);                    }                    row                })                .collect();            Answer::json(200, json!({ "version": state.version, "rows": rows }))        }        ("GET", "/v1/outbox") => {            let status = query(&request.path).get("status").cloned().unwrap_or_else(|| "queued".into());            let rows: Vec<Value> = state                .live("outbox")                .into_iter()                .filter(|(_, held)| held.data.get("status") == Some(&json!(status)))                .map(|(id, held)| json!({ "table": "outbox", "id": id, "data": held.data, "version": held.version }))                .collect();            Answer::json(200, json!({ "rows": rows }))        }        ("POST", "/v1/act") => {            let body = request.json();            let args = &body["args"];            match body["act"].as_str().unwrap_or_default() {                "import_rows" => {                    let rows = args["rows"].as_array().cloned().unwrap_or_default();                    if let Some((busy, left)) = state.busy_writes.as_mut() {                        if *left > 0 && rows.iter().any(|r| r["table"].as_str() == Some(busy.as_str())) {                            *left -= 1;                            return Answer::json(500, json!({ "code": "internal_error", "message": "the business did not answer" }));                        }                    }                    if rows.len() > IMPORT_ROWS {                        return Answer::json(413, json!({ "code": "too_many", "message": format!("import at most {IMPORT_ROWS} rows per call") }));                    }                    let tokens: usize = rows.iter().map(|r| r["blind"].as_array().map_or(0, Vec::len)).sum();                    if rows.len() > 1 && tokens > BLIND_PER_CALL {                        return Answer::json(413, json!({ "code": "too_large", "message": format!("a call carries at most {BLIND_PER_CALL} blind tokens ({tokens} over {} rows)", rows.len()) }));                    }                    // One transaction: a refused row refuses the call, and nothing of it is kept.                    for row in rows.iter().filter(|r| r["retract"] != json!(true)) {                        let data = row["data"].as_object().cloned().unwrap_or_default();                        if let Some(refused) = state.refuses(row["table"].as_str().unwrap_or_default(), &data) {                            return refused;                        }                    }                    for row in args["rows"].as_array().into_iter().flatten() {                        let (table, id) = (row["table"].as_str().unwrap(), row["id"].as_str().unwrap());                        if row["retract"] == json!(true) {                            state.retract(table, id);                        } else {                            let data = row["data"].as_object().cloned().unwrap_or_default();                            state.put(table, id, &data, row.get("blind"), row["created_at"].as_str(), row["updated_at"].as_str());                        }                    }                    Answer::json(200, json!({ "version": state.version, "made": {}, "changed": {} }))                }                act @ ("create" | "update") => {                    let (table, id) = (args["table"].as_str().unwrap_or_default(), args["id"].as_str().unwrap_or_default());                    if let Some((busy, left)) = state.busy_writes.as_mut() {                        if busy == table && *left > 0 {                            *left -= 1;                            return Answer::json(500, json!({ "code": "internal_error", "message": "the business did not answer" }));                        }                    }                    let held = state.rows.get(&(table.to_string(), id.to_string())).is_some_and(|h| !h.deleted);                    if act == "create" && held {                        return Answer::json(409, json!({ "code": "duplicate_id", "message": "taken" }));                    }                    if act == "update" && !held {                        return Answer::json(404, json!({ "code": "no_such_record", "message": "no row" }));                    }                    let data = args["data"].as_object().cloned().unwrap_or_default();                    if let Some(refused) = state.refuses(table, &data) {                        return refused;                    }                    state.put(table, id, &data, args.get("blind"), None, None);                    Answer::json(200, json!({ "version": state.version, "changed": [] }))                }                // As the Worker's agent.ts `add` refuses (FAKES AUDIT): no such grant, a grant that is not a live                // grant to your Claude, no table, a table its policy withholds or saved secrets, a wrap not "w1:".                "assistant_add" => {                    let grant_id = args["grant_id"].as_str().unwrap_or_default().to_string();                    let Some(grant) = state.rows.get(&("unlock_grant".to_string(), grant_id.clone())).filter(|h| !h.deleted).cloned() else {                        return Answer::json(404, json!({ "code": "no_such_grant", "message": "no such grant" }));                    };                    if grant.data.get("account") != Some(&json!(true)) || grant.data.get("ended_at").is_some_and(|v| !v.is_null()) {                        return Answer::json(409, json!({ "code": "grant_ended", "message": "not a live grant to your Claude" }));                    }                    let tables: Vec<String> = args["tables"].as_array().into_iter().flatten().filter_map(|t| t.as_str().map(str::to_string)).collect();                    if tables.is_empty() {                        return Answer::json(400, json!({ "code": "bad_args", "message": "an addition hands at least one table's keys" }));                    }                    let list = |key: &str| -> Vec<String> { grant.data.get(key).and_then(Value::as_array).into_iter().flatten().filter_map(|t| t.as_str().map(str::to_string)).collect() };                    let withheld = list("withheld");                    if tables.iter().any(|t| withheld.contains(t) || ["code_credential", "passkey", "secret"].contains(&t.as_str())) {                        return Answer::json(403, json!({ "code": "withheld", "message": "withheld from your Claude" }));                    }                    let wrapped = args["wrapped"].as_str().unwrap_or_default().to_string();                    if !wrapped.starts_with("w1:") {                        return Answer::json(400, json!({ "code": "bad_args", "message": "wrapped is the w1: wrap" }));                    }                    state.wraps.push((grant_id.clone(), wrapped));                    let mut now = list("tables");                    now.extend(tables);                    now.sort();                    now.dedup();                    let patch = json!({ "tables": now }).as_object().cloned().unwrap();                    state.put("unlock_grant", &grant_id, &patch, None, None, None);                    Answer::json(200, json!({ "version": state.version, "changed": [] }))                }                "delete" => {                    state.retract(args["table"].as_str().unwrap_or_default(), args["id"].as_str().unwrap_or_default());                    Answer::json(200, json!({ "version": state.version, "changed": [] }))                }                other => Answer::json(400, json!({ "code": "unknown_act", "message": other })),            }        }        // apps/business `mediaPlain`: this database's plain files of the kind, a page at a time; while a device        // that reads the kind is on an app from before (`plain_waiting`), the devices named and nothing listed.        ("GET", "/v1/media-plain") => {            let q = query(&request.path);            let kind = q.get("kind").cloned().unwrap_or_default();            if !["messages", "people"].contains(&kind.as_str()) {                return Answer::json(400, json!({ "code": "bad_request", "message": "kind is one of messages, people" }));            }            if let Some(waiting) = state.plain_waiting.get(&kind) {                return Answer::json(200, json!({ "files": [], "next": null, "waiting": waiting }));            }            let database = state.business["database_id"].as_str().unwrap_or_default().to_string();            let limit: usize = q.get("limit").and_then(|l| l.parse().ok()).unwrap_or(100).clamp(1, 1000);            let after = q.get("after").cloned();            let prefix = format!("{database}/{kind}/");            let files: Vec<Value> = state                .media                .iter()                .filter(|(key, _)| key.starts_with(&prefix) && after.as_ref().is_none_or(|a| key.as_str() > a.as_str()))                .filter(|(key, _)| state.media_types.get(*key).map(String::as_str) != Some("application/vnd.cotton.f1"))                .take(limit)                .map(|(key, bytes)| json!({ "key": key, "bytes": bytes.len() }))                .collect();            let next = if files.len() >= limit { files.last().map(|f| f["key"].clone()).unwrap_or(Value::Null) } else { Value::Null };            Answer::json(200, json!({ "files": files, "next": next }))        }        ("POST", "/v1/media/missing") => {            let body = request.json();            let sealed = body["sealed"] == json!(true);            let missing: Vec<&str> = body["keys"]                .as_array()                .into_iter()                .flatten()                .filter_map(Value::as_str)                .filter(|key| !state.media.contains_key(*key) || (sealed && state.media_types.get(*key).map(String::as_str) != Some("application/vnd.cotton.f1")))                .collect();            Answer::json(200, if sealed { json!({ "missing": missing, "sealed": true }) } else { json!({ "missing": missing }) })        }        ("HEAD" | "GET", path) if path.starts_with("/v1/media/") => {            let key = path.trim_start_matches("/v1/media/").to_string();            let Some(bytes) = state.media.get(&key) else { return Answer::empty(404) };            let kind = state.media_types.get(&key).cloned().or(Some("application/octet-stream".to_string()));            // `Range: bytes=a-b`, as the object answers one.            let range = request.header("range").and_then(|r| r.strip_prefix("bytes=")).and_then(|r| r.split_once('-')).and_then(|(a, b)| Some((a.parse::<usize>().ok()?, b.parse::<usize>().ok()?)));            match range {                Some((from, to)) => Answer { status: 206, body: bytes[from.min(bytes.len())..(to + 1).min(bytes.len())].to_vec(), kind },                None => Answer { status: 200, body: bytes.clone(), kind },            }        }        ("PUT", path) if path.starts_with("/v1/media/") => {            let key = path.trim_start_matches("/v1/media/").to_string();            if let Some(kind) = request.header("content-type") {                state.media_types.insert(key.clone(), kind.to_string());            }            state.media.insert(key, request.body.clone());            Answer::json(200, json!({ "stored": true }))        }        _ => Answer::json(404, json!({ "code": "not_found", "message": format!("no route {} {}", request.method, request.path) })),    }}impl FakeObject {    /// An object of `database_id` owned by `owner_phone`, holding `tables`.    pub fn start(database_id: &str, owner_phone: &str, tables: Vec<Value>) -> FakeObject {        let state = Arc::new(Mutex::new(State {            tables,            business: json!({ "database_id": database_id, "owner_phone": owner_phone, "namespace": database_id, "kind": "personal" }),            ..State::default()        }));        let held = Arc::clone(&state);        let server = TestServer::start(move |request| answer(&held, request));        FakeObject { server, state }    }    /// Everything the object holds of rows (their data, as kept) and every    /// byte it was sent, as one text for a guard to grep.    pub fn everything(&self) -> String {        let state = self.state.lock().unwrap();        let mut out = String::new();        for ((table, id), held) in &state.rows {            out.push_str(&format!("{table} {id} {}\n", Value::Object(held.data.clone())));        }        for request in self.server.requests() {            out.push_str(&request.path);            out.push('\n');            out.push_str(&String::from_utf8_lossy(&request.body));            out.push('\n');        }        out    }    /// The row erased as the object erases one: a tombstone with nothing of what it held.    pub fn erase_row(&self, table: &str, id: &str) {        let mut state = self.state.lock().unwrap();        state.retract(table, id);        if let Some(entry) = state.rows.get_mut(&(table.to_string(), id.to_string())) {            entry.data.clear();        }    }    pub fn put_row(&self, table: &str, id: &str, data: Value) {        let data = data.as_object().cloned().unwrap();        self.state.lock().unwrap().put(table, id, &data, None, None, None);    }}/// The kit's own definition of `table` (crates/cotton-core/kits/personal/tables)./// Open, as an object serves it before the kit's seal reaches it: the kit's/// own `seal` block is left out (a sealed fixture says its block itself).pub fn kit_table(table: &str) -> Value {    let mut def = kit_sealed_table(table);    if let Some(def) = def.as_object_mut() {        def.remove("seal");    }    def}/// The kit's definition of `table` exactly as it ships, its `seal` block with it.pub fn kit_sealed_table(table: &str) -> Value {    let path = cotton_store::manifest_dir().join("../cotton-core/kits/personal/tables").join(format!("{table}.json"));    serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()}/// The kit's definition of `table` with a seal block: `clear` stays clear,/// `blind` gets word tokens, `exact` exact ones, every other column sealed.pub fn sealed_table(table: &str, clear: &[&str], blind: &[&str], exact: &[&str]) -> Value {    let mut def = kit_table(table);    def["seal"] = json!({ "clear": clear, "blind": blind, "blind_exact": exact });    def}/// The messages kit's tables sealed as the kit ships them (lane/// seal-messages-mail), plus people sealed as the sealing plan's §1 table says.pub fn sealed_messages() -> Vec<Value> {    vec![        kit_sealed_table("thread"),        kit_sealed_table("message"),        kit_sealed_table("thread_member"),        kit_sealed_table("message_reaction"),        kit_sealed_table("message_contact"),        kit_sealed_table("message_contact_handle"),        sealed_table("person", &["archived_at", "trashed_at", "avatar_photo_id", "birthday"], &["full_name"], &[]),        sealed_table("person_handle", &["person_id", "trashed_at"], &[], &["normalised"]),        kit_sealed_table("call"),        kit_table("seal_key"),    ]}