1mod cache;
52mod paths;
53
54use std::convert::Infallible;
55use std::future::Future;
56use std::io;
57use std::path::{Component, Path, PathBuf};
58use std::pin::Pin;
59use std::sync::{Arc, PoisonError, RwLock};
60use std::task::{Context, Poll};
61
62use bytes::Bytes;
63use http::header::{ALLOW, CACHE_CONTROL, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue, LOCATION, X_CONTENT_TYPE_OPTIONS};
64use http::request::Parts;
65use http::{Method, Request, Response, StatusCode};
66use http_body_util::combinators::UnsyncBoxBody;
67use http_body_util::{BodyExt, Empty, Full};
68use percent_encoding::{AsciiSet, CONTROLS, percent_decode_str, utf8_percent_encode};
69use tower_http::services::ServeFile;
70use tower_service::Service;
71
72use cache::Snapshot;
73pub use paths::{HTML_NO_STORE, RSC_CACHE_CONTROL, RSC_VARY, is_rsc_payload, set_headers};
74
75pub type Body = UnsyncBoxBody<Bytes, io::Error>;
77
78pub type SeoInject = Arc<dyn Fn(&Parts, Bytes) -> Bytes + Send + Sync>;
81
82pub type NotFoundHandler = Arc<dyn Fn(&Parts) -> Response<Bytes> + Send + Sync>;
84
85#[derive(Debug, thiserror::Error)]
87pub enum Error {
88 #[error("nextstatic: root {0:?}: {1}")]
90 Root(PathBuf, #[source] io::Error),
91 #[error("nextstatic: root {0:?} is not a directory")]
93 NotDir(PathBuf),
94 #[error("nextstatic: index root {0:?}: {1}")]
96 Index(PathBuf, #[source] io::Error),
97}
98
99#[derive(Clone, Default)]
101pub struct Config {
102 pub root: PathBuf,
104 pub trailing_slash: bool,
106 pub seo_inject: Option<SeoInject>,
108 pub api_prefixes: Option<Vec<String>>,
110 pub spa_fallback: bool,
112 pub not_found: Option<NotFoundHandler>,
114 pub disable_cache: bool,
116 pub html_cache_max_bytes: i64,
118}
119
120impl Config {
121 pub fn new(root: impl Into<PathBuf>) -> Self {
123 Self {
124 root: root.into(),
125 ..Self::default()
126 }
127 }
128}
129
130impl std::fmt::Debug for Config {
131 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132 f.debug_struct("Config")
133 .field("root", &self.root)
134 .field("trailing_slash", &self.trailing_slash)
135 .field("seo_inject", &self.seo_inject.is_some())
136 .field("api_prefixes", &self.api_prefixes)
137 .field("spa_fallback", &self.spa_fallback)
138 .field("not_found", &self.not_found.is_some())
139 .field("disable_cache", &self.disable_cache)
140 .field("html_cache_max_bytes", &self.html_cache_max_bytes)
141 .finish()
142 }
143}
144
145struct Inner {
146 cfg: Config,
147 api_prefixes: Vec<String>,
148 snap: RwLock<Option<Arc<Snapshot>>>,
150}
151
152#[derive(Clone)]
155pub struct NextStatic {
156 inner: Arc<Inner>,
157}
158
159impl std::fmt::Debug for NextStatic {
160 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161 f.debug_struct("NextStatic")
162 .field("cfg", &self.inner.cfg)
163 .finish_non_exhaustive()
164 }
165}
166
167const PATH_ESCAPE: &AsciiSet = &CONTROLS
169 .add(b' ')
170 .add(b'"')
171 .add(b'#')
172 .add(b'%')
173 .add(b'<')
174 .add(b'>')
175 .add(b'?')
176 .add(b'`')
177 .add(b'{')
178 .add(b'}');
179
180const ROOT_INDEX: &str = "/index.html";
181
182fn full_body(b: impl Into<Bytes>) -> Body {
183 Full::new(b.into()).map_err(|never| match never {}).boxed_unsync()
184}
185
186fn empty_body() -> Body {
187 Empty::new().map_err(|never| match never {}).boxed_unsync()
188}
189
190fn text(status: StatusCode, msg: &str) -> Response<Body> {
192 let mut resp = Response::new(full_body(format!("{msg}\n")));
193 *resp.status_mut() = status;
194 let h = resp.headers_mut();
195 h.insert(CONTENT_TYPE, HeaderValue::from_static("text/plain; charset=utf-8"));
196 h.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
197 resp
198}
199
200impl NextStatic {
201 pub fn new(cfg: Config) -> Result<Self, Error> {
203 let meta = std::fs::metadata(&cfg.root).map_err(|e| Error::Root(cfg.root.clone(), e))?;
204 if !meta.is_dir() {
205 return Err(Error::NotDir(cfg.root.clone()));
206 }
207 let api_prefixes = cfg.api_prefixes.clone().unwrap_or_else(|| vec!["/api/".to_owned()]);
208 let this = Self {
209 inner: Arc::new(Inner {
210 cfg,
211 api_prefixes,
212 snap: RwLock::new(None),
213 }),
214 };
215 this.reload()?;
216 Ok(this)
217 }
218
219 pub fn reload(&self) -> Result<(), Error> {
223 let cfg = &self.inner.cfg;
224 if cfg.disable_cache {
225 return Ok(());
226 }
227 let snap = Snapshot::build(&cfg.root, cfg.html_cache_max_bytes)?;
228 *self.inner.snap.write().unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(snap));
229 Ok(())
230 }
231
232 fn snapshot(&self) -> Option<Arc<Snapshot>> {
233 self.inner.snap.read().unwrap_or_else(PoisonError::into_inner).clone()
234 }
235
236 fn full_path(&self, fs_path: &str) -> Option<PathBuf> {
239 let mut full = self.inner.cfg.root.clone();
240 for seg in fs_path.split('/').filter(|s| !s.is_empty()) {
241 let mut comps = Path::new(seg).components();
242 match (comps.next(), comps.next()) {
243 (Some(Component::Normal(_)), None) => full.push(seg),
244 _ => return None,
245 }
246 }
247 Some(full)
248 }
249
250 async fn exists(&self, fs_path: &str) -> bool {
251 match self.snapshot() {
252 Some(s) => s.contains(fs_path),
253 None => match self.full_path(fs_path) {
254 Some(full) => tokio::fs::metadata(full).await.is_ok_and(|m| m.is_file()),
255 None => false,
256 },
257 }
258 }
259
260 async fn read_html(&self, fs_path: &str) -> io::Result<Bytes> {
261 let full = self
262 .full_path(fs_path)
263 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "path outside export root"))?;
264 let Some(snap) = self.snapshot() else {
265 return tokio::fs::read(&full).await.map(Bytes::from);
266 };
267 if let Some(body) = snap.cached_html(fs_path) {
268 return Ok(body);
269 }
270 let body = Bytes::from(tokio::fs::read(&full).await?);
271 Ok(snap.store_html(fs_path, body))
272 }
273
274 pub async fn handle<B>(&self, req: Request<B>) -> Response<Body> {
278 let (parts, body) = req.into_parts();
279 drop(body); if parts.method != Method::GET && parts.method != Method::HEAD {
282 let mut resp = text(StatusCode::METHOD_NOT_ALLOWED, "method not allowed");
283 resp.headers_mut().insert(ALLOW, HeaderValue::from_static("GET, HEAD"));
284 return resp;
285 }
286
287 let Ok(decoded) = percent_decode_str(parts.uri.path()).decode_utf8() else {
288 return text(StatusCode::BAD_REQUEST, "invalid path");
289 };
290 let p = paths::clean(&format!("/{decoded}"));
292 if p.contains(['\\', '\0']) {
293 return text(StatusCode::BAD_REQUEST, "invalid path");
294 }
295
296 if self
297 .inner
298 .api_prefixes
299 .iter()
300 .any(|pre| !pre.is_empty() && p.starts_with(pre.as_str()))
301 {
302 let mut resp = Response::new(full_body(Bytes::from_static(
303 br#"{"code":404,"data":{},"msg":"not found"}"#,
304 )));
305 *resp.status_mut() = StatusCode::NOT_FOUND;
306 resp.headers_mut().insert(
307 CONTENT_TYPE,
308 HeaderValue::from_static("application/json; charset=utf-8"),
309 );
310 return resp;
311 }
312
313 if p == "/" {
314 return self.serve_html(&parts, ROOT_INDEX, StatusCode::OK).await;
315 }
316 if !paths::ext(&p).is_empty() {
317 return self.serve_asset(&parts, &p).await;
318 }
319 self.serve_page(&parts, &p, decoded.ends_with('/')).await
320 }
321
322 async fn serve_asset(&self, parts: &Parts, p: &str) -> Response<Body> {
325 if paths::ext(p).eq_ignore_ascii_case(".html") && self.exists(p).await {
326 return self.serve_html(parts, p, StatusCode::OK).await;
327 }
328 if let Some(resp) = self.try_serve_file(parts, p, p).await {
329 return resp;
330 }
331 if let Some(restored) = paths::restore_rsc_dot_path(p)
332 && let Some(resp) = self.try_serve_file(parts, &restored, p).await
333 {
334 return resp;
335 }
336 if is_rsc_payload(p) {
337 if let Some(alt) = paths::placeholder_path(p) {
339 if let Some(resp) = self.try_serve_file(parts, &alt, p).await {
340 return resp;
341 }
342 if let Some(restored) = paths::restore_rsc_dot_path(&alt)
343 && let Some(resp) = self.try_serve_file(parts, &restored, p).await
344 {
345 return resp;
346 }
347 }
348 if let Some(parent) = paths::drop_last_dir(p)
350 && let Some(resp) = self.try_serve_file(parts, &parent, p).await
351 {
352 return resp;
353 }
354 }
355 self.not_found_asset(parts)
356 }
357
358 async fn serve_page(&self, parts: &Parts, p: &str, has_trailing_slash: bool) -> Response<Body> {
361 if self.inner.cfg.trailing_slash && !has_trailing_slash {
362 let mut loc = utf8_percent_encode(&format!("{p}/"), PATH_ESCAPE).to_string();
364 if let Some(q) = parts.uri.query() {
365 loc.push('?');
366 loc.push_str(q);
367 }
368 let mut resp = Response::new(empty_body());
369 *resp.status_mut() = StatusCode::PERMANENT_REDIRECT;
370 if let Ok(v) = HeaderValue::from_str(&loc) {
371 resp.headers_mut().insert(LOCATION, v);
372 }
373 return resp;
374 }
375
376 let index = paths::join(p, "index.html");
377 if let Some(resp) = self.try_serve_html(parts, &index).await {
378 return resp;
379 }
380 if let Some(resp) = self.try_serve_html(parts, &format!("{p}.html")).await {
382 return resp;
383 }
384 if let Some(alt) = paths::placeholder_path(&index)
386 && let Some(resp) = self.try_serve_html(parts, &alt).await
387 {
388 return resp;
389 }
390 let mut dir = paths::dir(p);
392 while dir != "/" {
393 if let Some(resp) = self.try_serve_html(parts, &paths::join(dir, "index.html")).await {
394 return resp;
395 }
396 dir = paths::dir(dir);
397 }
398 self.not_found_page(parts).await
399 }
400
401 async fn try_serve_file(&self, parts: &Parts, fs_path: &str, header_path: &str) -> Option<Response<Body>> {
403 if !self.exists(fs_path).await {
404 return None;
405 }
406 let full = self.full_path(fs_path)?;
407 let req = Request::from_parts(parts.clone(), ());
408 let resp = match ServeFile::new(full).try_call(req).await {
409 Ok(resp) => resp.map(BodyExt::boxed_unsync),
410 Err(_) => return Some(text(StatusCode::INTERNAL_SERVER_ERROR, "internal error")),
411 };
412 if resp.status() == StatusCode::NOT_FOUND {
413 return None; }
415 let mut resp = resp;
416 set_headers(resp.headers_mut(), header_path);
417 Some(resp)
418 }
419
420 async fn try_serve_html(&self, parts: &Parts, fs_path: &str) -> Option<Response<Body>> {
421 if !self.exists(fs_path).await {
422 return None;
423 }
424 Some(self.serve_html(parts, fs_path, StatusCode::OK).await)
425 }
426
427 async fn serve_html(&self, parts: &Parts, fs_path: &str, status: StatusCode) -> Response<Body> {
429 let Ok(mut body) = self.read_html(fs_path).await else {
430 return self.not_found_asset(parts);
431 };
432 if let Some(inject) = &self.inner.cfg.seo_inject {
433 body = inject(parts, body);
434 }
435 let len = body.len();
436 let mut resp = Response::new(if parts.method == Method::HEAD {
437 empty_body()
438 } else {
439 full_body(body)
440 });
441 *resp.status_mut() = status;
442 let h = resp.headers_mut();
443 h.insert(CONTENT_LENGTH, HeaderValue::from(len));
445 h.insert(CONTENT_TYPE, HeaderValue::from_static("text/html; charset=utf-8"));
446 h.insert(CACHE_CONTROL, HeaderValue::from_static(HTML_NO_STORE));
447 resp
448 }
449
450 fn custom_not_found(&self, parts: &Parts) -> Option<Response<Body>> {
451 self.inner.cfg.not_found.as_ref().map(|f| f(parts).map(full_body))
452 }
453
454 fn not_found_asset(&self, parts: &Parts) -> Response<Body> {
457 let mut resp = self
458 .custom_not_found(parts)
459 .unwrap_or_else(|| text(StatusCode::NOT_FOUND, "404 page not found"));
460 resp.headers_mut()
461 .entry(CACHE_CONTROL)
462 .or_insert(HeaderValue::from_static("no-store"));
463 resp
464 }
465
466 async fn not_found_page(&self, parts: &Parts) -> Response<Body> {
469 if let Some(resp) = self.custom_not_found(parts) {
470 return resp;
471 }
472 if self.inner.cfg.spa_fallback && self.exists(ROOT_INDEX).await {
473 return self.serve_html(parts, ROOT_INDEX, StatusCode::OK).await;
474 }
475 if self.exists("/404.html").await {
476 return self.serve_html(parts, "/404.html", StatusCode::NOT_FOUND).await;
477 }
478 if self.exists(ROOT_INDEX).await {
479 return self.serve_html(parts, ROOT_INDEX, StatusCode::NOT_FOUND).await;
480 }
481 text(StatusCode::NOT_FOUND, "404 page not found")
482 }
483
484 pub fn root(&self) -> &Path {
486 &self.inner.cfg.root
487 }
488}
489
490impl<B: Send + 'static> Service<Request<B>> for NextStatic {
491 type Response = Response<Body>;
492 type Error = Infallible;
493 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
494
495 fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
496 Poll::Ready(Ok(()))
497 }
498
499 fn call(&mut self, req: Request<B>) -> Self::Future {
500 let this = self.clone();
501 Box::pin(async move { Ok(this.handle(req).await) })
502 }
503}