~ 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
600 lines · 22.6 KB Raw History
//! Link cards, for a post's link (`link_card`, hidden from the model): the
//! page at a URL read, through the outbound client as anything fetched is,
//! for its title, description and image (Open Graph's, Twitter's, or its
//! `<title>`), as `app.bsky.embed.external#external` holds them; the image,
//! where there is one and it is small enough, uploaded to the person's PDS
//! as the card's thumb. What the page says is untrusted: plain text, its
//! entities decoded, cut short.

use crate::Hud;
use crate::oauth::Account;
use crate::pds::image_type;
use crate::tools::{Args, Output, Refusal};
use bytes::Bytes;
use serde_json::{Value, json};
use std::time::Duration;
use url::Url;

/// How long the page, and then its image, have.
const WAIT: Duration = Duration::from_secs(5);
/// The most of a page read.
const PAGE_MAX: usize = 4 * 1024 * 1024;
/// The most of an image read.
const IMAGE_MAX: usize = 5 * 1024 * 1024;
/// The most bytes of a thumb: Bluesky's limit for an external embed's.
const THUMB_MAX: usize = 1_000_000;
/// The longest URL taken.
const URL_MAX: usize = 3000;
/// The most characters of a title and of a description kept.
const TITLE_MAX: usize = 300;
const DESCRIPTION_MAX: usize = 1000;

/// The tool's definition: hidden from the model, a post form's.
pub fn definition() -> Value {
    json!({
        "name": "link_card",
        "title": "Make a link card",
        "description": "Read a web page's title, description and image for a post's link card, the image uploaded to the signed-in person's PDS as its thumb. Called by the view; needs sign-in.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "url": { "type": "string", "format": "uri", "maxLength": URL_MAX,
                         "description": "The page's http(s) URL." },
            },
            "required": ["url"],
            "additionalProperties": false,
        },
        "annotations": { "title": "Make a link card", "readOnlyHint": false,
                         "destructiveHint": false, "idempotentHint": true, "openWorldHint": true },
        "_meta": { "ui": { "visibility": ["app"] } },
    })
}

/// What a page says of itself: empty where it says nothing.
#[derive(Debug, Default, PartialEq)]
pub(crate) struct Page {
    pub title: String,
    pub description: String,
    /// Its image's absolute http(s) URL.
    pub image: Option<Url>,
}

/// `html`'s head read as a card: the first of `og:title`, `twitter:title`
/// and `<title>`; of `og:description`, `twitter:description` and
/// `description`; of `og:image` (`:secure_url`, `:url`) and
/// `twitter:image`, made absolute against `base`.
pub(crate) fn read_page(html: &str, base: &Url) -> Page {
    let (metas, title) = head(html);
    let meta = |keys: &[&str]| {
        keys.iter()
            .find_map(|k| metas.iter().find(|(m, c)| m == k && !c.trim().is_empty()))
            .map(|(_, c)| c.as_str())
    };
    let title = meta(&["og:title", "twitter:title"]).or(title.as_deref());
    let description = meta(&["og:description", "twitter:description", "description"]);
    let image = meta(&[
        "og:image",
        "og:image:secure_url",
        "og:image:url",
        "twitter:image",
        "twitter:image:src",
    ])
    .and_then(|i| base.join(decode(i).trim()).ok())
    .filter(|u| matches!(u.scheme(), "http" | "https"));
    Page {
        title: plain(title.unwrap_or_default(), TITLE_MAX),
        description: plain(description.unwrap_or_default(), DESCRIPTION_MAX),
        image,
    }
}

/// Text as a card shows it: its entities decoded, its runs of whitespace
/// one space, at most `max` characters.
fn plain(s: &str, max: usize) -> String {
    let decoded = decode(s);
    let mut out = String::with_capacity(decoded.len().min(max * 4));
    for (n, word) in decoded.split_whitespace().enumerate() {
        if n > 0 {
            out.push(' ');
        }
        out.push_str(word);
    }
    match out.char_indices().nth(max) {
        Some((cut, _)) => {
            out.truncate(cut);
            out.truncate(out.trim_end().len());
            out.push('…');
            out
        }
        None => out,
    }
}

/// Whether `rest`, from a `<`, opens the tag `name` (lowercase, as `rest`).
fn opens(rest: &str, name: &str) -> bool {
    rest[1..].starts_with(name)
        && rest[1 + name.len()..]
            .chars()
            .next()
            .is_none_or(|c| c.is_ascii_whitespace() || c == '>' || c == '/')
}

/// Where a tag that starts `rest` ends, past its `>`, quoted values
/// skipped; the end of `rest` if it does not.
fn tag_end(rest: &str) -> usize {
    let mut quote = None;
    for (i, b) in rest.bytes().enumerate() {
        match (quote, b) {
            (None, b'"' | b'\'') => quote = Some(b),
            (Some(q), _) if b == q => quote = None,
            (None, b'>') => return i + 1,
            _ => {}
        }
    }
    rest.len()
}

/// A head's `<meta>` tags, each its `property` or `name` (lowercase) and
/// its `content`, in order; and its `<title>`. Read until `<body` or
/// `</head>`, past comments, scripts and styles.
fn head(html: &str) -> (Vec<(String, String)>, Option<String>) {
    // ASCII lowercasing keeps every byte where it was.
    let lower = html.to_ascii_lowercase();
    let (mut metas, mut title) = (Vec::new(), None);
    let mut i = 0;
    while let Some(at) = lower[i..].find('<').map(|o| i + o) {
        let rest = &lower[at..];
        let skip_to = |close: &str| {
            rest.find(close)
                .map_or(lower.len(), |e| at + e + close.len())
        };
        if rest.starts_with("<!--") {
            i = skip_to("-->");
        } else if opens(rest, "script") {
            i = skip_to("</script");
        } else if opens(rest, "style") {
            i = skip_to("</style");
        } else if opens(rest, "title") {
            let open = at + tag_end(rest);
            let close = lower[open..]
                .find("</title")
                .map_or(lower.len(), |e| open + e);
            if title.is_none() {
                title = Some(html[open..close].to_string());
            }
            i = close;
        } else if opens(rest, "meta") {
            let end = at + tag_end(rest);
            let attrs = attributes(&html[at + 5..end]);
            let get = |k: &str| attrs.iter().find(|(n, _)| n == k).map(|(_, v)| v);
            if let (Some(key), Some(content)) = (get("property").or(get("name")), get("content")) {
                metas.push((key.to_ascii_lowercase(), content.to_string()));
            }
            i = end;
        } else if opens(rest, "body") || rest.starts_with("</head") {
            break;
        } else {
            i = at + 1;
        }
    }
    (metas, title)
}

/// A tag's attributes, from past its name to its end: each name
/// (lowercase) and its value as written, quoted or not.
fn attributes(tag: &str) -> Vec<(String, &str)> {
    let mut out = Vec::new();
    let mut rest = tag;
    loop {
        rest = rest.trim_start_matches(|c: char| c.is_ascii_whitespace() || c == '/');
        if rest.is_empty() || rest.starts_with('>') {
            return out;
        }
        let name_end = rest
            .find(|c: char| c.is_ascii_whitespace() || matches!(c, '=' | '>' | '/'))
            .unwrap_or(rest.len());
        let name = rest[..name_end].to_ascii_lowercase();
        rest = rest[name_end..].trim_start();
        let Some(after) = rest.strip_prefix('=') else {
            out.push((name, ""));
            continue;
        };
        let after = after.trim_start();
        let (value, next) = match after.chars().next() {
            Some(q @ ('"' | '\'')) => {
                let body = &after[1..];
                let end = body.find(q).unwrap_or(body.len());
                (&body[..end], &body[(end + 1).min(body.len())..])
            }
            _ => {
                let end = after
                    .find(|c: char| c.is_ascii_whitespace() || c == '>')
                    .unwrap_or(after.len());
                (&after[..end], &after[end..])
            }
        };
        out.push((name, value));
        rest = next;
    }
}

/// `s` with its character references decoded: numeric ones, and the named
/// ones a title or description holds; any other left as it is.
fn decode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut rest = s;
    while let Some(p) = rest.find('&') {
        out.push_str(&rest[..p]);
        rest = &rest[p..];
        let found = rest[1..]
            .find(';')
            .filter(|&e| e <= 12)
            .and_then(|e| Some((reference(&rest[1..=e])?, e + 2)));
        match found {
            Some((c, len)) => {
                out.push(c);
                rest = &rest[len..];
            }
            None => {
                out.push('&');
                rest = &rest[1..];
            }
        }
    }
    out.push_str(rest);
    out
}

/// The character a reference's name (between `&` and `;`) stands for.
fn reference(name: &str) -> Option<char> {
    if let Some(n) = name.strip_prefix('#') {
        let code = match n.strip_prefix(['x', 'X']) {
            Some(hex) => u32::from_str_radix(hex, 16).ok()?,
            None => n.parse().ok()?,
        };
        return char::from_u32(code).filter(|c| *c != '\0');
    }
    Some(match name {
        "amp" => '&',
        "lt" => '<',
        "gt" => '>',
        "quot" => '"',
        "apos" => '\'',
        "nbsp" => '\u{a0}',
        "ndash" => '–',
        "mdash" => '—',
        "hellip" => '…',
        "lsquo" => '‘',
        "rsquo" => '’',
        "ldquo" => '“',
        "rdquo" => '”',
        "laquo" => '«',
        "raquo" => '»',
        "middot" => '·',
        "bull" => '•',
        "copy" => '©',
        "reg" => '®',
        "trade" => '™',
        _ => return None,
    })
}

/// A card's URL, checked: http(s), with a host.
fn checked_url(url: &str) -> Result<Url, String> {
    let url = url.trim();
    if url.len() > URL_MAX {
        return Err(format!("url is at most {URL_MAX} characters"));
    }
    Url::parse(url)
        .ok()
        .filter(|u| matches!(u.scheme(), "http" | "https") && u.host().is_some())
        .ok_or_else(|| format!("Not an http(s) URL: {url}"))
}

impl Hud {
    pub(crate) async fn link_card_tool(
        &self,
        arguments: Option<&Value>,
        account: Option<&Account>,
    ) -> Result<Output, Refusal> {
        let Some(account) = account else {
            return Err(Refusal::SignIn);
        };
        let args = Args::of(arguments, &["url"])?;
        let url = checked_url(args.required("url")?)?;
        let host = url.host_str().unwrap_or_default().to_string();
        let req = self
            .net
            .get(&url)?
            .header(reqwest::header::ACCEPT, "text/html,application/xhtml+xml");
        let got = self
            .net
            .send(req, WAIT, PAGE_MAX)
            .await
            .map_err(|f| format!("Could not read {host}: {f}"))?;
        if got.status != 200 {
            return Err(format!("{host} answered {}", got.status).into());
        }
        let html = got
            .header("content-type")
            .is_none_or(|t| t.contains("html"));
        let page = match html {
            true => read_page(&String::from_utf8_lossy(&got.body), &url),
            false => Page::default(),
        };
        let mut card = json!({ "uri": url.as_str(), "title": page.title,
                               "description": page.description });
        let mut structured = json!({});
        if let Some(image) = &page.image
            && let Some(thumb) = self.thumb(account, image).await?
        {
            // A blob ref as `upload_blob` makes one: its CID always there.
            let cid = thumb["ref"]["$link"].as_str().unwrap_or_default();
            structured["image"] = json!(crate::blobs::url(
                &self.config.public_origin,
                &account.did,
                cid
            ));
            card["thumb"] = thumb;
        }
        let text = match page.title.as_str() {
            "" => format!("A card for {url}."),
            title => format!("A card for {url}: {title}."),
        };
        structured["card"] = card;
        Ok(Output {
            text,
            structured,
            meta: json!({}),
        })
    }

    /// A card's image uploaded as the account's blob, its ref; none where
    /// it cannot be read, is no image, or is over `THUMB_MAX`: a card goes
    /// without its thumb, unless the account must sign in again.
    async fn thumb(&self, account: &Account, image: &Url) -> Result<Option<Value>, Refusal> {
        let got = match self.net.fetch(image, WAIT, IMAGE_MAX).await {
            Ok(got) if got.status == 200 => got,
            Ok(got) => {
                tracing::info!(status = got.status, "link card's image refused");
                return Ok(None);
            }
            Err(f) => {
                tracing::info!(why = f.why, "link card's image unread");
                return Ok(None);
            }
        };
        let Some(mime) = image_type(&got.body).filter(|_| got.body.len() <= THUMB_MAX) else {
            return Ok(None);
        };
        match self.upload_blob(account, mime, Bytes::from(got.body)).await {
            Ok(blob) => Ok(Some(blob)),
            Err(Refusal::SignIn) => Err(Refusal::SignIn),
            Err(Refusal::Error(why)) => {
                tracing::info!(why, "link card's thumb not uploaded");
                Ok(None)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::writes::tests::{Asked, CID, DID, closed_port, json_answer, refused, served};

    fn base() -> Url {
        Url::parse("https://example.com/posts/1").unwrap()
    }

    #[test]
    fn open_graph_read() {
        let html = r#"<!doctype html><html><head>
            <title>Fallback</title>
            <!-- <meta property="og:title" content="Commented out"> -->
            <script>var s = '<meta property="og:title" content="In a script">';</script>
            <META PROPERTY="og:title" CONTENT="Tom &amp; Jerry&#39;s &#x1F600; &quot;day&quot;">
            <meta name='description' content='The plain one'>
            <meta property="og:description" content="  Two
                lines  &hellip; ">
            <meta property="og:image" content="/img/card.png?a=1&amp;b=2">
            </head><body><meta property="og:image" content="https://late.example/x.png"></body>"#;
        assert_eq!(
            read_page(html, &base()),
            Page {
                title: "Tom & Jerry's 😀 \"day\"".into(),
                description: "Two lines …".into(),
                image: Some(Url::parse("https://example.com/img/card.png?a=1&b=2").unwrap()),
            }
        );
    }

    #[test]
    fn fallbacks_read() {
        let html = "<html><head><title>\n  A &lt;b&gt; title &unknown; &#0; </title>\
            <meta name=description content=Unquoted>\
            <meta name=\"twitter:image\" content=\"//cdn.example/i.jpg\">\
            <meta property=\"og:image\" content=\"javascript:alert(1)\"></head>";
        let page = read_page(html, &base());
        assert_eq!(page.title, "A <b> title &unknown; &#0;");
        assert_eq!(page.description, "Unquoted");
        // og:image is first but not http(s): none, not the next one.
        assert_eq!(page.image, None);
        let page = read_page("<p>No head at all", &base());
        assert_eq!(page, Page::default());
        let page = read_page(
            r#"<meta name="twitter:image" content="//cdn.example/i.jpg">"#,
            &base(),
        );
        assert_eq!(page.image.unwrap().as_str(), "https://cdn.example/i.jpg");
    }

    /// Styles skipped; a meta naming no key, or with no content, passed
    /// over; the first of two titles; a tag left open read to the end.
    #[test]
    fn odd_heads_read() {
        let html = "<head><style>meta { color: red }</style>\
            <meta itemprop content=\"no key\"><meta property=\"og:title\">\
            <title>First</title><title>Second</title>\
            <meta property=\"og:description\" content=\"left open";
        assert_eq!(
            read_page(html, &base()),
            Page {
                title: "First".into(),
                description: "left open".into(),
                image: None,
            }
        );
    }

    #[test]
    fn named_references_decoded() {
        assert_eq!(
            decode(
                "&amp;&lt;&gt;&quot;&apos;&nbsp;&ndash;&mdash;&hellip;&lsquo;&rsquo;\
                 &ldquo;&rdquo;&laquo;&raquo;&middot;&bull;&copy;&reg;&trade;"
            ),
            "&<>\"'\u{a0}–—…‘’“”«»·•©®™"
        );
    }

    #[test]
    fn cut_short() {
        assert_eq!(plain(&"word ".repeat(100), 9), "word word…");
        assert_eq!(plain("short", 9), "short");
    }

    #[test]
    fn only_http_urls() {
        assert!(checked_url("https://example.com/a").is_ok());
        assert!(checked_url(" http://example.com ").is_ok());
        assert!(checked_url("ftp://example.com").is_err());
        assert!(checked_url("javascript:alert(1)").is_err());
        assert!(checked_url("not a url").is_err());
        let long = format!("https://example.com/{}", "a".repeat(URL_MAX));
        assert_eq!(
            checked_url(&long).unwrap_err(),
            "url is at most 3000 characters"
        );
    }

    const PNG: &[u8] = b"\x89PNG\r\n\x1a\n";

    /// A page for each case, its image beside it; the PDS refuses an image
    /// marked `refuse`, and the token sent with one marked `expire`.
    fn site(away: u16) -> impl Fn(&Asked) -> crate::writes::tests::Answer + Send + Sync {
        move |a| {
            let html = |image: &str| {
                let page = format!(
                    "<html><head><meta property=\"og:title\" content=\"A page\">\
                     <meta name=\"description\" content=\"About it\">\
                     <meta property=\"og:image\" content=\"{image}\"></head></html>"
                );
                (200, "text/html; charset=utf-8", page.into_bytes())
            };
            let png = |tail: &[u8]| (200, "image/png", [PNG, tail].concat());
            match a.path.as_str() {
                "/page" => html("/img.png"),
                "/img.png" => png(b"ok"),
                "/untyped" => (200, "", b"<title>Untyped</title>".to_vec()),
                "/data" => json_answer(200, json!({ "title": "not a page" })),
                "/missing" => html("/gone.png"),
                "/away" => html(&format!("http://127.0.0.1:{away}/x.png")),
                "/text" => html("/text.png"),
                "/text.png" => (200, "image/png", b"not an image".to_vec()),
                "/big" => html("/big.png"),
                "/big.png" => png(&vec![0; THUMB_MAX]),
                "/refused" => html("/refuse.png"),
                "/refuse.png" => png(b"refuse"),
                "/expired" => html("/expire.png"),
                "/expire.png" => png(b"expire"),
                "/xrpc/com.atproto.repo.uploadBlob" if a.body.ends_with(b"refuse") => {
                    json_answer(400, json!({ "error": "InvalidBlob" }))
                }
                "/xrpc/com.atproto.repo.uploadBlob" if a.body.ends_with(b"expire") => {
                    json_answer(401, json!({ "error": "invalid_token" }))
                }
                "/xrpc/com.atproto.repo.uploadBlob" => json_answer(
                    200,
                    json!({ "blob": { "$type": "blob", "ref": { "$link": CID },
                                      "mimeType": "image/png", "size": a.body.len() } }),
                ),
                _ => (404, "text/html", b"<h1>Not found</h1>".to_vec()),
            }
        }
    }

    #[tokio::test]
    async fn cards_made_from_pages() {
        let away = closed_port().await;
        let s = served(site(away)).await;
        let card = async |path: &str| {
            let url = format!("{}{path}", s.url);
            s.hud
                .link_card_tool(Some(&json!({ "url": url })), Some(&s.account))
                .await
        };
        // Its title, description and image, the image the account's blob.
        let url = format!("{}/page", s.url);
        let out = card("/page").await.unwrap();
        assert_eq!(out.text, format!("A card for {url}: A page."));
        let thumb = json!({ "$type": "blob", "ref": { "$link": CID }, "mimeType": "image/png",
                            "size": PNG.len() + 2 });
        assert_eq!(
            out.structured,
            json!({ "image": format!("https://hud.test/blob/{DID}/{CID}"),
                    "card": { "uri": url, "title": "A page", "description": "About it", "thumb": thumb } })
        );
        // A page that says not what it is is read as one; anything else
        // makes a card of its URL alone.
        assert_eq!(
            card("/untyped").await.unwrap().structured["card"]["title"],
            "Untyped"
        );
        let url = format!("{}/data", s.url);
        let out = card("/data").await.unwrap();
        assert_eq!(out.text, format!("A card for {url}."));
        assert_eq!(
            out.structured,
            json!({ "card": { "uri": url, "title": "", "description": "" } })
        );
        // An image that cannot be had, is no image, is too big for a thumb
        // or is refused by the PDS: the card made without it.
        for path in ["/missing", "/away", "/text", "/big", "/refused"] {
            let out = card(path).await.unwrap();
            assert_eq!(out.structured["card"]["title"], "A page", "{path}");
            assert_eq!(out.structured["card"].get("thumb"), None, "{path}");
            assert_eq!(out.structured.get("image"), None, "{path}");
        }
        let uploaded = s
            .asked
            .lock()
            .unwrap()
            .iter()
            .filter(|a| a.path == "/xrpc/com.atproto.repo.uploadBlob")
            .count();
        assert_eq!(uploaded, 2, "only the page's image and the refused one");
        // A page not there, or no server at all.
        assert_eq!(
            card("/nowhere").await.unwrap_err(),
            Refusal::Error("127.0.0.1 answered 404".into())
        );
        let url = format!("http://127.0.0.1:{away}/");
        let e = refused(
            s.hud
                .link_card_tool(Some(&json!({ "url": url })), Some(&s.account))
                .await,
        );
        assert!(e.starts_with("Could not read 127.0.0.1: "), "{e}");
        assert_eq!(
            s.hud
                .link_card_tool(Some(&json!({ "url": "ftp://a.example" })), Some(&s.account))
                .await
                .unwrap_err(),
            Refusal::Error("Not an http(s) URL: ftp://a.example".into())
        );
        // A sign-in the PDS no longer takes, which cannot be renewed: sign
        // in again, rather than a card without its thumb.
        assert_eq!(card("/expired").await.unwrap_err(), Refusal::SignIn);
    }
}