use std::{
env,
future::Future,
pin::Pin,
sync::Arc,
task::{ready, Context, Poll},
};
use axum::{
body::Body,
http::{
header::{CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_SECURITY_POLICY, CONTENT_TYPE},
HeaderMap, Method, Request, Response,
},
};
use bytes::{BufMut, Bytes, BytesMut};
use hyper::body::{Body as HttpBody, Frame, SizeHint};
use tower::{Layer, Service};
pub const RELOAD_PORT_ENV: &str = "PROA_DEV_RELOAD_PORT";
pub const RELOAD_TOKEN_ENV: &str = "PROA_DEV_RELOAD_TOKEN";
const DEV_EVENTS_PATH: &str = "/__proa/dev-events";
const HEAD_CLOSE: &[u8] = b"</head";
const TOKEN_BYTES: usize = 16;
const CLIENT_JS: &str = include_str!("dev_reload_client.js");
pub fn layer_from_env() -> Option<DevReloadLayer> {
let port = env::var(RELOAD_PORT_ENV).ok()?;
let Some(port) = parse_reload_port(&port) else {
tracing::warn!(
value = %port,
"{RELOAD_PORT_ENV} is not a port number; live reload stays off"
);
return None;
};
let token = env::var(RELOAD_TOKEN_ENV).unwrap_or_default();
let Some(token) = parse_reload_token(&token) else {
tracing::warn!(
"{RELOAD_PORT_ENV} is set without a valid {RELOAD_TOKEN_ENV}; live reload stays off"
);
return None;
};
Some(DevReloadLayer::new(port, token))
}
fn parse_reload_port(value: &str) -> Option<u16> {
match value.trim().parse::<u16>() {
Ok(0) | Err(_) => None,
Ok(port) => Some(port),
}
}
fn parse_reload_token(value: &str) -> Option<&str> {
let token = value.trim();
let expected = TOKEN_BYTES * 2;
(token.len() == expected
&& token
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)))
.then_some(token)
}
#[derive(Debug, Clone)]
pub struct DevReloadLayer {
script: Arc<str>,
connect_source: Arc<str>,
}
impl DevReloadLayer {
pub fn new(port: u16, token: &str) -> Self {
let script = CLIENT_JS
.replace("__PROA_DEV_RELOAD_PORT__", &port.to_string())
.replace("__PROA_DEV_EVENTS_PATH__", DEV_EVENTS_PATH)
.replace(
"__PROA_DEV_RELOAD_TOKEN__",
parse_reload_token(token).unwrap_or_default(),
);
Self {
script: Arc::from(script),
connect_source: Arc::from(format!("http://*:{port}")),
}
}
fn tag(&self, nonce: Option<&str>) -> Bytes {
let mut tag = BytesMut::with_capacity(self.script.len() + 64);
tag.put_slice(b"<script");
if let Some(nonce) = nonce {
tag.put_slice(b" nonce=\"");
tag.put_slice(nonce.as_bytes());
tag.put_slice(b"\"");
}
tag.put_slice(b">");
tag.put_slice(self.script.as_bytes());
tag.put_slice(b"</script>");
tag.freeze()
}
}
impl<S> Layer<S> for DevReloadLayer {
type Service = DevReload<S>;
fn layer(&self, inner: S) -> Self::Service {
DevReload {
inner,
layer: self.clone(),
}
}
}
#[derive(Debug, Clone)]
pub struct DevReload<S> {
inner: S,
layer: DevReloadLayer,
}
impl<S, B> Service<Request<B>> for DevReload<S>
where
S: Service<Request<B>, Response = Response<Body>>,
{
type Response = Response<Body>;
type Error = S::Error;
type Future = DevReloadFuture<S::Future>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request<B>) -> Self::Future {
let skip = is_embedded_destination(request.headers()) || request.method() == Method::HEAD;
DevReloadFuture {
inner: self.inner.call(request),
layer: self.layer.clone(),
skip,
}
}
}
fn is_embedded_destination(headers: &HeaderMap) -> bool {
headers
.get("sec-fetch-dest")
.and_then(|value| value.to_str().ok())
.is_some_and(|value| {
matches!(
value.trim(),
"iframe" | "frame" | "embed" | "object" | "fencedframe"
)
})
}
#[pin_project::pin_project]
#[derive(Debug)]
pub struct DevReloadFuture<F> {
#[pin]
inner: F,
layer: DevReloadLayer,
skip: bool,
}
impl<F, E> Future for DevReloadFuture<F>
where
F: Future<Output = Result<Response<Body>, E>>,
{
type Output = Result<Response<Body>, E>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
let response = ready!(this.inner.poll(cx))?;
if *this.skip {
return Poll::Ready(Ok(response));
}
Poll::Ready(Ok(inject(response, this.layer)))
}
}
fn inject(mut response: Response<Body>, layer: &DevReloadLayer) -> Response<Body> {
if !accepts_injection(response.headers()) {
return response;
}
let nonce = script_nonce(response.headers());
let tag = layer.tag(nonce.as_deref());
if let Some(policy) = allow_connect_source(response.headers(), &layer.connect_source) {
if let Ok(value) = policy.parse() {
response
.headers_mut()
.insert(CONTENT_SECURITY_POLICY, value);
}
}
response.headers_mut().remove(CONTENT_LENGTH);
response.map(|body| Body::new(InjectBody::new(body, tag)))
}
fn accepts_injection(headers: &HeaderMap) -> bool {
let is_html = headers
.get(CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.is_some_and(|value| {
value
.split(';')
.next()
.is_some_and(|mime| mime.trim().eq_ignore_ascii_case("text/html"))
});
let is_identity = headers
.get(CONTENT_ENCODING)
.and_then(|value| value.to_str().ok())
.is_none_or(|value| value.trim().eq_ignore_ascii_case("identity"));
is_html && is_identity
}
fn allow_connect_source(headers: &HeaderMap, source: &str) -> Option<String> {
let policy = headers.get(CONTENT_SECURITY_POLICY)?.to_str().ok()?;
let mut directives: Vec<String> = Vec::new();
let mut widened = false;
let mut default_src = None;
for directive in policy.split(';') {
let trimmed = directive.trim();
if trimmed.is_empty() {
continue;
}
let name = trimmed.split_whitespace().next().unwrap_or_default();
if name.eq_ignore_ascii_case("connect-src") {
directives.push(format!("{trimmed} {source}"));
widened = true;
} else {
if name.eq_ignore_ascii_case("default-src") {
default_src = Some(trimmed.to_string());
}
directives.push(trimmed.to_string());
}
}
if !widened {
let fallback = default_src?;
let sources = fallback
.split_once(char::is_whitespace)
.map_or("", |(_, sources)| sources.trim());
directives.push(format!("connect-src {sources} {source}").replace(" ", " "));
}
Some(directives.join("; "))
}
fn script_nonce(headers: &HeaderMap) -> Option<String> {
let policy = headers.get(CONTENT_SECURITY_POLICY)?.to_str().ok()?;
let directive =
directive_value(policy, "script-src").or_else(|| directive_value(policy, "default-src"))?;
let start = directive.find("'nonce-")? + "'nonce-".len();
let rest = &directive[start..];
let end = rest.find('\'')?;
let nonce = &rest[..end];
nonce
.chars()
.all(|character| character.is_ascii_alphanumeric() || matches!(character, '+' | '/' | '='))
.then(|| nonce.to_string())
}
fn directive_value<'policy>(policy: &'policy str, name: &str) -> Option<&'policy str> {
policy.split(';').find_map(|directive| {
let directive = directive.trim();
let (candidate, sources) = directive.split_once(char::is_whitespace)?;
candidate.eq_ignore_ascii_case(name).then_some(sources)
})
}
#[pin_project::pin_project]
struct InjectBody<B> {
#[pin]
inner: B,
script: Option<Bytes>,
carry: Bytes,
trailers: Option<Frame<Bytes>>,
document: Option<bool>,
head: BytesMut,
finished: bool,
}
impl<B> InjectBody<B> {
fn new(inner: B, script: Bytes) -> Self {
Self {
inner,
script: Some(script),
carry: Bytes::new(),
trailers: None,
document: None,
head: BytesMut::new(),
finished: false,
}
}
}
impl<B> HttpBody for InjectBody<B>
where
B: HttpBody<Data = Bytes>,
{
type Data = Bytes;
type Error = B::Error;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
let mut this = self.project();
loop {
if *this.finished {
return Poll::Ready(this.trailers.take().map(Ok));
}
if this.script.is_none() {
return this.inner.as_mut().poll_frame(cx);
}
let Some(frame) = ready!(this.inner.as_mut().poll_frame(cx)) else {
*this.finished = true;
let mut tail = BytesMut::from(std::mem::take(this.carry));
if end_of_body_is_document(this.document, this.head) {
tail.put_slice(&this.script.take().unwrap_or_default());
}
if tail.is_empty() {
return Poll::Ready(None);
}
return Poll::Ready(Some(Ok(Frame::data(tail.freeze()))));
};
let frame = match frame {
Ok(frame) => frame,
Err(error) => return Poll::Ready(Some(Err(error))),
};
let data = match frame.into_data() {
Ok(data) => data,
Err(trailers) => {
*this.finished = true;
*this.trailers = Some(trailers);
let mut tail = BytesMut::from(std::mem::take(this.carry));
if end_of_body_is_document(this.document, this.head) {
tail.put_slice(&this.script.take().unwrap_or_default());
}
if tail.is_empty() {
return Poll::Ready(this.trailers.take().map(Ok));
}
return Poll::Ready(Some(Ok(Frame::data(tail.freeze()))));
}
};
let mut buffer = BytesMut::with_capacity(this.carry.len() + data.len());
buffer.put_slice(this.carry);
buffer.put_slice(&data);
*this.carry = Bytes::new();
if this.document.is_none() {
let room = DOCUMENT_SNIFF_BYTES.saturating_sub(this.head.len());
this.head.put_slice(&data[..room.min(data.len())]);
*this.document = document_verdict(this.head, false);
}
if let Some(at) = find_ignore_ascii_case(&buffer, HEAD_CLOSE) {
let script = this.script.take().unwrap_or_default();
let mut patched = BytesMut::with_capacity(buffer.len() + script.len());
patched.put_slice(&buffer[..at]);
patched.put_slice(&script);
patched.put_slice(&buffer[at..]);
return Poll::Ready(Some(Ok(Frame::data(patched.freeze()))));
}
let keep = buffer.len().min(HEAD_CLOSE.len() - 1);
let split = buffer.len() - keep;
*this.carry = buffer.split_off(split).freeze();
if buffer.is_empty() {
continue;
}
return Poll::Ready(Some(Ok(Frame::data(buffer.freeze()))));
}
}
fn is_end_stream(&self) -> bool {
self.finished && self.trailers.is_none()
}
fn size_hint(&self) -> SizeHint {
SizeHint::new()
}
}
const DOCUMENT_SNIFF_BYTES: usize = 64;
fn document_verdict(head: &[u8], ended: bool) -> Option<bool> {
let start = head.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(head);
let start = start
.iter()
.position(|byte| !byte.is_ascii_whitespace())
.map_or(&[][..], |at| &start[at..]);
let mut undecided = false;
for prefix in [&b"<!doctype"[..], b"<html"] {
let shared = prefix.len().min(start.len());
if !start[..shared].eq_ignore_ascii_case(&prefix[..shared]) {
continue;
}
if shared == prefix.len() {
return Some(true);
}
undecided = true;
}
if undecided && !ended && head.len() < DOCUMENT_SNIFF_BYTES {
return None;
}
Some(false)
}
fn end_of_body_is_document(document: &Option<bool>, head: &[u8]) -> bool {
if let Some(document) = document {
return *document;
}
head.is_empty() || document_verdict(head, true).unwrap_or(true)
}
fn find_ignore_ascii_case(haystack: &[u8], needle: &[u8]) -> Option<usize> {
if needle.is_empty() || haystack.len() < needle.len() {
return None;
}
haystack
.windows(needle.len())
.position(|window| window.eq_ignore_ascii_case(needle))
}
#[cfg(test)]
mod tests;