Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/korp-map

crates/korp-map-wire/src/landing.rs

//! **The landing page** (`GET /` and `GET /v1/`): one HTML page, no external assets,
//! light and dark, saying what the server is, which regions it serves (fetched live
//! from `/v1/regions`), an example of every endpoint with a button that runs it, the
//! Python client, and the error codes. Every link is an absolute `/v1/…` or
//! `/openapi.json` path, so the page works at `/` and behind a front that routes only
//! `/v1/` and `/openapi.json` here.

use crate::error::Code;
use crate::server::ServerConfig;

const PAGE: &str = include_str!("landing.html");

/// `s` with `&`, `<`, `>` and `"` escaped.
fn escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

/// The page, for a server told `cfg`; `files_section` is the HTML of the file
/// downloads section (empty when none are served).
#[must_use]
pub fn page(cfg: &ServerConfig, files_section: &str) -> String {
    let about = cfg
        .about
        .as_deref()
        .map_or_else(|| "korp-map map wire, contract v1.2".to_string(), escape);
    let cors = match &cfg.cors_origin {
        Some(o) if o == "*" => {
            "any origin may read the replies (<code>Access-Control-Allow-Origin: *</code>)"
                .to_string()
        }
        Some(o) => format!("replies may be read by <code>{}</code>", escape(o)),
        None => "no CORS headers are sent".to_string(),
    };
    let codes: String = Code::ALL
        .iter()
        .map(|c| {
            format!(
                "<tr><td><code>{}</code></td><td>{}</td><td>{}</td></tr>\n",
                c.tag(),
                c.http_status(),
                escape(c.summary())
            )
        })
        .collect();
    PAGE.replace("{{ABOUT}}", &about)
        .replace("{{CORS}}", &cors)
        .replace("{{CODES}}", &codes)
        .replace("{{FILES_SECTION}}", files_section)
}

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

    #[test]
    fn the_page_is_filled_and_names_every_code() {
        let p = page(&ServerConfig::default(), "");
        assert!(!p.contains("{{"), "a placeholder is left");
        for c in Code::ALL {
            assert!(p.contains(&c.tag()), "{}", c.tag());
        }
        assert!(p.contains("korp-map map wire, contract v1.2"));
        assert!(p.contains("Access-Control-Allow-Origin: *"));
    }

    #[test]
    fn the_page_loads_nothing_from_elsewhere_and_links_only_absolute_server_paths() {
        let p = page(&ServerConfig::default(), "");
        assert!(!p.contains("<script src"), "no external script");
        assert!(!p.contains("<link"), "no external stylesheet");
        assert!(!p.contains("src=\"http"), "no external asset");
        for href in p
            .split("href=\"")
            .skip(1)
            .map(|s| s.split('"').next().unwrap())
        {
            assert!(
                href.starts_with("https://") || href.starts_with("/v1/") || href == "/openapi.json",
                "{href}: a link must work under the /v1/ prefix"
            );
        }
        for fetched in p
            .split("fetch(\"")
            .skip(1)
            .map(|s| s.split('"').next().unwrap())
        {
            assert!(fetched.starts_with("/v1/"), "{fetched}");
        }
    }

    #[test]
    fn the_about_line_is_escaped() {
        let cfg = ServerConfig {
            about: Some("korp-map-server 0.1.0 (<abc>)".into()),
            ..ServerConfig::default()
        };
        assert!(page(&cfg, "").contains("korp-map-server 0.1.0 (&lt;abc&gt;)"));
    }
}