rust-web-utils 0.1.0

Lightweight web utilities: client IP & trusted proxies, bot/browser detection, unified JSON response, business timezone, auth cookies + CSRF, cron guards, Next.js static export hosting
Documentation
//! 路径规范化、RSC 判定与响应头分类; 纯函数, 不碰磁盘

use http::HeaderMap;
use http::header::{CACHE_CONTROL, CONTENT_TYPE, HeaderValue, VARY};

/// RSC payload 响应必须携带的 Vary 头, 防止 CDN 把 HTML 与 RSC 缓存串台
pub const RSC_VARY: &str = "RSC, Next-Router-State-Tree, Next-Router-Prefetch";

/// RSC payload 的短缓存; 文件名不带 hash, 发版后最多 max-age + stale-while-revalidate 内可能拿到旧 payload
pub const RSC_CACHE_CONTROL: &str = "public, max-age=60, stale-while-revalidate=300";

/// HTML 的硬化禁缓存头; 普通 no-cache 会被部分 CDN (如 Cloudflare 默认规则) 忽略
pub const HTML_NO_STORE: &str = "no-store, no-cache, must-revalidate, max-age=0";

/// 与 Go `path.Clean` 一致地规范化以 `/` 开头的路径: 合并重复斜杠, 消除 `.` 与 `..`
/// (不越过根), 去掉末尾斜杠; 结果至少为 `/`
pub(crate) fn clean(p: &str) -> String {
    let mut segs: Vec<&str> = Vec::new();
    for seg in p.split('/') {
        match seg {
            "" | "." => {}
            ".." => {
                segs.pop();
            }
            s => segs.push(s),
        }
    }
    let mut out = String::with_capacity(p.len() + 1);
    for s in &segs {
        out.push('/');
        out.push_str(s);
    }
    if out.is_empty() {
        out.push('/');
    }
    out
}

/// 最后一级路径段的扩展名 (含点), 无扩展名时为空串; 同 Go `path.Ext`
pub(crate) fn ext(p: &str) -> &str {
    let base = &p[p.rfind('/').map_or(0, |i| i + 1)..];
    base.rfind('.').map_or("", |i| &base[i..])
}

/// 同 Go `path.Dir` (输入为以 `/` 开头的规范路径)
pub(crate) fn dir(p: &str) -> &str {
    match p.rfind('/') {
        Some(0) | None => "/",
        Some(i) => &p[..i],
    }
}

/// `dir` 下的 `name`; `dir` 为 `/` 时不重复斜杠
pub(crate) fn join(dir: &str, name: &str) -> String {
    if dir == "/" {
        format!("/{name}")
    } else {
        format!("{dir}/{name}")
    }
}

/// 判断路径是否为 Next.js export 的 RSC 数据文件。覆盖 Next 15 (每目录 `index.txt`) 与
/// Next 16 (`__next._index.txt` / `__next._tree.txt` / `__next.__PAGE__.txt` / route group
/// `__next.!<b64>...` / 点号形态); `robots.txt` / `ads.txt` 等普通文本不会命中。
/// 大小写不敏感, 防大小写不敏感文件系统上被变体绕过
pub fn is_rsc_payload(p: &str) -> bool {
    let base = p.rsplit('/').next().unwrap_or(p).to_ascii_lowercase();
    if !base.ends_with(".txt") {
        return false;
    }
    base == "index.txt" || base.starts_with("__next.") || base.ends_with("__page__.txt")
}

fn set(headers: &mut HeaderMap, name: http::HeaderName, value: &'static str) {
    headers.insert(name, HeaderValue::from_static(value));
}

/// 按响应路径分类设置 `Content-Type`、`Vary` 与缓存头 (覆盖已有值)。
/// 分类: RSC `.txt` / `sw.js` / manifest / robots + sitemap / `/_next/static` / 普通 `.txt` /
/// 图片字体; 其余保持文件服务按扩展名推断的类型
pub fn set_headers(headers: &mut HeaderMap, url_path: &str) {
    let lower = url_path.to_ascii_lowercase();
    if is_rsc_payload(&lower) {
        set(headers, CONTENT_TYPE, "text/x-component; charset=utf-8");
        set(headers, VARY, RSC_VARY);
        // 短缓存: <Link> 预取很密, 避免每次都回源做条件请求; 不用 immutable
        set(headers, CACHE_CONTROL, RSC_CACHE_CONTROL);
    } else if lower == "/sw.js" {
        // Service Worker 必须实时更新, 且作用域头允许挂根
        set(headers, CONTENT_TYPE, "application/javascript; charset=utf-8");
        set(headers, CACHE_CONTROL, "no-cache");
        headers.insert("service-worker-allowed", HeaderValue::from_static("/"));
    } else if lower == "/manifest.json" || lower.ends_with(".webmanifest") {
        set(headers, CONTENT_TYPE, "application/manifest+json; charset=utf-8");
        set(headers, CACHE_CONTROL, "public, max-age=300");
    } else if lower == "/robots.txt" || lower == "/sitemap.xml" {
        set(headers, CACHE_CONTROL, "public, max-age=3600");
        if lower.ends_with(".txt") {
            set(headers, CONTENT_TYPE, "text/plain; charset=utf-8");
        }
    } else if lower.starts_with("/_next/static/") {
        set(headers, CACHE_CONTROL, "public, max-age=31536000, immutable");
    } else if lower.ends_with(".txt") {
        set(headers, CONTENT_TYPE, "text/plain; charset=utf-8");
    } else if [
        ".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".svg", ".ico", ".woff", ".woff2", ".ttf", ".otf",
    ]
    .iter()
    .any(|s| lower.ends_with(s))
    {
        set(headers, CACHE_CONTROL, "public, max-age=86400");
    }
}

/// 还原 Next 16 route group 的点号 RSC 路径为磁盘目录结构:
/// `/admin/users/__next.!<b64>.admin.users.__PAGE__.txt`
/// → `/admin/users/__next.!<b64>/admin/users/__PAGE__.txt`;
/// `__next._index.txt` 等平铺文件名 (`__next.` 后紧跟 `_`) 不转换, 返回 `None`
pub(crate) fn restore_rsc_dot_path(p: &str) -> Option<String> {
    let idx = p.find("/__next.")?;
    let dir_part = &p[..=idx];
    let after = &p[idx + "/__next.".len()..];
    if after.starts_with('_') {
        return None;
    }
    let stem = after.strip_suffix(".txt")?;
    let parts: Vec<&str> = stem.split('.').collect();
    if parts.len() < 2 {
        return None;
    }
    // 首段 (route group 编码或路由段) 留在 __next. 目录名内, 中间段还原为子目录, 末段加回扩展名
    let mut out = format!("{dir_part}__next.{}", parts[0]);
    for seg in &parts[1..parts.len() - 1] {
        out.push('/');
        out.push_str(seg);
    }
    out.push('/');
    out.push_str(parts[parts.len() - 1]);
    out.push_str(".txt");
    Some(out)
}

/// 拆成 (父目录的父目录, 文件名); 最后一级目录不存在 (文件直接在根下) 时返回 `None`
fn split_last_dir(p: &str) -> Option<(&str, &str)> {
    let slash = p.rfind('/')?;
    let (d, base) = (&p[..slash], &p[slash + 1..]);
    if d.is_empty() {
        return None;
    }
    Some((dir(d), base))
}

/// 把最后一级目录替换为动态路由占位符 `_`:
/// `/voddetail/123/index.html` → `/voddetail/_/index.html`
pub(crate) fn placeholder_path(p: &str) -> Option<String> {
    split_last_dir(p).map(|(parent, base)| join(&join(parent, "_"), base))
}

/// 去掉最后一级目录 (保留文件名), 用于"动态详情 RSC 数据落在父目录"形态:
/// `/app/12345/index.txt` → `/app/index.txt`
pub(crate) fn drop_last_dir(p: &str) -> Option<String> {
    split_last_dir(p).map(|(parent, base)| join(parent, base))
}

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

    #[test]
    fn clean_paths() {
        for (input, want) in [
            ("/", "/"),
            ("//", "/"),
            ("/a/b/", "/a/b"),
            ("/a//b/./c", "/a/b/c"),
            ("/../../etc/passwd", "/etc/passwd"),
            ("/a/../../b", "/b"),
            ("/a/..", "/"),
            ("//evil.com", "/evil.com"),
        ] {
            assert_eq!(clean(input), want, "{input}");
        }
    }

    #[test]
    fn ext_and_dir() {
        assert_eq!(ext("/a/b.js"), ".js");
        assert_eq!(ext("/v1.2/foo"), "");
        assert_eq!(ext("/foo."), ".");
        assert_eq!(ext("/"), "");
        assert_eq!(dir("/a/b"), "/a");
        assert_eq!(dir("/a"), "/");
        assert_eq!(join("/", "x"), "/x");
        assert_eq!(join("/a", "x"), "/a/x");
    }

    #[test]
    fn rsc_payload() {
        for (p, want) in [
            ("/index.txt", true),
            ("/INDEX.TXT", true),
            ("/about/__next._index.txt", true),
            ("/about/__next._head.txt", true),
            ("/about/__next._tree.txt", true),
            ("/about/__next._full.txt", true),
            ("/admin/users/__next.!KGNvbnNvbGUp.admin.users.__PAGE__.txt", true),
            ("/x/__PAGE__.txt", true),
            ("/robots.txt", false),
            ("/ads.txt", false),
            ("/.well-known/security.txt", false),
            ("/app.js", false),
        ] {
            assert_eq!(is_rsc_payload(p), want, "{p}");
        }
    }

    #[test]
    fn restore_dot_path() {
        let cases = [
            (
                "/admin/users/__next.!KGNvbnNvbGUp.admin.users.__PAGE__.txt",
                Some("/admin/users/__next.!KGNvbnNvbGUp/admin/users/__PAGE__.txt"),
            ),
            (
                "/voddetail/123/__next.voddetail.$d$id.__PAGE__.txt",
                Some("/voddetail/123/__next.voddetail/$d$id/__PAGE__.txt"),
            ),
            ("/about/__next._index.txt", None),
            ("/about/__next._tree.txt", None),
            ("/__next.__PAGE__.txt", None),
            ("/robots.txt", None),
        ];
        for (input, want) in cases {
            assert_eq!(restore_rsc_dot_path(input).as_deref(), want, "{input}");
        }
    }

    #[test]
    fn placeholder_and_parent() {
        assert_eq!(
            placeholder_path("/voddetail/123/index.html").as_deref(),
            Some("/voddetail/_/index.html")
        );
        assert_eq!(placeholder_path("/123/index.html").as_deref(), Some("/_/index.html"));
        assert_eq!(placeholder_path("/index.html"), None);
        assert_eq!(drop_last_dir("/app/12345/index.txt").as_deref(), Some("/app/index.txt"));
        assert_eq!(drop_last_dir("/app/index.txt").as_deref(), Some("/index.txt"));
        assert_eq!(drop_last_dir("/index.txt"), None);
    }

    #[test]
    fn header_classes() {
        let check = |p: &str| {
            let mut h = HeaderMap::new();
            set_headers(&mut h, p);
            h
        };
        let h = check("/about/__next._index.txt");
        assert_eq!(h[CONTENT_TYPE], "text/x-component; charset=utf-8");
        assert_eq!(h[VARY], RSC_VARY);
        assert_eq!(h[CACHE_CONTROL], RSC_CACHE_CONTROL);

        let h = check("/sw.js");
        assert_eq!(h[CACHE_CONTROL], "no-cache");
        assert_eq!(h["service-worker-allowed"], "/");

        assert_eq!(
            check("/manifest.json")[CONTENT_TYPE],
            "application/manifest+json; charset=utf-8"
        );
        assert_eq!(check("/site.webmanifest")[CACHE_CONTROL], "public, max-age=300");
        assert_eq!(check("/robots.txt")[CACHE_CONTROL], "public, max-age=3600");
        assert!(check("/robots.txt").get(VARY).is_none());
        assert_eq!(
            check("/_NEXT/static/chunk.js")[CACHE_CONTROL],
            "public, max-age=31536000, immutable"
        );
        assert_eq!(check("/ads.txt")[CONTENT_TYPE], "text/plain; charset=utf-8");
        assert_eq!(check("/logo.PNG")[CACHE_CONTROL], "public, max-age=86400");
        assert!(check("/app.js").is_empty());
    }
}