Cotton code
340 lines · 17.5 KB · RustRaw
//! Account › Assistants › one assistant: what each of the account's keys may do (ADMIN KEYS 3). The core side of the//! screen; the shells draw what it answers. The words are `unlock.json` `account.may_do.*`.//!//! - `assistant.keys {}` → `{ title, keys: [{ id, title, line, act }], empty }`: every live assistant connection (an//!   OAuth connection once, however many refreshes it holds; a pasted key on its own), each with the preset it stands//!   at as its line. Asked of the object (`GET /v1/keys`): token rows never sync to a phone. Signed out: `sign_in_first`.//! - `assistant.key { id }` → one assistant: `{ id, title, preset, presets, more, note }`. Presets a person understands//!   first ("Everything I allow from my phone", "Only its own memory", "Read only"), the table list under `more`.//! - `assistant.allow { id, preset }` or `{ id, allow: { read, write, outward, acts } }` → sets it through the object's//!   `token_allow` (the owner's own device: a key never does), and answers `{ said, preset, undo }`.//!//! A key with no allow stands at "Everything I allow from my phone": it is as every key was before allows (its scopes//! alone, the phone's grants deciding every locked table), so nothing a person had changes until they choose.use std::collections::BTreeMap;use serde_json::{json, Map, Value};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::shell::client::ClientController;pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    let client = handle.client();    match method {        "assistant.keys" => keys(&client),        "assistant.key" => key(&client, request),        "assistant.allow" => allow(&client, request),        _ => Err(MethodError::new("unknown_method", format!("`{method}` is not an assistant key method"))),    }}/// The tables an assistant keeps for itself: its notes (memory) and your sessions with it (`key_allow.DEFAULT_ALLOW`).const OWN_READ: [&str; 7] = ["memory", "project", "project_link", "prompt", "session", "session_message", "session_task"];const OWN_WRITE: [&str; 5] = ["memory", "prompt", "session", "session_message", "session_task"];/// Tables no key ever reads or writes (`key_allow` NEVER): never listed.const NEVER: [&str; 8] = ["mcp_token", "oauth_client", "oauth_code", "oauth_refresh", "device", "vault_key", "seal_key", "person_key"];/// What `acts` may name (`key_allow.GRANTABLE_ACTS`).const GRANTABLE: [&str; 1] = ["update_definition"];/// The presets, in the order the screen offers them.const PRESETS: [&str; 3] = ["everything", "memory", "read_only"];/// A key's allow as the object keeps it, or None for a key with none (as every key was: "everything").#[derive(Debug, Clone, PartialEq)]struct Allow {    read: Tables,    write: Tables,    outward: bool,    sealed: bool,    acts: Vec<String>,}#[derive(Debug, Clone, PartialEq)]enum Tables {    All,    Some(Vec<String>),}impl Tables {    fn of(value: &Value) -> Tables {        match value {            Value::String(s) if s == "*" => Tables::All,            Value::Array(items) => {                let mut out: Vec<String> = items.iter().filter_map(Value::as_str).map(str::to_string).collect();                out.sort();                out.dedup();                Tables::Some(out)            }            _ => Tables::Some(Vec::new()),        }    }    fn list(items: &[&str]) -> Tables {        let mut out: Vec<String> = items.iter().map(|s| s.to_string()).collect();        out.sort();        Tables::Some(out)    }    fn json(&self) -> Value {        match self {            Tables::All => json!("*"),            Tables::Some(items) => json!(items),        }    }    fn has(&self, table: &str) -> bool {        match self {            Tables::All => true,            Tables::Some(items) => items.iter().any(|t| t == table),        }    }}impl Allow {    fn of(value: &Value) -> Option<Allow> {        let object = value.as_object()?;        Some(Allow {            read: Tables::of(object.get("read").unwrap_or(&Value::Null)),            write: Tables::of(object.get("write").unwrap_or(&Value::Null)),            outward: object.get("outward").and_then(Value::as_bool).unwrap_or(false),            sealed: object.get("sealed").and_then(Value::as_bool).unwrap_or(false),            acts: object.get("acts").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default(),        })    }    fn json(&self) -> Value {        json!({ "read": self.read.json(), "write": self.write.json(), "outward": self.outward, "sealed": self.sealed, "acts": self.acts })    }}/// A preset's allow: None is "everything" (a key as before allows).fn preset(id: &str) -> Option<Option<Allow>> {    match id {        "everything" => Some(None),        "memory" => Some(Some(Allow { read: Tables::list(&OWN_READ), write: Tables::list(&OWN_WRITE), outward: false, sealed: true, acts: Vec::new() })),        "read_only" => Some(Some(Allow { read: Tables::All, write: Tables::list(&OWN_WRITE), outward: false, sealed: true, acts: Vec::new() })),        _ => None,    }}/// The preset a key stands at, or "custom".fn preset_of(allow: &Option<Allow>) -> &'static str {    PRESETS.iter().copied().find(|id| preset(id).as_ref() == Some(allow)).unwrap_or("custom")}fn lines(client: &ClientController) -> Result<cotton_core::rules::shell_lines::LineSet, MethodError> {    super::unlock::lines_of(client)}fn say(lines: &cotton_core::rules::shell_lines::LineSet, key: &str, fills: &[(&str, &str)]) -> String {    lines.say(&format!("account.may_do.{key}"), fills).unwrap_or_default()}fn unreadable(why: String) -> MethodError {    MethodError::new("unreadable", why)}/// One assistant connection: its newest live token (the one `token_allow` is asked of: the object carries it to the/// connection's other tokens).struct Key {    id: String,    name: String,    machine: String,    allow: Option<Allow>,}/// The object's route for the account's keys (`GET /v1/keys`, the owner's own device alone). Token rows never sync to a/// phone (they hold the hashes), so the list is asked of the object, never read from the copy.const KEYS_ROUTE: &str = "/v1/keys";/// Every live connection the object holds, newest first.fn connections(client: &ClientController) -> Result<Vec<Key>, MethodError> {    let door = client.object_door().ok_or_else(|| MethodError::new("sign_in_first", "the account's assistants are kept on the object: sign in first"))?;    keys_of(&door.send("GET", KEYS_ROUTE, None)?)}/// `GET /v1/keys` → `{ keys: [{ id, name, machine, connection_id, allow }] }`, live ones only, newest first. One per/// connection (an OAuth connection's refreshes are one assistant): the first, newest, stands for it.fn keys_of(answer: &Value) -> Result<Vec<Key>, MethodError> {    let rows = answer.get("keys").and_then(Value::as_array).ok_or_else(|| unreadable("the object answered no keys".into()))?;    let text = |row: &Value, key: &str| row.get(key).and_then(Value::as_str).unwrap_or_default().trim().to_string();    let mut by_connection: BTreeMap<String, ()> = BTreeMap::new();    let mut out = Vec::new();    for row in rows {        let id = text(row, "id");        if id.is_empty() {            continue;        }        let connection = Some(text(row, "connection_id")).filter(|c| !c.is_empty()).unwrap_or_else(|| id.clone());        if by_connection.insert(connection, ()).is_some() {            continue;        }        out.push(Key { id, name: text(row, "name"), machine: text(row, "machine"), allow: Allow::of(row.get("allow").unwrap_or(&Value::Null)) });    }    Ok(out)}fn title(lines: &cotton_core::rules::shell_lines::LineSet, key: &Key) -> String {    let name = if key.name.is_empty() { say(lines, "unnamed", &[]) } else { key.name.clone() };    if key.machine.is_empty() { name } else { say(lines, "on_machine", &[("name", &name), ("machine", &key.machine)]) }}/// `assistant.keys {}`.fn keys(client: &ClientController) -> Result<Value, MethodError> {    let lines = lines(client)?;    let keys: Vec<Value> = connections(client)?        .iter()        .map(|key| {            let at = preset_of(&key.allow);            json!({ "id": key.id, "title": title(&lines, key), "line": say(&lines, &format!("presets.{at}"), &[]), "act": { "method": "assistant.key", "request": { "id": key.id } } })        })        .collect();    let empty = keys.is_empty().then(|| say(&lines, "none", &[]));    Ok(json!({ "title": say(&lines, "keys_title", &[]), "keys": keys, "empty": empty }))}fn find(client: &ClientController, request: &Value) -> Result<Key, MethodError> {    let id = request.get("id").and_then(Value::as_str).map(str::trim).filter(|id| !id.is_empty()).ok_or_else(|| MethodError::new("bad_request", "names the assistant: id"))?;    connections(client)?.into_iter().find(|key| key.id == id).ok_or_else(|| MethodError::new("not_found", "no such assistant"))}/// The tables a person may choose between: this copy's tables that a key can be given, by their names.fn choosable(client: &ClientController) -> Result<Vec<(String, String)>, MethodError> {    let found = client        .read_rows("assistant.key.tables", &mut |ctx| {            let definitions = cotton_tools::definitions::shared_table_definitions_from_driver(ctx.db(), ctx.workspace_id).map_err(|failure| failure.to_string())?;            let mut out: Vec<(String, String)> = definitions                .definitions                .iter()                .filter(|d| !NEVER.contains(&d.id.as_str()) && d.has_face())                .map(|d| (d.id.clone(), d.plural.clone()))                .collect();            out.sort_by(|a, b| a.1.to_lowercase().cmp(&b.1.to_lowercase()));            Ok(json!(out))        })        .map_err(unreadable)?;    Ok(serde_json::from_value(found).unwrap_or_default())}/// `assistant.key { id }`.fn key(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let lines = lines(client)?;    let key = find(client, request)?;    let at = preset_of(&key.allow);    let mut presets: Vec<Value> = PRESETS        .iter()        .map(|id| json!({ "id": id, "label": say(&lines, &format!("presets.{id}"), &[]), "sub": say(&lines, &format!("presets.{id}_sub"), &[]), "chosen": *id == at, "act": { "method": "assistant.allow", "request": { "id": key.id, "preset": id } } }))        .collect();    if at == "custom" {        presets.push(json!({ "id": "custom", "label": say(&lines, "presets.custom", &[]), "sub": say(&lines, "presets.custom_sub", &[]), "chosen": true, "act": null }));    }    // Under More: each table it may read and change, outward, and the acts given by name. "Everything" (no allow, or    // "*") is said once, not as every table switched on.    let tables = choosable(client)?;    let (read, write, outward, acts) = match &key.allow {        None => (Tables::All, Tables::All, true, GRANTABLE.iter().map(|a| a.to_string()).collect::<Vec<_>>()),        Some(allow) => (allow.read.clone(), allow.write.clone(), allow.outward, allow.acts.clone()),    };    let rows = |list: &Tables, also: Option<&Tables>| -> Vec<Value> {        tables.iter().map(|(id, label)| json!({ "table": id, "label": label, "on": list.has(id) || also.is_some_and(|a| a.has(id)) })).collect()    };    let more = json!({        "title": say(&lines, "more", &[]),        "read": { "label": say(&lines, "read", &[]), "everything": read == Tables::All || write == Tables::All, "everything_label": say(&lines, "all_tables", &[]), "tables": rows(&read, Some(&write)) },        "write": { "label": say(&lines, "change", &[]), "everything": write == Tables::All, "everything_label": say(&lines, "all_tables", &[]), "tables": rows(&write, None) },        "outward": { "label": say(&lines, "outward", &[]), "sub": say(&lines, "outward_sub", &[]), "on": outward },        "acts": GRANTABLE.iter().map(|a| json!({ "id": a, "label": say(&lines, &format!("acts_named.{a}"), &[]), "sub": say(&lines, &format!("acts_named.{a}_sub"), &[]), "on": acts.iter().any(|x| x == a) })).collect::<Vec<_>>(),        "acts_label": say(&lines, "acts", &[]),        "save": { "label": say(&lines, "save", &[]), "method": "assistant.allow", "request": { "id": key.id } },    });    Ok(json!({ "id": key.id, "title": title(&lines, &key), "heading": say(&lines, "title", &[]), "preset": at, "presets": presets, "more": more, "note": say(&lines, "sealed_note", &[]) }))}/// An allow the phone sends from More, checked here before the object checks it again.fn allow_from(request: &Value) -> Result<Allow, MethodError> {    let asked = request.get("allow").and_then(Value::as_object).ok_or_else(|| MethodError::new("bad_request", "assistant.allow takes a preset or allow { read, write, outward, acts }"))?;    let tables = |key: &str| -> Result<Tables, MethodError> {        let value = asked.get(key).unwrap_or(&Value::Null);        let read = Tables::of(value);        if let Tables::Some(items) = &read {            if let Some(never) = items.iter().find(|t| NEVER.contains(&t.as_str())) {                return Err(MethodError::new("bad_request", format!("{never} is never given to an assistant")));            }        }        Ok(read)    };    let acts: Vec<String> = asked.get("acts").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default();    if let Some(unknown) = acts.iter().find(|a| !GRANTABLE.contains(&a.as_str())) {        return Err(MethodError::new("bad_request", format!("{unknown} is not something an assistant is given by name")));    }    // Its own notes and sessions stay on whatever is chosen: an assistant that cannot keep them stops working.    let mut read = tables("read")?;    let mut write = tables("write")?;    for (list, own) in [(&mut read, &OWN_READ[..]), (&mut write, &OWN_WRITE[..])] {        if let Tables::Some(items) = list {            items.extend(own.iter().map(|s| s.to_string()));            items.sort();            items.dedup();        }    }    Ok(Allow { read, write, outward: asked.get("outward").and_then(Value::as_bool).unwrap_or(false), sealed: true, acts })}/// `assistant.allow { id, preset | allow }`.fn allow(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let lines = lines(client)?;    let key = find(client, request)?;    let chosen: Option<Allow> = match request.get("preset").and_then(Value::as_str) {        Some(id) => preset(id).ok_or_else(|| MethodError::new("bad_request", format!("{id} is not a preset: {}", PRESETS.join(", "))))?,        None => Some(allow_from(request)?),    };    let sent = chosen.as_ref().map_or(json!("all"), Allow::json);    super::unlock::post(client, "token_allow", json!({ "id": key.id, "allow": sent }))?;    client.nudge_sync();    let before = key.allow.as_ref().map_or(json!("all"), Allow::json);    let at = preset_of(&chosen);    Ok(json!({        "said": say(&lines, "saved", &[("name", &title(&lines, &key))]),        "preset": at,        "undo": { "label": say(&lines, "undo", &[]), "method": "assistant.allow", "request": if before == json!("all") { json!({ "id": key.id, "preset": "everything" }) } else { json!({ "id": key.id, "allow": before }) } },    }))}#[cfg(test)]mod tests {    use super::*;    // RULE (ADMIN KEYS 3): a key with no allow stands at "everything"; each preset reads back as itself; anything else    // is "custom"; More's own choice always keeps the assistant's own notes and sessions.    #[test]    fn presets_read_back_as_themselves() {        assert_eq!(preset_of(&None), "everything");        for id in PRESETS {            assert_eq!(preset_of(&preset(id).expect("a preset")), id);        }        let notes = Allow { read: Tables::list(&["note"]), write: Tables::Some(Vec::new()), outward: false, sealed: true, acts: Vec::new() };        assert_eq!(preset_of(&Some(notes)), "custom");        let mine = allow_from(&json!({ "allow": { "read": ["note"], "write": [], "acts": ["update_definition"] } })).expect("an allow");        assert!(mine.read.has("note") && mine.read.has("memory") && mine.write.has("session") && !mine.write.has("note"));        assert_eq!(mine.acts, ["update_definition"]);        assert!(allow_from(&json!({ "allow": { "read": ["mcp_token"] } })).is_err());        assert!(allow_from(&json!({ "allow": { "acts": ["set_role"] } })).is_err());        // What the object stores reads back the same (key_allow.stored is this JSON).        let stored = preset("read_only").unwrap().unwrap().json();        assert_eq!(preset_of(&Allow::of(&stored)), "read_only");    }    // RULE (ADMIN KEYS 3): the list is the object's `GET /v1/keys`; an OAuth connection is one assistant however many    // tokens it holds (the newest stands for it), a pasted key one of its own, and a key with no allow is "everything".    #[test]    fn a_connection_is_one_assistant() {        let answer = json!({ "keys": [            { "id": "t3", "name": "Invented Claude", "connection_id": "c1", "allow": null },            { "id": "t2", "name": "Lane invented", "machine": "invented-host", "allow": preset("memory").unwrap().unwrap().json() },            { "id": "t1", "name": "Invented Claude", "connection_id": "c1", "allow": null },        ] });        let keys = keys_of(&answer).expect("keys");        assert_eq!(keys.iter().map(|k| k.id.as_str()).collect::<Vec<_>>(), ["t3", "t2"]);        assert_eq!(preset_of(&keys[0].allow), "everything");        assert_eq!(preset_of(&keys[1].allow), "memory");        assert_eq!(keys[1].machine, "invented-host");        assert!(keys_of(&json!({})).is_err());    }}