~ 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
236 lines · 8.9 KB Raw History
//! Apps' icons, as Bluesky shows a link's: each app's site's favicon, by
//! its domain, as a favicon service (`HUD_FAVICONS`, by default Bluesky's
//! link-card service, `https://cardyb.bsky.app/v1/favicon?url=`) answers it
//! for `https://<domain>`, the URL following the service's address encoded.
//! An app is the domain of an NSID (`apps::domain`): `app.bsky.feed.post`
//! is `bsky.app`'s.
//!
//! Only a 200 `image/png` of at most 100,000 bytes is an icon. Each is kept
//! on disk, `<HUD_CACHE_DIR>/icons/<domain>.png`, a week; what is none (an
//! error, a timeout, too large, not a PNG) is kept as none,
//! `<domain>.miss`, a day, so a site without one is not asked again on
//! every page. A domain is a hostname, never an address, nor a name that
//! only a private network resolves, unless `HUD_ALLOW_PRIVATE`.

use crate::Hud;
use std::net::IpAddr;
use std::path::PathBuf;
use std::time::{Duration, SystemTime};

/// The favicon service, by default: the domain's URL follows, encoded.
pub const FAVICONS: &str = "https://cardyb.bsky.app/v1/favicon?url=";
/// The most bytes an icon takes.
pub const ICON_AT_MOST: usize = 100_000;
/// How long the service has to answer.
const WAIT: Duration = Duration::from_secs(5);
/// How long an icon is kept.
pub const KEEP: Duration = Duration::from_secs(7 * 86_400);
/// How long a domain without one is kept as without one.
const KEEP_MISSING: Duration = Duration::from_secs(86_400);
/// Names only a private network, or none, resolves.
const PRIVATE: [&str; 10] = [
    "localhost",
    "local",
    "internal",
    "intranet",
    "lan",
    "home",
    "invalid",
    "test",
    "example",
    "arpa",
];

/// A domain asked for, lowercased, if it is a hostname whose icon may be
/// asked: none for an address, or a private name unless `allow_private`.
pub fn checked_domain(domain: &str, allow_private: bool) -> Option<String> {
    let domain = domain.trim().trim_end_matches('.').to_ascii_lowercase();
    if domain.parse::<IpAddr>().is_ok() || !atproto::syntax::is_handle(&domain) {
        return None;
    }
    let tld = domain.rsplit('.').next()?;
    if !allow_private && (PRIVATE.contains(&tld) || tld.bytes().all(|b| b.is_ascii_digit())) {
        return None;
    }
    Some(domain)
}

impl Hud {
    /// The icon of `domain` (checked), a PNG: kept, or asked of the favicon
    /// service; none where the service has none, or none is asked; or why
    /// the service had no answer now, which is kept nowhere, so the next
    /// ask asks again (`net`).
    pub async fn icon(&self, domain: &str) -> Result<Option<Vec<u8>>, String> {
        let Some(service) = self.config.favicons.as_deref() else {
            return Ok(None);
        };
        let png = self.icon_path(domain, "png");
        let miss = self.icon_path(domain, "miss");
        if fresh(&png, KEEP).await {
            return Ok(tokio::fs::read(&png).await.ok());
        }
        if fresh(&miss, KEEP_MISSING).await {
            return Ok(None);
        }
        let asked = format!(
            "{service}{}",
            url::form_urlencoded::byte_serialize(format!("https://{domain}").as_bytes())
                .collect::<String>()
        );
        let found = match url::Url::parse(&asked) {
            Ok(url) => match self.net.fetch(&url, WAIT, ICON_AT_MOST).await {
                Ok(got) if got.status == 200 && got.header("content-type") == Some("image/png") => {
                    Some(got.body)
                }
                Ok(got) if got.unavailable() => {
                    return Err(format!("the favicon service answered {}", got.status));
                }
                Ok(got) => {
                    tracing::debug!(domain, status = got.status, "no icon");
                    None
                }
                Err(f) if f.answered => {
                    tracing::debug!(domain, why = %f, "no icon");
                    None
                }
                Err(f) => return Err(f.why),
            },
            Err(_) => None,
        };
        let (path, body): (&PathBuf, &[u8]) = match &found {
            Some(b) => (&png, b),
            None => (&miss, b""),
        };
        let kept = async {
            tokio::fs::create_dir_all(self.icon_dir()).await?;
            tokio::fs::write(path, body).await?;
            let other = if found.is_some() { &miss } else { &png };
            match tokio::fs::remove_file(other).await {
                Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
                _ => Ok(()),
            }
        };
        if let Err(e) = kept.await {
            tracing::warn!(domain, error = %e, "could not keep an icon");
        }
        Ok(found)
    }

    /// The directory icons are kept in.
    fn icon_dir(&self) -> PathBuf {
        self.config.cache_dir.join("icons")
    }

    fn icon_path(&self, domain: &str, ext: &str) -> PathBuf {
        self.icon_dir().join(format!("{domain}.{ext}"))
    }
}

/// Whether a file kept is younger than `keep`.
async fn fresh(path: &PathBuf, keep: Duration) -> bool {
    let Ok(meta) = tokio::fs::metadata(path).await else {
        return false;
    };
    meta.modified()
        .ok()
        .and_then(|m| SystemTime::now().duration_since(m).ok())
        .is_some_and(|age| age < keep)
}

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

    #[test]
    fn domains_checked() {
        assert_eq!(
            checked_domain("Bsky.App", false).as_deref(),
            Some("bsky.app")
        );
        assert_eq!(
            checked_domain("leaflet.pub.", false).as_deref(),
            Some("leaflet.pub")
        );
        for bad in [
            "127.0.0.1",
            "::1",
            "[::1]",
            "localhost",
            "printer.local",
            "hud.test",
            "a b.com",
            "no_dots",
            "x..y",
            "evil.com/path",
            "",
        ] {
            assert_eq!(checked_domain(bad, false), None, "{bad}");
        }
        assert_eq!(
            checked_domain("hud.test", true).as_deref(),
            Some("hud.test")
        );
        assert_eq!(checked_domain("10.0.0.1", true), None);
    }

    #[tokio::test]
    async fn icons_asked_kept_or_not() {
        const PNG: &[u8] = b"\x89PNG\r\n\x1a\nicon";
        let favicon = |axum::extract::Query(q): axum::extract::Query<
            std::collections::HashMap<String, String>,
        >| async move {
            use axum::http::StatusCode;
            use axum::response::IntoResponse;
            let png = [("content-type", "image/png")];
            match q["url"].as_str() {
                "https://busy.test" => StatusCode::SERVICE_UNAVAILABLE.into_response(),
                "https://none.test" => StatusCode::NOT_FOUND.into_response(),
                "https://huge.test" => (png, vec![0; ICON_AT_MOST + 1]).into_response(),
                _ => (png, PNG).into_response(),
            }
        };
        let app = axum::Router::new().route("/", axum::routing::get(favicon));
        let service = format!("{}/?url=", crate::tests::serve(app).await);
        let with = |favicons: Option<&str>| {
            let favicons = favicons.map(str::to_string);
            crate::tests::hud_with("http://127.0.0.1:1", |c| c.favicons = favicons)
        };
        // None asked of no service.
        assert_eq!(with(None).icon("png.test").await, Ok(None));
        let hud = with(Some(&service));
        assert_eq!(hud.icon("png.test").await, Ok(Some(PNG.to_vec())));
        // Kept: read again from disk.
        assert!(hud.icon_path("png.test", "png").exists());
        assert_eq!(hud.icon("png.test").await, Ok(Some(PNG.to_vec())));
        // None, kept as none; one too large is none as well.
        assert_eq!(hud.icon("none.test").await, Ok(None));
        assert!(hud.icon_path("none.test", "miss").exists());
        assert_eq!(hud.icon("none.test").await, Ok(None));
        assert_eq!(hud.icon("huge.test").await, Ok(None));
        // A service that cannot answer now is no answer, kept nowhere.
        assert_eq!(
            hud.icon("busy.test").await,
            Err("the favicon service answered 503".into())
        );
        assert!(!hud.icon_path("busy.test", "miss").exists());
        let closed = with(Some("http://127.0.0.1:1/?url="));
        assert_eq!(
            closed.icon("png.test").await,
            Err("could not connect".into())
        );
        // One named by no URL has none, and that is kept.
        let nowhere = with(Some("nowhere"));
        assert_eq!(nowhere.icon("png.test").await, Ok(None));
        assert!(nowhere.icon_path("png.test", "miss").exists());
        // What cannot be kept is still given.
        let file = std::env::temp_dir().join(format!("hud-icons-{}", atproto::jose::random(6)));
        std::fs::write(&file, "").unwrap();
        let mut diskless = with(Some(&service));
        std::sync::Arc::get_mut(&mut diskless)
            .unwrap()
            .config
            .cache_dir = file.clone();
        assert_eq!(diskless.icon("png.test").await, Ok(Some(PNG.to_vec())));
        let _ = std::fs::remove_file(file);
    }
}