~ 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
108 lines · 4.1 KB Raw History
//! The playground, sign-in on or off: `GET /playground`, its page (one
//! HTML file, `web/dist/playground.html`, embedded as `PLAYGROUND_HTML`),
//! where a view is written beside what it draws. The page calls
//! `getPlayground` and `previewView` (`crate::xrpc`), anyone's, as the web
//! session where the browser has one. Its CSP is the workspace's.

use crate::PLAYGROUND_HTML;
use crate::workspace::csp;
use axum::Router;
use axum::extract::State;
use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use hud_core::Hud;
use std::sync::Arc;

/// The playground's route.
pub fn routes() -> Router<Arc<Hud>> {
    Router::new().route("/playground", get(page))
}

/// `GET /playground`: the page.
async fn page(State(hud): State<Arc<Hud>>) -> Response {
    let policy = csp(
        &hud.config.public_origin,
        hud.config.image_cdn_origin().as_deref(),
    );
    (
        StatusCode::OK,
        [
            (header::CONTENT_TYPE, "text/html; charset=utf-8".to_string()),
            (header::CONTENT_SECURITY_POLICY, policy),
            (header::CACHE_CONTROL, "no-cache".to_string()),
            (header::REFERRER_POLICY, "no-referrer".to_string()),
            (header::X_FRAME_OPTIONS, "DENY".to_string()),
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
        ],
        PLAYGROUND_HTML,
    )
        .into_response()
}

#[cfg(test)]
mod tests {
    use axum::body::Body;
    use axum::http::{Request, StatusCode, header};
    use hud_core::{Config, Hud};
    use tower::ServiceExt;

    /// With sign-in off, the playground's page, its icon and its methods
    /// are there, the workspace's not.
    #[tokio::test]
    async fn the_playground_with_sign_in_off() {
        let dir = std::env::temp_dir().join(format!("hud-playground-{}", atproto::jose::random(6)));
        let hud = Hud::new(Config {
            port: 0,
            bind: "::".parse().unwrap(),
            public_origin: "http://localhost:8787".into(),
            cache_dir: dir.join("cache"),
            data_dir: dir,
            oauth: false,
            oauth_scope: hud_core::scope::asked(hud_core::view::views(), true, false),
            oauth_include: None,
            workspace: true,
            spaces: false,
            plc_url: "https://plc.directory".into(),
            handle_resolver: None,
            allow_private: false,
            blob_cache_bytes: 0,
            cache_memory_bytes: 1 << 20,
            backlinks: hud_core::backlinks::Backlinks::None,
            favicons: None,
            image_cdn: None,
            relay: None,
            sign_up_pds: hud_core::config::SIGN_UP_PDS.into(),
            client: Default::default(),
            operators: Vec::new(),
            logs: false,
            logs_keep: hud_core::logs::KEEP,
        })
        .unwrap();
        let got = async |path: &str| {
            let r = crate::router(hud.clone(), None)
                .oneshot(Request::get(path).body(Body::empty()).unwrap())
                .await
                .unwrap();
            let status = r.status();
            let headers = r.headers().clone();
            let body = axum::body::to_bytes(r.into_body(), usize::MAX)
                .await
                .unwrap();
            (status, headers, String::from_utf8(body.to_vec()).unwrap())
        };
        let (status, headers, body) = got("/playground").await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body, crate::PLAYGROUND_HTML);
        let policy = headers[header::CONTENT_SECURITY_POLICY].to_str().unwrap();
        assert!(policy.contains("connect-src 'self'"), "{policy}");
        assert_eq!(got("/favicon.svg").await.0, StatusCode::OK);
        let (status, _, body) = got("/xrpc/place.hud.getPlayground").await;
        assert_eq!(status, StatusCode::OK);
        assert!(body.contains("standard-document"));
        let (status, _, body) = got("/xrpc/place.hud.getWorkspace").await;
        assert_eq!(status, StatusCode::NOT_IMPLEMENTED, "{body}");
        assert!(body.contains("sign-in off"), "{body}");
        assert_eq!(got("/workspace").await.0, StatusCode::NOT_FOUND);
    }
}