use axum::{
Json,
extract::{FromRef, FromRequestParts},
http::{
HeaderMap, StatusCode,
header::{LOCATION, REFERER, VARY},
request::Parts,
},
response::{Html, IntoResponse, Response},
};
use serde_json::{Value, json};
use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
sync::Arc,
};
use tower_sessions::Session;
pub struct Config {
version: String,
head: String,
title: String,
}
pub type InertiaConfig = Arc<Config>;
impl Config {
pub fn dev(port: u16, entry: &str, react: bool, title: &str) -> InertiaConfig {
let o = format!("http://localhost:{port}");
let preamble = if react {
format!(
r#"<script type="module">import R from "{o}/@react-refresh";R.injectIntoGlobalHook(window);window.$RefreshReg$=()=>{{}};window.$RefreshSig$=()=>t=>t;window.__vite_plugin_react_preamble_installed__=true;</script>"#
)
} else {
String::new()
};
let head = format!(
r#"{preamble}<script type="module" src="{o}/@vite/client"></script><script type="module" src="{o}/{entry}"></script>"#
);
Self::new("dev".into(), head, title)
}
pub fn prod(manifest: &str, entry: &str, title: &str) -> Result<InertiaConfig, String> {
let raw = std::fs::read_to_string(manifest).map_err(|e| format!("{manifest}: {e}"))?;
let m: Value = serde_json::from_str(&raw).map_err(|e| e.to_string())?;
let e = m.get(entry).ok_or(format!("{entry} not in manifest"))?;
let mut head = String::new();
for css in e["css"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
{
head += &format!(r#"<link rel="stylesheet" href="/{}">"#, escape(css));
}
let js = e["file"].as_str().ok_or("manifest entry has no file")?;
head += &format!(r#"<script type="module" src="/{}"></script>"#, escape(js));
let mut h = DefaultHasher::new();
raw.hash(&mut h);
Ok(Self::new(format!("{:x}", h.finish()), head, title))
}
pub fn from_env(title: &str) -> InertiaConfig {
let entry = std::env::var("VITE_ENTRY").unwrap_or_else(|_| "src/main.js".into());
if std::env::var("APP_ENV").is_ok_and(|e| e == "production") {
return Self::prod("client/dist/.vite/manifest.json", &entry, title)
.expect("inertia manifest");
}
let port = std::env::var("VITE_PORT")
.ok()
.and_then(|p| p.parse().ok())
.unwrap_or(5173);
Self::dev(port, &entry, false, title)
}
fn new(version: String, head: String, title: &str) -> InertiaConfig {
Arc::new(Config {
version,
head,
title: escape(title),
})
}
}
pub fn with_head(cfg: InertiaConfig, html: &str) -> InertiaConfig {
Arc::new(Config {
version: cfg.version.clone(),
head: format!("{}{html}", cfg.head),
title: cfg.title.clone(),
})
}
pub struct Inertia {
cfg: InertiaConfig,
headers: HeaderMap,
url: String,
shared: serde_json::Map<String, Value>,
flash: Value,
errors: Value,
}
impl<S> FromRequestParts<S> for Inertia
where
S: Send + Sync,
InertiaConfig: FromRef<S>,
{
type Rejection = (StatusCode, &'static str);
async fn from_request_parts(p: &mut Parts, s: &S) -> Result<Self, Self::Rejection> {
let session = Session::from_request_parts(p, s).await?;
let flash = session
.remove::<Value>("flash")
.await
.ok()
.flatten()
.unwrap_or_else(|| json!({}));
let errors = session
.remove::<Value>("errors")
.await
.ok()
.flatten()
.unwrap_or_else(|| json!({}));
let uid = session.get::<i64>("user_id").await.ok().flatten();
let auth = json!({ "user": uid.map(|id| json!({ "id": id })) });
Ok(Inertia {
shared: std::iter::once(("auth".to_string(), auth)).collect(),
flash,
errors,
cfg: InertiaConfig::from_ref(s),
headers: p.headers.clone(),
url: p.uri.path_and_query().map_or("/", |x| x.as_str()).into(),
})
}
}
impl Inertia {
fn header(&self, k: &str) -> Option<&str> {
self.headers.get(k)?.to_str().ok()
}
pub fn with(mut self, key: &str, value: Value) -> Self {
self.shared.insert(key.into(), value);
self
}
pub fn render(self, component: &str, mut props: Value) -> Response {
let is_inertia = self.header("x-inertia").is_some();
if is_inertia
&& self
.header("x-inertia-version")
.is_some_and(|v| v != self.cfg.version)
{
return (StatusCode::CONFLICT, [("x-inertia-location", self.url)]).into_response();
}
if let Value::Object(m) = &mut props {
for (k, v) in &self.shared {
m.entry(k).or_insert(v.clone());
}
m.entry("flash").or_insert(self.flash.clone());
m.entry("errors").or_insert(self.errors.clone());
}
if self.header("x-inertia-partial-component") == Some(component)
&& let Some(only) = self.header("x-inertia-partial-data")
{
partial(&mut props, only);
}
let page = json!({
"component": component, "props": props,
"url": self.url, "version": self.cfg.version,
});
if is_inertia {
return (
[
("x-inertia", "true"),
(VARY.as_str(), "X-Inertia"),
("cache-control", "no-store"),
],
Json(page),
)
.into_response();
}
let c = &self.cfg;
([("cache-control", "no-store")], Html(format!(
r#"<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{}</title>{}</head><body><div id="app" data-page="{}"></div></body></html>"#,
c.title, c.head, escape(&page.to_string())
)))
.into_response()
}
}
pub fn redirect(to: &str) -> Response {
(StatusCode::SEE_OTHER, [(LOCATION, to)]).into_response()
}
pub fn redirect_back(headers: &HeaderMap) -> Response {
let path = headers
.get(REFERER)
.and_then(|v| v.to_str().ok())
.and_then(|r| r.parse::<axum::http::Uri>().ok())
.and_then(|u| u.path_and_query().map(|p| p.to_string()))
.filter(|p| !p.starts_with("//") && !p.contains(['\\']) && !p.chars().any(char::is_control))
.unwrap_or_else(|| "/".into());
redirect(&path)
}
pub async fn flash(session: &Session, key: &str, msg: impl Into<String>) {
let mut m = session
.get::<Value>("flash")
.await
.ok()
.flatten()
.unwrap_or_else(|| json!({}));
m[key] = Value::String(msg.into());
let _ = session.insert("flash", m).await;
}
pub async fn flash_errors(session: &Session, errors: std::collections::BTreeMap<String, String>) {
let _ = session.insert("errors", errors).await;
}
fn partial(props: &mut Value, only: &str) {
if let Value::Object(m) = props {
let keep: Vec<&str> = only.split(',').map(str::trim).collect();
m.retain(|k, _| keep.contains(&k.as_str()));
}
}
fn escape(s: &str) -> String {
s.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
.replace('\'', "'")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escapes_and_filters() {
assert_eq!(
escape(r#"<a href="x">&'"#),
"<a href="x">&'"
);
let mut p = json!({"a": 1, "b": 2, "c": 3});
partial(&mut p, "a, c");
assert_eq!(p, json!({"a": 1, "c": 3}));
}
#[test]
fn redirect_back_uses_referer_path() {
let loc = |r: Response| r.headers()[LOCATION].to_str().unwrap().to_string();
let mut h = HeaderMap::new();
assert_eq!(loc(redirect_back(&h)), "/");
h.insert(REFERER, "http://evil.com/posts/new?a=1".parse().unwrap());
let r = redirect_back(&h);
assert_eq!(r.status(), StatusCode::SEE_OTHER);
assert_eq!(loc(r), "/posts/new?a=1");
for bad in [
"https://x//attacker.test/p",
"https://x/\\attacker.test",
"https://x/a\\b",
] {
h.insert(REFERER, bad.parse().unwrap());
assert_eq!(loc(redirect_back(&h)), "/", "{bad}");
}
}
#[tokio::test]
async fn pages_are_no_store() {
use axum::{Router, body::Body, http::Request, routing::get};
use tower::ServiceExt;
use tower_sessions::{MemoryStore, SessionManagerLayer};
async fn page(i: Inertia) -> Response {
i.render("C", json!({}))
}
let app = Router::new()
.route("/", get(page))
.with_state(Config::dev(5173, "src/main.js", false, "t"))
.layer(SessionManagerLayer::new(MemoryStore::default()));
for x in [false, true] {
let mut r = Request::get("/");
if x {
r = r.header("x-inertia", "true");
}
let r = app
.clone()
.oneshot(r.body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(r.headers()["cache-control"], "no-store", "inertia={x}");
}
}
#[tokio::test]
async fn flash_errors_round_trip_once() {
use axum::{Router, body::Body, http::Request, routing::get};
use tower::ServiceExt;
use tower_sessions::{MemoryStore, SessionManagerLayer};
async fn set(s: Session) {
flash(&s, "success", "ok").await;
flash_errors(&s, [("email".to_string(), "bad".to_string())].into()).await;
}
async fn show(i: Inertia) -> Response {
i.with("x", json!(1)).render("C", json!({}))
}
let app = Router::new()
.route("/set", get(set))
.route("/show", get(show))
.with_state(Config::dev(5173, "src/main.js", false, "t"))
.layer(SessionManagerLayer::new(MemoryStore::default()));
let req = |uri: &str, cookie: &str| {
Request::get(uri)
.header("x-inertia", "true")
.header("cookie", cookie)
.body(Body::empty())
.unwrap()
};
let r = app.clone().oneshot(req("/set", "")).await.unwrap();
let cookie = r.headers()["set-cookie"]
.to_str()
.unwrap()
.split(';')
.next()
.unwrap()
.to_string();
let mut seen = vec![];
for _ in 0..2 {
let r = app.clone().oneshot(req("/show", &cookie)).await.unwrap();
let b = axum::body::to_bytes(r.into_body(), usize::MAX)
.await
.unwrap();
seen.push(serde_json::from_slice::<Value>(&b).unwrap()["props"].clone());
}
assert_eq!(
seen[0],
json!({"x":1,"auth":{"user":null},"flash":{"success":"ok"},"errors":{"email":"bad"}})
);
assert_eq!(
seen[1],
json!({"x":1,"auth":{"user":null},"flash":{},"errors":{}})
);
}
#[tokio::test]
async fn with_head_is_rendered_in_head() {
use axum::{Router, body::Body, http::Request, routing::get};
use tower::ServiceExt;
use tower_sessions::{MemoryStore, SessionManagerLayer};
async fn page(i: Inertia) -> Response {
i.render("C", json!({}))
}
let cfg = with_head(
Config::dev(5173, "src/main.js", false, "t"),
"<script>THEME</script>",
);
let app = Router::new()
.route("/", get(page))
.with_state(cfg)
.layer(SessionManagerLayer::new(MemoryStore::default()));
let r = app
.oneshot(Request::get("/").body(Body::empty()).unwrap())
.await
.unwrap();
let html = String::from_utf8(
axum::body::to_bytes(r.into_body(), usize::MAX)
.await
.unwrap()
.to_vec(),
)
.unwrap();
let head = &html[html.find("<head>").unwrap()..html.find("</head>").unwrap()];
assert!(
head.contains("<script>THEME</script>") && head.contains("@vite/client"),
"{head}"
);
}
}