Skip to main content

rust_web_utils/nextstatic/
paths.rs

1//! 路径规范化、RSC 判定与响应头分类; 纯函数, 不碰磁盘
2
3use http::HeaderMap;
4use http::header::{CACHE_CONTROL, CONTENT_TYPE, HeaderValue, VARY};
5
6/// RSC payload 响应必须携带的 Vary 头, 防止 CDN 把 HTML 与 RSC 缓存串台
7pub const RSC_VARY: &str = "RSC, Next-Router-State-Tree, Next-Router-Prefetch";
8
9/// RSC payload 的短缓存; 文件名不带 hash, 发版后最多 max-age + stale-while-revalidate 内可能拿到旧 payload
10pub const RSC_CACHE_CONTROL: &str = "public, max-age=60, stale-while-revalidate=300";
11
12/// HTML 的硬化禁缓存头; 普通 no-cache 会被部分 CDN (如 Cloudflare 默认规则) 忽略
13pub const HTML_NO_STORE: &str = "no-store, no-cache, must-revalidate, max-age=0";
14
15/// 与 Go `path.Clean` 一致地规范化以 `/` 开头的路径: 合并重复斜杠, 消除 `.` 与 `..`
16/// (不越过根), 去掉末尾斜杠; 结果至少为 `/`
17pub(crate) fn clean(p: &str) -> String {
18    let mut segs: Vec<&str> = Vec::new();
19    for seg in p.split('/') {
20        match seg {
21            "" | "." => {}
22            ".." => {
23                segs.pop();
24            }
25            s => segs.push(s),
26        }
27    }
28    let mut out = String::with_capacity(p.len() + 1);
29    for s in &segs {
30        out.push('/');
31        out.push_str(s);
32    }
33    if out.is_empty() {
34        out.push('/');
35    }
36    out
37}
38
39/// 最后一级路径段的扩展名 (含点), 无扩展名时为空串; 同 Go `path.Ext`
40pub(crate) fn ext(p: &str) -> &str {
41    let base = &p[p.rfind('/').map_or(0, |i| i + 1)..];
42    base.rfind('.').map_or("", |i| &base[i..])
43}
44
45/// 同 Go `path.Dir` (输入为以 `/` 开头的规范路径)
46pub(crate) fn dir(p: &str) -> &str {
47    match p.rfind('/') {
48        Some(0) | None => "/",
49        Some(i) => &p[..i],
50    }
51}
52
53/// `dir` 下的 `name`; `dir` 为 `/` 时不重复斜杠
54pub(crate) fn join(dir: &str, name: &str) -> String {
55    if dir == "/" {
56        format!("/{name}")
57    } else {
58        format!("{dir}/{name}")
59    }
60}
61
62/// 判断路径是否为 Next.js export 的 RSC 数据文件。覆盖 Next 15 (每目录 `index.txt`) 与
63/// Next 16 (`__next._index.txt` / `__next._tree.txt` / `__next.__PAGE__.txt` / route group
64/// `__next.!<b64>...` / 点号形态); `robots.txt` / `ads.txt` 等普通文本不会命中。
65/// 大小写不敏感, 防大小写不敏感文件系统上被变体绕过
66pub fn is_rsc_payload(p: &str) -> bool {
67    let base = p.rsplit('/').next().unwrap_or(p).to_ascii_lowercase();
68    if !base.ends_with(".txt") {
69        return false;
70    }
71    base == "index.txt" || base.starts_with("__next.") || base.ends_with("__page__.txt")
72}
73
74fn set(headers: &mut HeaderMap, name: http::HeaderName, value: &'static str) {
75    headers.insert(name, HeaderValue::from_static(value));
76}
77
78/// 按响应路径分类设置 `Content-Type`、`Vary` 与缓存头 (覆盖已有值)。
79/// 分类: RSC `.txt` / `sw.js` / manifest / robots + sitemap / `/_next/static` / 普通 `.txt` /
80/// 图片字体; 其余保持文件服务按扩展名推断的类型
81pub fn set_headers(headers: &mut HeaderMap, url_path: &str) {
82    let lower = url_path.to_ascii_lowercase();
83    if is_rsc_payload(&lower) {
84        set(headers, CONTENT_TYPE, "text/x-component; charset=utf-8");
85        set(headers, VARY, RSC_VARY);
86        // 短缓存: <Link> 预取很密, 避免每次都回源做条件请求; 不用 immutable
87        set(headers, CACHE_CONTROL, RSC_CACHE_CONTROL);
88    } else if lower == "/sw.js" {
89        // Service Worker 必须实时更新, 且作用域头允许挂根
90        set(headers, CONTENT_TYPE, "application/javascript; charset=utf-8");
91        set(headers, CACHE_CONTROL, "no-cache");
92        headers.insert("service-worker-allowed", HeaderValue::from_static("/"));
93    } else if lower == "/manifest.json" || lower.ends_with(".webmanifest") {
94        set(headers, CONTENT_TYPE, "application/manifest+json; charset=utf-8");
95        set(headers, CACHE_CONTROL, "public, max-age=300");
96    } else if lower == "/robots.txt" || lower == "/sitemap.xml" {
97        set(headers, CACHE_CONTROL, "public, max-age=3600");
98        if lower.ends_with(".txt") {
99            set(headers, CONTENT_TYPE, "text/plain; charset=utf-8");
100        }
101    } else if lower.starts_with("/_next/static/") {
102        set(headers, CACHE_CONTROL, "public, max-age=31536000, immutable");
103    } else if lower.ends_with(".txt") {
104        set(headers, CONTENT_TYPE, "text/plain; charset=utf-8");
105    } else if [
106        ".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".svg", ".ico", ".woff", ".woff2", ".ttf", ".otf",
107    ]
108    .iter()
109    .any(|s| lower.ends_with(s))
110    {
111        set(headers, CACHE_CONTROL, "public, max-age=86400");
112    }
113}
114
115/// 还原 Next 16 route group 的点号 RSC 路径为磁盘目录结构:
116/// `/admin/users/__next.!<b64>.admin.users.__PAGE__.txt`
117/// → `/admin/users/__next.!<b64>/admin/users/__PAGE__.txt`;
118/// `__next._index.txt` 等平铺文件名 (`__next.` 后紧跟 `_`) 不转换, 返回 `None`
119pub(crate) fn restore_rsc_dot_path(p: &str) -> Option<String> {
120    let idx = p.find("/__next.")?;
121    let dir_part = &p[..=idx];
122    let after = &p[idx + "/__next.".len()..];
123    if after.starts_with('_') {
124        return None;
125    }
126    let stem = after.strip_suffix(".txt")?;
127    let parts: Vec<&str> = stem.split('.').collect();
128    if parts.len() < 2 {
129        return None;
130    }
131    // 首段 (route group 编码或路由段) 留在 __next. 目录名内, 中间段还原为子目录, 末段加回扩展名
132    let mut out = format!("{dir_part}__next.{}", parts[0]);
133    for seg in &parts[1..parts.len() - 1] {
134        out.push('/');
135        out.push_str(seg);
136    }
137    out.push('/');
138    out.push_str(parts[parts.len() - 1]);
139    out.push_str(".txt");
140    Some(out)
141}
142
143/// 拆成 (父目录的父目录, 文件名); 最后一级目录不存在 (文件直接在根下) 时返回 `None`
144fn split_last_dir(p: &str) -> Option<(&str, &str)> {
145    let slash = p.rfind('/')?;
146    let (d, base) = (&p[..slash], &p[slash + 1..]);
147    if d.is_empty() {
148        return None;
149    }
150    Some((dir(d), base))
151}
152
153/// 把最后一级目录替换为动态路由占位符 `_`:
154/// `/voddetail/123/index.html` → `/voddetail/_/index.html`
155pub(crate) fn placeholder_path(p: &str) -> Option<String> {
156    split_last_dir(p).map(|(parent, base)| join(&join(parent, "_"), base))
157}
158
159/// 去掉最后一级目录 (保留文件名), 用于"动态详情 RSC 数据落在父目录"形态:
160/// `/app/12345/index.txt` → `/app/index.txt`
161pub(crate) fn drop_last_dir(p: &str) -> Option<String> {
162    split_last_dir(p).map(|(parent, base)| join(parent, base))
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    #[test]
170    fn clean_paths() {
171        for (input, want) in [
172            ("/", "/"),
173            ("//", "/"),
174            ("/a/b/", "/a/b"),
175            ("/a//b/./c", "/a/b/c"),
176            ("/../../etc/passwd", "/etc/passwd"),
177            ("/a/../../b", "/b"),
178            ("/a/..", "/"),
179            ("//evil.com", "/evil.com"),
180        ] {
181            assert_eq!(clean(input), want, "{input}");
182        }
183    }
184
185    #[test]
186    fn ext_and_dir() {
187        assert_eq!(ext("/a/b.js"), ".js");
188        assert_eq!(ext("/v1.2/foo"), "");
189        assert_eq!(ext("/foo."), ".");
190        assert_eq!(ext("/"), "");
191        assert_eq!(dir("/a/b"), "/a");
192        assert_eq!(dir("/a"), "/");
193        assert_eq!(join("/", "x"), "/x");
194        assert_eq!(join("/a", "x"), "/a/x");
195    }
196
197    #[test]
198    fn rsc_payload() {
199        for (p, want) in [
200            ("/index.txt", true),
201            ("/INDEX.TXT", true),
202            ("/about/__next._index.txt", true),
203            ("/about/__next._head.txt", true),
204            ("/about/__next._tree.txt", true),
205            ("/about/__next._full.txt", true),
206            ("/admin/users/__next.!KGNvbnNvbGUp.admin.users.__PAGE__.txt", true),
207            ("/x/__PAGE__.txt", true),
208            ("/robots.txt", false),
209            ("/ads.txt", false),
210            ("/.well-known/security.txt", false),
211            ("/app.js", false),
212        ] {
213            assert_eq!(is_rsc_payload(p), want, "{p}");
214        }
215    }
216
217    #[test]
218    fn restore_dot_path() {
219        let cases = [
220            (
221                "/admin/users/__next.!KGNvbnNvbGUp.admin.users.__PAGE__.txt",
222                Some("/admin/users/__next.!KGNvbnNvbGUp/admin/users/__PAGE__.txt"),
223            ),
224            (
225                "/voddetail/123/__next.voddetail.$d$id.__PAGE__.txt",
226                Some("/voddetail/123/__next.voddetail/$d$id/__PAGE__.txt"),
227            ),
228            ("/about/__next._index.txt", None),
229            ("/about/__next._tree.txt", None),
230            ("/__next.__PAGE__.txt", None),
231            ("/robots.txt", None),
232        ];
233        for (input, want) in cases {
234            assert_eq!(restore_rsc_dot_path(input).as_deref(), want, "{input}");
235        }
236    }
237
238    #[test]
239    fn placeholder_and_parent() {
240        assert_eq!(
241            placeholder_path("/voddetail/123/index.html").as_deref(),
242            Some("/voddetail/_/index.html")
243        );
244        assert_eq!(placeholder_path("/123/index.html").as_deref(), Some("/_/index.html"));
245        assert_eq!(placeholder_path("/index.html"), None);
246        assert_eq!(drop_last_dir("/app/12345/index.txt").as_deref(), Some("/app/index.txt"));
247        assert_eq!(drop_last_dir("/app/index.txt").as_deref(), Some("/index.txt"));
248        assert_eq!(drop_last_dir("/index.txt"), None);
249    }
250
251    #[test]
252    fn header_classes() {
253        let check = |p: &str| {
254            let mut h = HeaderMap::new();
255            set_headers(&mut h, p);
256            h
257        };
258        let h = check("/about/__next._index.txt");
259        assert_eq!(h[CONTENT_TYPE], "text/x-component; charset=utf-8");
260        assert_eq!(h[VARY], RSC_VARY);
261        assert_eq!(h[CACHE_CONTROL], RSC_CACHE_CONTROL);
262
263        let h = check("/sw.js");
264        assert_eq!(h[CACHE_CONTROL], "no-cache");
265        assert_eq!(h["service-worker-allowed"], "/");
266
267        assert_eq!(
268            check("/manifest.json")[CONTENT_TYPE],
269            "application/manifest+json; charset=utf-8"
270        );
271        assert_eq!(check("/site.webmanifest")[CACHE_CONTROL], "public, max-age=300");
272        assert_eq!(check("/robots.txt")[CACHE_CONTROL], "public, max-age=3600");
273        assert!(check("/robots.txt").get(VARY).is_none());
274        assert_eq!(
275            check("/_NEXT/static/chunk.js")[CACHE_CONTROL],
276            "public, max-age=31536000, immutable"
277        );
278        assert_eq!(check("/ads.txt")[CONTENT_TYPE], "text/plain; charset=utf-8");
279        assert_eq!(check("/logo.PNG")[CACHE_CONTROL], "public, max-age=86400");
280        assert!(check("/app.js").is_empty());
281    }
282}