arks-server 1.3.2

Git server: upload-pack / receive-pack + smart/dumb HTTP + daemon (M11/M25)
Documentation
//! Progressive Web App (`/manifest.webmanifest`, `/sw.js`, `/offline`) and
//! well-known discovery endpoints (`/.well-known/security.txt`, `/.well-known/api-catalog`)
//! governed by `web-platform-baseline.sot.md` WP-PWA-1..3 and `rest-api-standards.sot.md` RA-DSC-2..3.
//!
//! PWA is enabled by default and can be disabled with `ARKS_WEB_PWA=false` (or `0`),
//! in which case `/manifest.webmanifest` returns 404 and `/sw.js` serves an unregister script.
//! Authenticated HTML, `/api/*`, `/repos/*`, Git Smart HTTP, LFS, and WebDAV are strictly
//! network-only and never cached by the Service Worker.

use crate::http::{HttpRequest, HttpResponse};
use crate::web::core::assets::{core_asset_url, core_manifest_hash};
use crate::web::ui::shell::respond_html;

/// Returns `true` unless the operator explicitly opted out via `ARKS_WEB_PWA=false|0`.
pub fn pwa_enabled() -> bool {
    match std::env::var("ARKS_WEB_PWA") {
        Ok(val) => !matches!(
            val.trim().to_ascii_lowercase().as_str(),
            "0" | "false" | "off"
        ),
        Err(_) => true,
    }
}

/// Dispatch PWA and `.well-known` discovery routes independently of repository discovery.
pub fn serve_pwa_route(req: &HttpRequest) -> Option<HttpResponse> {
    serve_pwa_route_with(req, pwa_enabled(), None, None)
}

pub(crate) fn serve_pwa_route_with(
    req: &HttpRequest,
    enabled: bool,
    security_contact: Option<&str>,
    security_expires: Option<&str>,
) -> Option<HttpResponse> {
    let path = req.path.as_str();
    if !matches!(
        path,
        "/manifest.webmanifest"
            | "/sw.js"
            | "/offline"
            | "/.well-known/security.txt"
            | "/.well-known/api-catalog"
    ) {
        return None;
    }

    if req.method == "OPTIONS" {
        return Some(HttpResponse {
            status: 204,
            content_type: "text/plain; charset=utf-8".into(),
            body: Vec::new(),
            www_authenticate: None,
            extra_headers: vec![("Allow".into(), "GET, HEAD, OPTIONS".into())],
        });
    }
    if !matches!(req.method.as_str(), "GET" | "HEAD") {
        return Some(HttpResponse {
            status: 405,
            content_type: "text/plain; charset=utf-8".into(),
            body: b"Method Not Allowed\n".to_vec(),
            www_authenticate: None,
            extra_headers: vec![("Allow".into(), "GET, HEAD, OPTIONS".into())],
        });
    }

    match path {
        "/manifest.webmanifest" => {
            if !enabled {
                return Some(HttpResponse {
                    status: 404,
                    content_type: "text/plain; charset=utf-8".into(),
                    body: b"PWA disabled by operator configuration\n".to_vec(),
                    www_authenticate: None,
                    extra_headers: vec![("Cache-Control".into(), "no-store".into())],
                });
            }
            let icon_svg = core_asset_url("/favicon.svg");
            let manifest = serde_json::json!({
                "name": "arks",
                "short_name": "arks",
                "description": "Self-hosted Git-compatible forge and revision server",
                "start_url": "/",
                "scope": "/",
                "display": "standalone",
                "background_color": "#0a0a0a",
                "theme_color": "#0a0a0a",
                "icons": [
                    {
                        "src": icon_svg,
                        "sizes": "any",
                        "type": "image/svg+xml",
                        "purpose": "any maskable"
                    }
                ]
            });
            let body = serde_json::to_vec_pretty(&manifest).unwrap_or_default();
            Some(HttpResponse {
                status: 200,
                content_type: "application/manifest+json; charset=utf-8".into(),
                body,
                www_authenticate: None,
                extra_headers: vec![
                    ("Cache-Control".into(), "no-cache".into()),
                    ("X-Content-Type-Options".into(), "nosniff".into()),
                ],
            })
        }
        "/sw.js" => {
            let js = if enabled {
                build_service_worker_js()
            } else {
                // Opt-out unregister script (WP-PWA-3).
                "self.addEventListener('install', function () { self.skipWaiting(); });\n\
                 self.addEventListener('activate', function (e) {\n\
                   e.waitUntil(caches.keys().then(function (ks) {\n\
                     return Promise.all(ks.map(function (k) { return caches.delete(k); }));\n\
                   }).then(function () { return self.registration.unregister(); }));\n\
                 });\n"
                    .to_string()
            };
            Some(HttpResponse {
                status: 200,
                content_type: "application/javascript; charset=utf-8".into(),
                body: js.into_bytes(),
                www_authenticate: None,
                extra_headers: vec![
                    ("Cache-Control".into(), "no-cache".into()),
                    ("Service-Worker-Allowed".into(), "/".into()),
                    ("X-Content-Type-Options".into(), "nosniff".into()),
                ],
            })
        }
        "/offline" => {
            let style = core_asset_url("/style.css");
            let theme_js = core_asset_url("/assets/theme-init.js");
            let html = format!(
                "<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\">\
                 <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
                 <meta name=\"color-scheme\" content=\"light dark\">\
                 <title>Offline — arks</title>\
                 <script src=\"{theme_js}\"></script>\
                 <link rel=\"stylesheet\" href=\"{style}\"></head>\
                 <body><main id=\"main-content\" class=\"mr-auth-main\">\
                 <div class=\"card\"><div class=\"card-header\"><strong>Offline</strong></div>\
                 <div class=\"card-body\"><p>Your connection to this arks instance is currently unavailable.</p>\
                 <p class=\"muted\">Authenticated pages, APIs, and Git operations are never cached offline.</p>\
                 <p><a class=\"btn\" href=\"/\">Retry</a></p></div></div></main></body></html>"
            );
            Some(respond_html(200, html))
        }
        "/.well-known/security.txt" => {
            // RFC 9116 (RA-DSC-2): 404 unless operator configures Contact AND Expires; never invent contacts.
            let env_contact = std::env::var("ARKS_SECURITY_CONTACT").ok();
            let env_expires = std::env::var("ARKS_SECURITY_EXPIRES").ok();
            let contact = security_contact
                .or(env_contact.as_deref())
                .map(str::trim)
                .filter(|s| !s.is_empty());
            let expires = security_expires
                .or(env_expires.as_deref())
                .map(str::trim)
                .filter(|s| !s.is_empty());
            match (contact, expires) {
                (Some(c), Some(e)) => {
                    let body = format!("Contact: {c}\nExpires: {e}\nPreferred-Languages: en\n");
                    Some(HttpResponse {
                        status: 200,
                        content_type: "text/plain; charset=utf-8".into(),
                        body: body.into_bytes(),
                        www_authenticate: None,
                        extra_headers: vec![
                            ("Cache-Control".into(), "public, max-age=3600".into()),
                            ("X-Content-Type-Options".into(), "nosniff".into()),
                        ],
                    })
                }
                _ => Some(HttpResponse {
                    status: 404,
                    content_type: "text/plain; charset=utf-8".into(),
                    body: b"security.txt not configured\n".to_vec(),
                    www_authenticate: None,
                    extra_headers: vec![("Cache-Control".into(), "no-store".into())],
                }),
            }
        }
        "/.well-known/api-catalog" => {
            // RFC 9727 application/linkset+json pointing to runtime OpenAPI 3.1.0.
            let catalog = serde_json::json!({
                "linkset": [
                    {
                        "anchor": "/api/v1",
                        "service-desc": [
                            {
                                "href": "/api/v1/openapi.json",
                                "type": "application/openapi+json"
                            }
                        ],
                        "status": [
                            {
                                "href": "/healthz",
                                "type": "application/json"
                            }
                        ]
                    }
                ]
            });
            let body = serde_json::to_vec_pretty(&catalog).unwrap_or_default();
            Some(HttpResponse {
                status: 200,
                content_type: "application/linkset+json; charset=utf-8".into(),
                body,
                www_authenticate: None,
                extra_headers: vec![
                    ("Cache-Control".into(), "no-cache".into()),
                    ("X-Content-Type-Options".into(), "nosniff".into()),
                ],
            })
        }
        _ => None,
    }
}

fn build_service_worker_js() -> String {
    let ver = core_manifest_hash();
    let precache = [
        core_asset_url("/style.css"),
        core_asset_url("/assets/theme-init.js"),
        core_asset_url("/assets/app.js"),
        core_asset_url("/assets/htmx.min.js"),
        core_asset_url("/assets/icons.svg"),
        core_asset_url("/favicon.svg"),
        "/offline",
    ];
    let precache_json = serde_json::to_string(&precache).unwrap_or_else(|_| "[]".into());
    format!(
        "/* arks serve Service Worker (WP-PWA-2): precaches fingerprinted static assets & /offline only. */\n\
         const CACHE_NAME = 'arks-static-{ver}';\n\
         const PRECACHE = {precache_json};\n\
         self.addEventListener('install', function (e) {{\n\
           e.waitUntil(caches.open(CACHE_NAME).then(function (c) {{ return c.addAll(PRECACHE); }}).then(function () {{ return self.skipWaiting(); }}));\n\
         }});\n\
         self.addEventListener('activate', function (e) {{\n\
           e.waitUntil(caches.keys().then(function (ks) {{\n\
             return Promise.all(ks.filter(function (k) {{ return k !== CACHE_NAME; }}).map(function (k) {{ return caches.delete(k); }}));\n\
           }}).then(function () {{ return self.clients.claim(); }}));\n\
         }});\n\
         function isNetworkOnly(url) {{\n\
           var p = url.pathname;\n\
           return p.startsWith('/api/') || p.startsWith('/repos/') || p.startsWith('/login') ||\n\
                  p.startsWith('/register') || p.startsWith('/logout') || p.startsWith('/settings') ||\n\
                  p.startsWith('/admin') || p.indexOf('/info/refs') !== -1 ||\n\
                  p.indexOf('/git-upload-pack') !== -1 || p.indexOf('/git-receive-pack') !== -1 ||\n\
                  p.indexOf('/info/lfs/') !== -1;\n\
         }}\n\
         self.addEventListener('fetch', function (e) {{\n\
           var req = e.request;\n\
           if (req.method !== 'GET') return;\n\
           var url = new URL(req.url);\n\
           if (url.origin !== self.location.origin || isNetworkOnly(url)) return;\n\
           if (req.mode === 'navigate') {{\n\
             e.respondWith(fetch(req).catch(function () {{ return caches.match('/offline'); }}));\n\
             return;\n\
           }}\n\
           if (PRECACHE.indexOf(url.pathname) !== -1) {{\n\
             e.respondWith(caches.match(req).then(function (hit) {{ return hit || fetch(req); }}));\n\
           }}\n\
         }});\n"
    )
}

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

    #[test]
    fn manifest_sw_offline_and_opt_out_follow_w6() {
        let m_req = HttpRequest::new("GET", "/manifest.webmanifest", "", Vec::new());
        let m_resp = serve_pwa_route_with(&m_req, true, None, None).unwrap();
        assert_eq!(m_resp.status, 200);
        assert!(m_resp.content_type.contains("application/manifest+json"));
        let mv: serde_json::Value = serde_json::from_slice(&m_resp.body).unwrap();
        assert_eq!(mv["name"], "arks");
        assert_eq!(mv["display"], "standalone");

        let sw_req = HttpRequest::new("GET", "/sw.js", "", Vec::new());
        let sw_resp = serve_pwa_route_with(&sw_req, true, None, None).unwrap();
        assert_eq!(sw_resp.status, 200);
        assert!(
            sw_resp
                .extra_headers
                .contains(&("Service-Worker-Allowed".into(), "/".into()))
        );
        assert!(
            sw_resp
                .extra_headers
                .contains(&("Cache-Control".into(), "no-cache".into()))
        );
        let sw_txt = String::from_utf8(sw_resp.body).unwrap();
        assert!(sw_txt.contains("/git-upload-pack"));
        assert!(sw_txt.contains("/info/lfs/"));
        assert!(sw_txt.contains("/api/"));

        // Opt-out: manifest returns 404, sw.js unregisters.
        let m_off = serve_pwa_route_with(&m_req, false, None, None).unwrap();
        assert_eq!(m_off.status, 404);
        let sw_off = serve_pwa_route_with(&sw_req, false, None, None).unwrap();
        assert_eq!(sw_off.status, 200);
        assert!(
            String::from_utf8(sw_off.body)
                .unwrap()
                .contains("unregister()")
        );

        // Offline page renders HTML.
        let off_req = HttpRequest::new("GET", "/offline", "", Vec::new());
        let off_resp = serve_pwa_route_with(&off_req, true, None, None).unwrap();
        assert_eq!(off_resp.status, 200);
        assert!(
            String::from_utf8(off_resp.body)
                .unwrap()
                .contains("Offline")
        );
    }

    #[test]
    fn security_txt_is_404_unless_configured_and_api_catalog_is_linkset() {
        let sec_req = HttpRequest::new("GET", "/.well-known/security.txt", "", Vec::new());
        let sec_404 = serve_pwa_route_with(&sec_req, true, None, None).unwrap();
        assert_eq!(sec_404.status, 404);

        let sec_ok = serve_pwa_route_with(
            &sec_req,
            true,
            Some("mailto:sec@example.invalid"),
            Some("2027-01-01T00:00:00Z"),
        )
        .unwrap();
        assert_eq!(sec_ok.status, 200);
        let txt = String::from_utf8(sec_ok.body).unwrap();
        assert!(txt.contains("Contact: mailto:sec@example.invalid"));
        assert!(txt.contains("Expires: 2027-01-01T00:00:00Z"));

        let cat_req = HttpRequest::new("GET", "/.well-known/api-catalog", "", Vec::new());
        let cat_resp = serve_pwa_route_with(&cat_req, true, None, None).unwrap();
        assert_eq!(cat_resp.status, 200);
        assert!(cat_resp.content_type.contains("application/linkset+json"));
        assert!(
            String::from_utf8(cat_resp.body)
                .unwrap()
                .contains("/api/v1/openapi.json")
        );
    }
}