~ 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
329 lines · 12.9 KB Raw History
//! A mode's `head` read against its scope: what a page drawing the tree
//! says of itself in its HTML head, to search engines and link previews
//! (`_meta.ui.head`). Each field is a template, as an action's record is
//! (`record`); one whose binding resolves to nothing usable is left out,
//! never an error. Its text is third parties' words, so each is put on one
//! line and cut short; its image is an https URL alone, its canonical a
//! path on the app's own site, its structured data (`jsonLd`) bounded in
//! size. The page escapes all of it as it writes its HTML.

use super::*;
use crate::summary::one_line;
use std::sync::LazyLock;

/// The most characters a head's title, description and image's alt text take.
const TITLE: usize = 120;
const DESCRIPTION: usize = 300;
const IMAGE_ALT: usize = 420;
/// The most characters a string in its structured data takes.
const DATA_TEXT: usize = 1000;
/// The longest canonical path, query included.
const CANONICAL: usize = 512;
/// The most elements a `$each` in structured data reads.
const EACH: usize = 50;
/// The most bytes its structured data takes, as JSON: past it, none.
const DATA_BYTES: usize = 32 * 1024;

/// A mode's head (`doc`, null where it has none) over its scope; None
/// where nothing in it resolves.
pub fn resolve(doc: &Value, scope: &Value, ctx: &Ctx) -> Option<Value> {
    let read = |key: &str| record(&doc[key], scope, ctx.root).ok();
    let mut out = Map::new();
    let texts = [
        ("title", TITLE),
        ("description", DESCRIPTION),
        ("imageAlt", IMAGE_ALT),
    ];
    for (key, max) in texts {
        if let Some(t) = read(key).as_ref().and_then(text).map(|t| one_line(&t, max)) {
            out.insert(key.into(), t.into());
        }
    }
    if let Some(src) = read("image").as_ref().and_then(|i| image(i, ctx)) {
        out.insert("image".into(), src.into());
    }
    if let Some(kind) = doc["type"].as_str() {
        out.insert("type".into(), kind.into());
    }
    if let Some(path) = read("canonical")
        .as_ref()
        .and_then(Value::as_str)
        .and_then(canonical)
    {
        out.insert("canonical".into(), path.into());
    }
    if read("noindex").as_ref().is_some_and(says_yes) {
        out.insert("noindex".into(), true.into());
    }
    if let Some(data) = data(&doc["jsonLd"], scope, ctx.root).filter(bounded) {
        out.insert("jsonLd".into(), data);
    }
    out.retain(|_, v| v.as_str() != Some(""));
    (!out.is_empty()).then_some(Value::Object(out))
}

/// Text: a string, or a number written out.
fn text(v: &Value) -> Option<String> {
    (v.is_string() || v.is_number()).then(|| write(v))
}

/// An image's absolute https URL: a blob's `url`, or a URL on the view's
/// origins, as an `Image` loads one.
fn image(v: &Value, ctx: &Ctx) -> Option<String> {
    url_of(v, ctx)
        .filter(|u| url::Url::parse(u).is_ok_and(|u| u.scheme() == "https" && u.host().is_some()))
}

/// Where a relative path is read from, to see it stays on the site.
static SITE: LazyLock<url::Url> =
    LazyLock::new(|| url::Url::parse("https://site.invalid/").expect("a URL"));

/// A path on the app's own site (`/profile/alice/gallery/3k…`), with its
/// query, as a URL writes it (percent-encoded), less any fragment; none
/// that would leave the site (`//host`, `/\host`).
fn canonical(s: &str) -> Option<String> {
    let u = s
        .starts_with('/')
        .then(|| SITE.join(s).ok())
        .flatten()
        .filter(|u| u.origin() == SITE.origin())?;
    let path = match u.query() {
        Some(q) => format!("{}?{q}", u.path()),
        None => u.path().to_string(),
    };
    (path.len() <= CANONICAL).then_some(path)
}

/// Whether noindex holds: true, or a list with something in it (an
/// account's labels).
fn says_yes(v: &Value) -> bool {
    *v == Value::Bool(true) || v.as_array().is_some_and(|a| !a.is_empty())
}

/// Structured data read: objects and arrays walked, a template read
/// (`record`) where one stands, `{"$each": [array, template]}` the
/// template read against each element; what resolves to nothing left out,
/// and so an object whose templates all read nothing (a place with no
/// name has no use for its `@type`), and an array or object with nothing
/// left. Strings put on one line.
fn data(v: &Value, scope: &Value, root: &Value) -> Option<Value> {
    match v {
        Value::Object(o) if o.contains_key("$each") => {
            let Ok(Value::Array(items)) = record(&o["$each"][0], scope, root) else {
                return None;
            };
            let read: Vec<Value> = items
                .iter()
                .take(EACH)
                .filter_map(|item| data(&o["$each"][1], item, root))
                .collect();
            (!read.is_empty()).then_some(Value::Array(read))
        }
        Value::Object(o) if o.keys().any(|k| k.starts_with('$')) => {
            record(v, scope, root).ok().map(|found| flat(&found))
        }
        Value::Object(o) => {
            let mut read = Map::new();
            let mut bound = false;
            let mut found = false;
            for (k, c) in o {
                let templated = holds_template(c);
                bound |= templated;
                if let Some(x) = data(c, scope, root) {
                    found |= templated;
                    read.insert(k.clone(), x);
                }
            }
            (found || !bound).then_some(Value::Object(read))
        }
        Value::Array(a) => {
            let read: Vec<Value> = a.iter().filter_map(|c| data(c, scope, root)).collect();
            (!read.is_empty()).then_some(Value::Array(read))
        }
        Value::Null => None,
        _ => Some(flat(v)),
    }
}

/// Whether a value of structured data reads anything: a key starting with
/// `$` anywhere in it.
fn holds_template(v: &Value) -> bool {
    match v {
        Value::Object(o) => o
            .iter()
            .any(|(k, c)| k.starts_with('$') || holds_template(c)),
        Value::Array(a) => a.iter().any(holds_template),
        _ => false,
    }
}

/// A value with each string in it on one line, cut short.
fn flat(v: &Value) -> Value {
    match v {
        Value::String(s) => one_line(s, DATA_TEXT).into(),
        Value::Array(a) => a.iter().map(flat).collect(),
        Value::Object(o) => o.iter().map(|(k, c)| (k.clone(), flat(c))).collect(),
        _ => v.clone(),
    }
}

/// Whether structured data is small enough to send.
fn bounded(v: &Value) -> bool {
    v.to_string().len() <= DATA_BYTES
}

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

    fn ctx<'a>(root: &'a Value, origins: &'a [String]) -> Ctx<'a> {
        Ctx {
            origins,
            thumbnails: vec![],
            trusted: true,
            root,
            report: None,
            inline: None,
            lexicon: None,
            handles: None,
            paged: Vec::new(),
            more: More::default(),
            me: None,
            people: None,
        }
    }

    fn head(doc: Value, scope: Value) -> Option<Value> {
        let origins = vec!["https://cdn.example.test".to_string()];
        resolve(&doc, &scope, &ctx(&scope, &origins))
    }

    /// Each field read from its template; one that resolves to nothing
    /// usable left out, and a head with nothing left none at all.
    #[test]
    fn a_head_keeps_what_resolves() {
        let scope = json!({ "g": { "title": "Coast", "by": "alice.test", "n": 12, "uri": "at://did:plc:a/x.y.z/3k",
                                   "photo": "https://cdn.example.test/p.jpg", "blob": { "url": "https://pds.test/b" },
                                   "labels": [{ "val": "nudity" }] } });
        let doc = json!({
            "title": { "$join": [{ "$": "g.title" }, " by ", { "$": "g.by" }, " on Grain"] },
            "description": { "$": "g.n" },
            "image": { "$": "g.photo" },
            "imageAlt": { "$": "g.missing" },
            "type": "article",
            "canonical": { "$join": ["/profile/", { "$": "g.by" }, "/gallery/", { "$rkey": "g.uri" }] },
            "noindex": { "$": "g.labels" },
        });
        assert_eq!(
            head(doc, scope.clone()),
            Some(
                json!({ "title": "Coast by alice.test on Grain", "description": "12",
                         "image": "https://cdn.example.test/p.jpg", "type": "article",
                         "canonical": "/profile/alice.test/gallery/3k", "noindex": true })
            )
        );
        // A blob's URL wherever it is; a string only on the view's origins.
        assert_eq!(
            head(json!({ "image": { "$": "g.blob" } }), scope.clone()),
            Some(json!({ "image": "https://pds.test/b" }))
        );
        assert_eq!(
            head(
                json!({ "image": "https://elsewhere.test/p.jpg" }),
                scope.clone()
            ),
            None
        );
        assert_eq!(
            head(
                json!({ "image": { "url": "http://pds.test/b" } }),
                scope.clone()
            ),
            None
        );
        // Text that is no text, an empty title, no labels: nothing.
        let none = json!({ "title": { "$": "g" }, "description": "", "noindex": { "$": "g.none" },
                           "canonical": { "$": "g.n" } });
        assert_eq!(head(none, scope.clone()), None);
        assert_eq!(head(json!({ "noindex": [] }), scope.clone()), None);
        assert_eq!(
            head(json!({ "noindex": true }), scope.clone()),
            Some(json!({ "noindex": true }))
        );
        assert_eq!(head(Value::Null, scope), None);
    }

    /// Third parties' text on one line, cut short; a canonical path stays
    /// on the site, encoded as a URL writes it.
    #[test]
    fn a_head_is_held_in_bounds() {
        let long = "word ".repeat(100);
        let scope = json!({ "t": format!("a\n\tb \u{7}{long}") });
        let got = head(
            json!({ "title": { "$": "t" }, "description": { "$": "t" }, "imageAlt": { "$": "t" } }),
            scope,
        )
        .unwrap();
        let title = got["title"].as_str().unwrap();
        assert!(title.starts_with("a b word"), "{title}");
        assert_eq!(title.chars().count(), TITLE + 1);
        assert!(title.ends_with('…'));
        assert_eq!(
            got["description"].as_str().unwrap().chars().count(),
            DESCRIPTION + 1
        );
        assert_eq!(
            got["imageAlt"].as_str().unwrap().chars().count(),
            IMAGE_ALT + 1
        );
        assert_eq!(
            canonical("/a b/c?q=x y#f").as_deref(),
            Some("/a%20b/c?q=x%20y")
        );
        assert_eq!(canonical("/x").as_deref(), Some("/x"));
        for off in [
            "//evil.test/x",
            "/\\evil.test/x",
            "x/y",
            "https://evil.test/",
            "",
        ] {
            assert_eq!(canonical(off), None, "{off}");
        }
        assert_eq!(canonical(&format!("/{}", "a".repeat(CANONICAL))), None);
    }

    /// Structured data: what resolves kept, what does not left out, an
    /// array's elements each read, a string flattened; too much of it, none.
    #[test]
    fn structured_data_keeps_what_resolves() {
        let scope = json!({ "g": { "title": "Coast\nline", "by": { "name": "Alice" }, "tags": ["sea\nside", 2],
                                   "items": [{ "src": "https://a/1", "alt": "One" }, { "src": "https://a/2" }, { "none": 1 }] } });
        let doc = json!({ "jsonLd": {
            "@context": "https://schema.org", "@type": "SocialMediaPosting",
            "headline": { "$": "g.title" }, "text": { "$": "g.missing" },
            "author": { "@type": "Person", "name": { "$": "g.by.name" }, "url": { "$": "g.by.url" } },
            "about": { "$": "g.by" },
            "keywords": ["photo", { "$": "g.missing" }], "tags": { "$": "g.tags" },
            "image": { "$each": [{ "$": "g.items" }, { "contentUrl": { "$": "src" }, "caption": { "$": "alt" } }] },
            "nothing": { "$each": [{ "$": "g.missing" }, { "a": 1 }] },
            "empty": { "$each": [{ "$": "g.items" }, { "a": { "$": "missing" } }] },
            "gone": { "x": { "$": "g.missing" } },
            "place": { "@type": "Place", "name": { "$": "g.missing" } },
            "stats": [{ "@type": "InteractionCounter", "n": { "$": "g.missing" } }],
            "literal": { "a": 1, "b": null },
        } });
        assert_eq!(
            head(doc, scope.clone()).unwrap()["jsonLd"],
            json!({ "@context": "https://schema.org", "@type": "SocialMediaPosting", "headline": "Coast line",
                    "author": { "@type": "Person", "name": "Alice" }, "about": { "name": "Alice" },
                    "keywords": ["photo"], "tags": ["sea side", 2], "literal": { "a": 1 },
                    "image": [{ "contentUrl": "https://a/1", "caption": "One" }, { "contentUrl": "https://a/2" }] })
        );
        let big = json!({ "t": "x".repeat(DATA_TEXT) });
        let many: Vec<Value> = (0..40)
            .map(|i| json!({ "k": { "$": "t" }, "i": i }))
            .collect();
        assert_eq!(head(json!({ "jsonLd": { "many": many } }), big), None);
    }
}