mod cache;
mod paths;
use std::convert::Infallible;
use std::future::Future;
use std::io;
use std::path::{Component, Path, PathBuf};
use std::pin::Pin;
use std::sync::{Arc, PoisonError, RwLock};
use std::task::{Context, Poll};
use bytes::Bytes;
use http::header::{ALLOW, CACHE_CONTROL, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue, LOCATION, X_CONTENT_TYPE_OPTIONS};
use http::request::Parts;
use http::{Method, Request, Response, StatusCode};
use http_body_util::combinators::UnsyncBoxBody;
use http_body_util::{BodyExt, Empty, Full};
use percent_encoding::{AsciiSet, CONTROLS, percent_decode_str, utf8_percent_encode};
use tower_http::services::ServeFile;
use tower_service::Service;
use cache::Snapshot;
pub use paths::{HTML_NO_STORE, RSC_CACHE_CONTROL, RSC_VARY, is_rsc_payload, set_headers};
pub type Body = UnsyncBoxBody<Bytes, io::Error>;
pub type SeoInject = Arc<dyn Fn(&Parts, Bytes) -> Bytes + Send + Sync>;
pub type NotFoundHandler = Arc<dyn Fn(&Parts) -> Response<Bytes> + Send + Sync>;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("nextstatic: root {0:?}: {1}")]
Root(PathBuf, #[source] io::Error),
#[error("nextstatic: root {0:?} is not a directory")]
NotDir(PathBuf),
#[error("nextstatic: index root {0:?}: {1}")]
Index(PathBuf, #[source] io::Error),
}
#[derive(Clone, Default)]
pub struct Config {
pub root: PathBuf,
pub trailing_slash: bool,
pub seo_inject: Option<SeoInject>,
pub api_prefixes: Option<Vec<String>>,
pub spa_fallback: bool,
pub not_found: Option<NotFoundHandler>,
pub disable_cache: bool,
pub html_cache_max_bytes: i64,
}
impl Config {
pub fn new(root: impl Into<PathBuf>) -> Self {
Self {
root: root.into(),
..Self::default()
}
}
}
impl std::fmt::Debug for Config {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Config")
.field("root", &self.root)
.field("trailing_slash", &self.trailing_slash)
.field("seo_inject", &self.seo_inject.is_some())
.field("api_prefixes", &self.api_prefixes)
.field("spa_fallback", &self.spa_fallback)
.field("not_found", &self.not_found.is_some())
.field("disable_cache", &self.disable_cache)
.field("html_cache_max_bytes", &self.html_cache_max_bytes)
.finish()
}
}
struct Inner {
cfg: Config,
api_prefixes: Vec<String>,
snap: RwLock<Option<Arc<Snapshot>>>,
}
#[derive(Clone)]
pub struct NextStatic {
inner: Arc<Inner>,
}
impl std::fmt::Debug for NextStatic {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("NextStatic")
.field("cfg", &self.inner.cfg)
.finish_non_exhaustive()
}
}
const PATH_ESCAPE: &AsciiSet = &CONTROLS
.add(b' ')
.add(b'"')
.add(b'#')
.add(b'%')
.add(b'<')
.add(b'>')
.add(b'?')
.add(b'`')
.add(b'{')
.add(b'}');
const ROOT_INDEX: &str = "/index.html";
fn full_body(b: impl Into<Bytes>) -> Body {
Full::new(b.into()).map_err(|never| match never {}).boxed_unsync()
}
fn empty_body() -> Body {
Empty::new().map_err(|never| match never {}).boxed_unsync()
}
fn text(status: StatusCode, msg: &str) -> Response<Body> {
let mut resp = Response::new(full_body(format!("{msg}\n")));
*resp.status_mut() = status;
let h = resp.headers_mut();
h.insert(CONTENT_TYPE, HeaderValue::from_static("text/plain; charset=utf-8"));
h.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
resp
}
impl NextStatic {
pub fn new(cfg: Config) -> Result<Self, Error> {
let meta = std::fs::metadata(&cfg.root).map_err(|e| Error::Root(cfg.root.clone(), e))?;
if !meta.is_dir() {
return Err(Error::NotDir(cfg.root.clone()));
}
let api_prefixes = cfg.api_prefixes.clone().unwrap_or_else(|| vec!["/api/".to_owned()]);
let this = Self {
inner: Arc::new(Inner {
cfg,
api_prefixes,
snap: RwLock::new(None),
}),
};
this.reload()?;
Ok(this)
}
pub fn reload(&self) -> Result<(), Error> {
let cfg = &self.inner.cfg;
if cfg.disable_cache {
return Ok(());
}
let snap = Snapshot::build(&cfg.root, cfg.html_cache_max_bytes)?;
*self.inner.snap.write().unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(snap));
Ok(())
}
fn snapshot(&self) -> Option<Arc<Snapshot>> {
self.inner.snap.read().unwrap_or_else(PoisonError::into_inner).clone()
}
fn full_path(&self, fs_path: &str) -> Option<PathBuf> {
let mut full = self.inner.cfg.root.clone();
for seg in fs_path.split('/').filter(|s| !s.is_empty()) {
let mut comps = Path::new(seg).components();
match (comps.next(), comps.next()) {
(Some(Component::Normal(_)), None) => full.push(seg),
_ => return None,
}
}
Some(full)
}
async fn exists(&self, fs_path: &str) -> bool {
match self.snapshot() {
Some(s) => s.contains(fs_path),
None => match self.full_path(fs_path) {
Some(full) => tokio::fs::metadata(full).await.is_ok_and(|m| m.is_file()),
None => false,
},
}
}
async fn read_html(&self, fs_path: &str) -> io::Result<Bytes> {
let full = self
.full_path(fs_path)
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "path outside export root"))?;
let Some(snap) = self.snapshot() else {
return tokio::fs::read(&full).await.map(Bytes::from);
};
if let Some(body) = snap.cached_html(fs_path) {
return Ok(body);
}
let body = Bytes::from(tokio::fs::read(&full).await?);
Ok(snap.store_html(fs_path, body))
}
pub async fn handle<B>(&self, req: Request<B>) -> Response<Body> {
let (parts, body) = req.into_parts();
drop(body);
if parts.method != Method::GET && parts.method != Method::HEAD {
let mut resp = text(StatusCode::METHOD_NOT_ALLOWED, "method not allowed");
resp.headers_mut().insert(ALLOW, HeaderValue::from_static("GET, HEAD"));
return resp;
}
let Ok(decoded) = percent_decode_str(parts.uri.path()).decode_utf8() else {
return text(StatusCode::BAD_REQUEST, "invalid path");
};
let p = paths::clean(&format!("/{decoded}"));
if p.contains(['\\', '\0']) {
return text(StatusCode::BAD_REQUEST, "invalid path");
}
if self
.inner
.api_prefixes
.iter()
.any(|pre| !pre.is_empty() && p.starts_with(pre.as_str()))
{
let mut resp = Response::new(full_body(Bytes::from_static(
br#"{"code":404,"data":{},"msg":"not found"}"#,
)));
*resp.status_mut() = StatusCode::NOT_FOUND;
resp.headers_mut().insert(
CONTENT_TYPE,
HeaderValue::from_static("application/json; charset=utf-8"),
);
return resp;
}
if p == "/" {
return self.serve_html(&parts, ROOT_INDEX, StatusCode::OK).await;
}
if !paths::ext(&p).is_empty() {
return self.serve_asset(&parts, &p).await;
}
self.serve_page(&parts, &p, decoded.ends_with('/')).await
}
async fn serve_asset(&self, parts: &Parts, p: &str) -> Response<Body> {
if paths::ext(p).eq_ignore_ascii_case(".html") && self.exists(p).await {
return self.serve_html(parts, p, StatusCode::OK).await;
}
if let Some(resp) = self.try_serve_file(parts, p, p).await {
return resp;
}
if let Some(restored) = paths::restore_rsc_dot_path(p)
&& let Some(resp) = self.try_serve_file(parts, &restored, p).await
{
return resp;
}
if is_rsc_payload(p) {
if let Some(alt) = paths::placeholder_path(p) {
if let Some(resp) = self.try_serve_file(parts, &alt, p).await {
return resp;
}
if let Some(restored) = paths::restore_rsc_dot_path(&alt)
&& let Some(resp) = self.try_serve_file(parts, &restored, p).await
{
return resp;
}
}
if let Some(parent) = paths::drop_last_dir(p)
&& let Some(resp) = self.try_serve_file(parts, &parent, p).await
{
return resp;
}
}
self.not_found_asset(parts)
}
async fn serve_page(&self, parts: &Parts, p: &str, has_trailing_slash: bool) -> Response<Body> {
if self.inner.cfg.trailing_slash && !has_trailing_slash {
let mut loc = utf8_percent_encode(&format!("{p}/"), PATH_ESCAPE).to_string();
if let Some(q) = parts.uri.query() {
loc.push('?');
loc.push_str(q);
}
let mut resp = Response::new(empty_body());
*resp.status_mut() = StatusCode::PERMANENT_REDIRECT;
if let Ok(v) = HeaderValue::from_str(&loc) {
resp.headers_mut().insert(LOCATION, v);
}
return resp;
}
let index = paths::join(p, "index.html");
if let Some(resp) = self.try_serve_html(parts, &index).await {
return resp;
}
if let Some(resp) = self.try_serve_html(parts, &format!("{p}.html")).await {
return resp;
}
if let Some(alt) = paths::placeholder_path(&index)
&& let Some(resp) = self.try_serve_html(parts, &alt).await
{
return resp;
}
let mut dir = paths::dir(p);
while dir != "/" {
if let Some(resp) = self.try_serve_html(parts, &paths::join(dir, "index.html")).await {
return resp;
}
dir = paths::dir(dir);
}
self.not_found_page(parts).await
}
async fn try_serve_file(&self, parts: &Parts, fs_path: &str, header_path: &str) -> Option<Response<Body>> {
if !self.exists(fs_path).await {
return None;
}
let full = self.full_path(fs_path)?;
let req = Request::from_parts(parts.clone(), ());
let resp = match ServeFile::new(full).try_call(req).await {
Ok(resp) => resp.map(BodyExt::boxed_unsync),
Err(_) => return Some(text(StatusCode::INTERNAL_SERVER_ERROR, "internal error")),
};
if resp.status() == StatusCode::NOT_FOUND {
return None; }
let mut resp = resp;
set_headers(resp.headers_mut(), header_path);
Some(resp)
}
async fn try_serve_html(&self, parts: &Parts, fs_path: &str) -> Option<Response<Body>> {
if !self.exists(fs_path).await {
return None;
}
Some(self.serve_html(parts, fs_path, StatusCode::OK).await)
}
async fn serve_html(&self, parts: &Parts, fs_path: &str, status: StatusCode) -> Response<Body> {
let Ok(mut body) = self.read_html(fs_path).await else {
return self.not_found_asset(parts);
};
if let Some(inject) = &self.inner.cfg.seo_inject {
body = inject(parts, body);
}
let len = body.len();
let mut resp = Response::new(if parts.method == Method::HEAD {
empty_body()
} else {
full_body(body)
});
*resp.status_mut() = status;
let h = resp.headers_mut();
h.insert(CONTENT_LENGTH, HeaderValue::from(len));
h.insert(CONTENT_TYPE, HeaderValue::from_static("text/html; charset=utf-8"));
h.insert(CACHE_CONTROL, HeaderValue::from_static(HTML_NO_STORE));
resp
}
fn custom_not_found(&self, parts: &Parts) -> Option<Response<Body>> {
self.inner.cfg.not_found.as_ref().map(|f| f(parts).map(full_body))
}
fn not_found_asset(&self, parts: &Parts) -> Response<Body> {
let mut resp = self
.custom_not_found(parts)
.unwrap_or_else(|| text(StatusCode::NOT_FOUND, "404 page not found"));
resp.headers_mut()
.entry(CACHE_CONTROL)
.or_insert(HeaderValue::from_static("no-store"));
resp
}
async fn not_found_page(&self, parts: &Parts) -> Response<Body> {
if let Some(resp) = self.custom_not_found(parts) {
return resp;
}
if self.inner.cfg.spa_fallback && self.exists(ROOT_INDEX).await {
return self.serve_html(parts, ROOT_INDEX, StatusCode::OK).await;
}
if self.exists("/404.html").await {
return self.serve_html(parts, "/404.html", StatusCode::NOT_FOUND).await;
}
if self.exists(ROOT_INDEX).await {
return self.serve_html(parts, ROOT_INDEX, StatusCode::NOT_FOUND).await;
}
text(StatusCode::NOT_FOUND, "404 page not found")
}
pub fn root(&self) -> &Path {
&self.inner.cfg.root
}
}
impl<B: Send + 'static> Service<Request<B>> for NextStatic {
type Response = Response<Body>;
type Error = Infallible;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: Request<B>) -> Self::Future {
let this = self.clone();
Box::pin(async move { Ok(this.handle(req).await) })
}
}