~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
387 lines · 14.1 KB Raw History
//! atproto spaces (proposal 0016's alpha, as the reference PDS and
//! Monolith serve it), as HUD reaches them: an account's own repo in a
//! space whose authority it is, on its own PDS, through its OAuth session
//! (`Hud::pds_call`, DPoP as every call to a PDS as the account), for the
//! canvases kept there (`canvas::space`). A space is
//! `at://<authority>/space/<type>/<key>`; a record in it is the account's,
//! by collection and key.
//!
//! What a PDS answers is untrusted: a failure becomes a `Failure`, its kind
//! read from the error's name alone, never its words; a listing's records
//! are kept only as `{collection, rkey, value}` with a value that is an
//! object.

use crate::Hud;
use crate::oauth::Account;
use crate::pds::error_name;
use crate::tools::Refusal;
use serde_json::{Value, json};
use std::time::Duration;
use url::Url;

/// The policy of a space only its authority reads and writes.
pub const PERSONAL: &str = "com.atproto.personalspace.policy";
/// How long `describeServer` has.
const WAIT: Duration = Duration::from_secs(10);
/// The most of `describeServer`'s answer read.
const DESCRIBE_MAX: usize = 64 * 1024;
/// A listing's page: records or spaces.
const PAGE: usize = 100;
/// The most pages of a listing read: past it, the listing is refused.
const PAGES_MAX: usize = 50;

/// Why a call in a space failed.
#[derive(Clone, Debug, PartialEq)]
pub enum Failure {
    /// The session ended: its account signs in again.
    SignedOut,
    /// The PDS has no spaces, or none this session may reach: the error
    /// it named.
    Unsupported(String),
    /// The session's grant has no permission for it.
    ScopeMissing,
    /// The PDS refused it: its error's name, and status.
    Refused(String, u16),
    /// The PDS could not be reached, failed, or answered something
    /// unreadable: why.
    Failed(String),
}

impl Failure {
    /// The failure in one line, for a person: what the PDS said, never in
    /// its own words.
    pub fn line(&self) -> String {
        match self {
            Failure::SignedOut => "your sign-in ended".into(),
            Failure::Unsupported(e) => format!("your PDS does not offer spaces to HUD ({e})"),
            Failure::ScopeMissing => "your sign-in does not allow HUD's workspace spaces".into(),
            Failure::Refused(e, status) => format!("your PDS refused: {e} ({status})"),
            Failure::Failed(why) => format!("your PDS could not be reached: {why}"),
        }
    }

    /// Whether trying again later may go otherwise: nothing about the PDS
    /// or the grant said no.
    pub fn transient(&self) -> bool {
        matches!(self, Failure::Failed(_))
            || matches!(self, Failure::Refused(_, status) if *status >= 500)
    }
}

/// A record of an account's repo in a space.
#[derive(Clone, Debug, PartialEq)]
pub struct SpaceRecord {
    pub collection: String,
    pub rkey: String,
    pub value: Value,
}

/// The space of `kind` keyed `skey` whose authority is `did`.
pub fn uri(did: &str, kind: &str, skey: &str) -> String {
    atproto::space::SpaceRef {
        authority: did.to_string(),
        kind: kind.to_string(),
        skey: skey.to_string(),
    }
    .to_string()
}

/// A failed answer's kind, from its status and error: one that means the
/// PDS has no spaces (it passes `com.atproto.space.*` on to a service that
/// does not know them, or has none to pass them to; an `rpc:` scope missing
/// is that too), the grant's permission missing, or a refusal.
fn failure(status: u16, body: &[u8]) -> Failure {
    let name = error_name(body);
    let message = serde_json::from_slice::<Value>(body)
        .ok()
        .and_then(|v| v.get("message")?.as_str().map(str::to_string))
        .unwrap_or_default();
    match name.as_deref() {
        Some("ScopeMissingError") if message.contains("\"rpc:") => {
            Failure::Unsupported("ScopeMissingError".into())
        }
        Some("ScopeMissingError") => Failure::ScopeMissing,
        Some(e @ ("MethodNotImplemented" | "UpstreamFailure" | "XRPCNotSupported")) => {
            Failure::Unsupported(e.to_string())
        }
        Some(e) => Failure::Refused(e.to_string(), status),
        None if matches!(status, 404 | 501) => Failure::Unsupported(format!("HTTP {status}")),
        None => Failure::Refused(format!("HTTP {status}"), status),
    }
}

impl Hud {
    /// Whether the PDS at `pds` says it serves the spaces alpha
    /// (`describeServer`'s `spacesAlpha`), or why it could not be asked.
    pub(crate) async fn spaces_alpha(&self, pds: &str) -> Result<bool, String> {
        let url = Url::parse(&format!("{pds}/xrpc/com.atproto.server.describeServer"))
            .map_err(|_| format!("{pds} is not a usable PDS"))?;
        let got = self.net.fetch_json(&url, WAIT, DESCRIBE_MAX).await?;
        if got.status != 200 {
            return Err(format!("describeServer answered {}", got.status));
        }
        let v: Value = serde_json::from_slice(&got.body)
            .map_err(|_| "describeServer answered something unreadable".to_string())?;
        Ok(v.get("spacesAlpha") == Some(&json!(true)))
    }

    /// Call a space method as the account: its answer, an object.
    async fn space_call(
        &self,
        account: &Account,
        nsid: &str,
        query: &[(&str, &str)],
        input: Option<&Value>,
    ) -> Result<Value, Failure> {
        let query: Vec<(String, String)> = query
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        let got = match self.pds_call(account, nsid, &query, input, None).await {
            Ok(got) => got,
            Err(Refusal::SignIn) => return Err(Failure::SignedOut),
            Err(Refusal::Error(why)) => return Err(Failure::Failed(why)),
        };
        if !(200..300).contains(&got.status) {
            return Err(failure(got.status, &got.body));
        }
        if got.body.is_empty() {
            return Ok(json!({}));
        }
        match serde_json::from_slice(&got.body) {
            Ok(v @ Value::Object(_)) => Ok(v),
            _ => Err(Failure::Failed(format!(
                "{nsid} answered something unreadable"
            ))),
        }
    }

    /// Create the space of `kind` keyed `skey` with the account as its
    /// authority, which it alone reads (the personal policy). One already
    /// there is kept.
    pub(crate) async fn create_space(
        &self,
        account: &Account,
        kind: &str,
        skey: &str,
    ) -> Result<(), Failure> {
        let input = json!({ "spaceType": kind, "skey": skey, "policy": { "$type": PERSONAL } });
        match self
            .space_call(account, "com.atproto.space.createSpace", &[], Some(&input))
            .await
        {
            Err(Failure::Refused(e, _)) if e == "SpaceAlreadyExists" => Ok(()),
            done => done.map(drop),
        }
    }

    /// Delete a space of the account's, its records and all. One not there
    /// is gone already.
    pub(crate) async fn delete_space(&self, account: &Account, space: &str) -> Result<(), Failure> {
        let input = json!({ "space": space });
        match self
            .space_call(account, "com.atproto.space.deleteSpace", &[], Some(&input))
            .await
        {
            Err(Failure::Refused(e, _)) if e == "SpaceNotFound" => Ok(()),
            done => done.map(drop),
        }
    }

    /// Write a record in the account's repo in a space, in place of any of
    /// its collection and key.
    pub(crate) async fn put_space_record(
        &self,
        account: &Account,
        space: &str,
        collection: &str,
        rkey: &str,
        record: &Value,
    ) -> Result<(), Failure> {
        let input = json!({ "space": space, "repo": account.did, "collection": collection,
                            "rkey": rkey, "record": record });
        self.space_call(account, "com.atproto.space.putRecord", &[], Some(&input))
            .await
            .map(drop)
    }

    /// Delete a record of the account's repo in a space; one not there is
    /// no failure.
    pub(crate) async fn delete_space_record(
        &self,
        account: &Account,
        space: &str,
        collection: &str,
        rkey: &str,
    ) -> Result<(), Failure> {
        let input =
            json!({ "space": space, "repo": account.did, "collection": collection, "rkey": rkey });
        self.space_call(account, "com.atproto.space.deleteRecord", &[], Some(&input))
            .await
            .map(drop)
    }

    /// Every record of the account's repo in a space, page by page.
    pub(crate) async fn space_records(
        &self,
        account: &Account,
        space: &str,
    ) -> Result<Vec<SpaceRecord>, Failure> {
        let limit = PAGE.to_string();
        let mut out = Vec::new();
        let mut cursor: Option<String> = None;
        for _ in 0..PAGES_MAX {
            let mut query = vec![
                ("space", space),
                ("repo", account.did.as_str()),
                ("limit", limit.as_str()),
            ];
            if let Some(c) = &cursor {
                query.push(("cursor", c));
            }
            let page = self
                .space_call(account, "com.atproto.space.listRecords", &query, None)
                .await?;
            let records = page["records"]
                .as_array()
                .ok_or_else(|| Failure::Failed("listRecords answered no records".into()))?;
            for r in records {
                let text = |k: &str| r.get(k)?.as_str().map(str::to_string);
                let (Some(collection), Some(rkey), Some(value)) = (
                    text("collection"),
                    text("rkey"),
                    r.get("value").filter(|v| v.is_object()),
                ) else {
                    return Err(Failure::Failed(
                        "listRecords answered a record that is not one".into(),
                    ));
                };
                out.push(SpaceRecord {
                    collection,
                    rkey,
                    value: value.clone(),
                });
            }
            let next = page["cursor"].as_str().map(str::to_string);
            if records.is_empty() || next.is_none() || next == cursor {
                return Ok(out);
            }
            cursor = next;
        }
        Err(Failure::Failed(format!(
            "{space} holds more than {} records",
            PAGE * PAGES_MAX
        )))
    }

    /// The spaces of `kind` whose authority is the account, page by page.
    pub(crate) async fn spaces_of(
        &self,
        account: &Account,
        kind: &str,
    ) -> Result<Vec<String>, Failure> {
        let limit = PAGE.to_string();
        let mut out = Vec::new();
        let mut cursor: Option<String> = None;
        for _ in 0..PAGES_MAX {
            let mut query = vec![
                ("spaceType", kind),
                ("spaceDid", account.did.as_str()),
                ("limit", limit.as_str()),
            ];
            if let Some(c) = &cursor {
                query.push(("cursor", c));
            }
            let page = self
                .space_call(account, "com.atproto.space.listSpaces", &query, None)
                .await?;
            let spaces = page["spaces"]
                .as_array()
                .ok_or_else(|| Failure::Failed("listSpaces answered no spaces".into()))?;
            out.extend(
                spaces
                    .iter()
                    .filter_map(|s| s.get("space")?.as_str().map(str::to_string)),
            );
            let next = page["cursor"].as_str().map(str::to_string);
            if spaces.is_empty() || next.is_none() || next == cursor {
                return Ok(out);
            }
            cursor = next;
        }
        Err(Failure::Failed(format!(
            "more than {} spaces of {kind}",
            PAGE * PAGES_MAX
        )))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn failures_by_their_names() {
        let body = |e: &str, m: &str| json!({ "error": e, "message": m }).to_string();
        assert_eq!(
            failure(
                403,
                body("ScopeMissingError", "Missing required scope \"space:x\"").as_bytes()
            ),
            Failure::ScopeMissing
        );
        // A PDS without spaces passes them on as a service's methods, and
        // refuses them as an rpc: scope.
        assert!(matches!(
            failure(
                403,
                body(
                    "ScopeMissingError",
                    "Missing required scope \"rpc:com.atproto.space.listSpaces?aud=*\""
                )
                .as_bytes()
            ),
            Failure::Unsupported(_)
        ));
        for e in ["MethodNotImplemented", "UpstreamFailure"] {
            assert!(matches!(
                failure(501, body(e, "").as_bytes()),
                Failure::Unsupported(_)
            ));
        }
        assert!(matches!(failure(404, b"<html>"), Failure::Unsupported(_)));
        assert_eq!(
            failure(400, body("SpaceNotFound", "").as_bytes()),
            Failure::Refused("SpaceNotFound".into(), 400)
        );
        assert!(failure(502, b"").transient());
        assert!(!failure(400, body("InvalidRequest", "").as_bytes()).transient());
        assert!(Failure::Failed("timeout".into()).transient());
        // A person reads what happened, never the PDS's own words.
        assert_eq!(
            failure(400, body("SpaceNotFound", "secret words").as_bytes()).line(),
            "your PDS refused: SpaceNotFound (400)"
        );
        for (f, line) in [
            (Failure::SignedOut, "your sign-in ended"),
            (
                Failure::Unsupported("XRPCNotSupported".into()),
                "your PDS does not offer spaces to HUD (XRPCNotSupported)",
            ),
            (
                Failure::ScopeMissing,
                "your sign-in does not allow HUD's workspace spaces",
            ),
            (
                Failure::Failed("timeout".into()),
                "your PDS could not be reached: timeout",
            ),
        ] {
            assert_eq!(f.line(), line);
        }
        assert_eq!(
            uri("did:plc:a", "place.hud.workspace", "00ab"),
            "at://did:plc:a/space/place.hud.workspace/00ab"
        );
    }
}