~ 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
74 lines · 2.6 KB Raw History
//! `GET /icon/<domain>`: an app's icon, its site's favicon as
//! `hud_core::icons` finds it, a PNG, which tiles show
//! (`place.hud.defs#tileView`'s `icon`), the workspace's
//! launcher rows and an account's profile (`describe_repo`'s apps). A
//! public favicon, so served with sign-in off too. Kept by browsers a
//! week, with an `ETag`; a domain with
//! none, or one that is no hostname whose icon may be asked, is a `404`,
//! kept a day, which the page falls back from; when the favicon service
//! had no answer now, a `502` kept by no one, asked again the next time.

use axum::extract::{Path, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Response};
use hud_core::Hud;
use hud_core::icons::checked_domain;
use sha2::{Digest, Sha256};
use std::sync::Arc;

/// How long a browser keeps an icon, and a domain's having none.
const KEPT: &str = "public, max-age=604800";
const KEPT_MISSING: &str = "public, max-age=86400";

pub async fn icon(
    State(hud): State<Arc<Hud>>,
    Path(domain): Path<String>,
    headers: HeaderMap,
) -> Response {
    let found = match checked_domain(&domain, hud.config.allow_private) {
        Some(domain) => hud.icon(&domain).await,
        None => Ok(None),
    };
    let text = |status: StatusCode, kept: &'static str, body: &'static str| {
        (
            status,
            [
                (header::CACHE_CONTROL, kept),
                (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
            ],
            body,
        )
            .into_response()
    };
    let png = match found {
        Ok(Some(png)) => png,
        Ok(None) => return text(StatusCode::NOT_FOUND, KEPT_MISSING, "no icon"),
        Err(why) => {
            tracing::debug!(domain, why, "no answer for an icon");
            return text(StatusCode::BAD_GATEWAY, "no-store", "no answer for an icon");
        }
    };
    let digest = Sha256::digest(&png);
    let etag = format!("\"{}\"", atproto::jose::b64(&digest[..16]));
    let fresh = headers
        .get(header::IF_NONE_MATCH)
        .and_then(|v| v.to_str().ok())
        .is_some_and(|v| v.split(',').any(|t| t.trim() == etag));
    let status = if fresh {
        StatusCode::NOT_MODIFIED
    } else {
        StatusCode::OK
    };
    let body = if fresh { Vec::new() } else { png };
    (
        status,
        [
            (header::CONTENT_TYPE, "image/png".to_string()),
            (header::CACHE_CONTROL, KEPT.to_string()),
            (header::ETAG, etag),
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
        ],
        body,
    )
        .into_response()
}