1use http::HeaderMap;
4use http::header::{CACHE_CONTROL, CONTENT_TYPE, HeaderValue, VARY};
5
6pub const RSC_VARY: &str = "RSC, Next-Router-State-Tree, Next-Router-Prefetch";
8
9pub const RSC_CACHE_CONTROL: &str = "public, max-age=60, stale-while-revalidate=300";
11
12pub const HTML_NO_STORE: &str = "no-store, no-cache, must-revalidate, max-age=0";
14
15pub(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
39pub(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
45pub(crate) fn dir(p: &str) -> &str {
47 match p.rfind('/') {
48 Some(0) | None => "/",
49 Some(i) => &p[..i],
50 }
51}
52
53pub(crate) fn join(dir: &str, name: &str) -> String {
55 if dir == "/" {
56 format!("/{name}")
57 } else {
58 format!("{dir}/{name}")
59 }
60}
61
62pub 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
78pub 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 set(headers, CACHE_CONTROL, RSC_CACHE_CONTROL);
88 } else if lower == "/sw.js" {
89 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
115pub(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 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
143fn 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
153pub(crate) fn placeholder_path(p: &str) -> Option<String> {
156 split_last_dir(p).map(|(parent, base)| join(&join(parent, "_"), base))
157}
158
159pub(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}