livewire-rust 0.1.4

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
Documentation
//! The endpoints the browser calls: the update handler, and the built runtime it loads.

use std::sync::Arc;

use laravel::container::Inject;
use laravel::http::{Request, Response, StatusCode};
use serde_json::{Map, Value};

use crate::checksum;
use crate::component::{Call, Params};
use crate::context::LivewireRequest;
use crate::error::LivewireError;
use crate::registry::ComponentRegistry;
use crate::snapshot::Snapshot;

/// Whether a request came from the browser runtime: it carries `X-Livewire` and a JSON body.
///
/// A request without both answers `404`, so a scanner cannot confirm the endpoint exists.
fn is_livewire_request(request: &Request) -> bool {
    request.header("x-livewire").is_some()
        && request
            .header("content-type")
            .is_some_and(|content_type| content_type.starts_with("application/json"))
}

/// Handles the browser's update request for a batch of components.
pub async fn update(registry: Inject<Arc<ComponentRegistry>>, request: Request) -> Response {
    let registry = Arc::clone(&registry);
    let config = registry.config().clone();

    if !is_livewire_request(&request) {
        return empty(StatusCode::NOT_FOUND);
    }

    // The body is read before it is parsed, so a chunked request without a content length still
    // hits the size guard.
    let limit = config.payload.max_size.unwrap_or(usize::MAX);
    let body = match read_body(request, limit).await {
        Ok(ReadBody::Bytes(pair)) => *pair,
        Ok(ReadBody::TooLarge { size }) => {
            return LivewireError::PayloadTooLarge { size, max: limit }.into_response(false);
        }
        Ok(ReadBody::Unreadable(error)) => return empty(error),
        Err(response) => return response,
    };

    let (bytes, request) = body;

    if bytes.is_empty() {
        return empty(StatusCode::NOT_FOUND);
    }

    let payload: Value = match serde_json::from_slice(&bytes) {
        Ok(payload) => payload,
        Err(_) => {
            return empty(StatusCode::NOT_FOUND);
        }
    };

    let Some(components) = payload.get("components").and_then(Value::as_array) else {
        return empty(StatusCode::NOT_FOUND);
    };
    if components.is_empty() {
        return empty(StatusCode::NOT_FOUND);
    }

    // Every component's envelope is checked before any count limit is applied, so a malformed
    // request is a `404` rather than a limit violation.
    let mut parsed = Vec::with_capacity(components.len());
    for component in components {
        let snapshot = component.get("snapshot").and_then(Value::as_str);
        let updates = component.get("updates").and_then(Value::as_object);
        let calls = component.get("calls").and_then(Value::as_array);

        let (Some(snapshot), Some(updates), Some(calls)) = (snapshot, updates, calls) else {
            return empty(StatusCode::NOT_FOUND);
        };

        let mut decoded = Vec::with_capacity(calls.len());
        for call in calls {
            let method = call.get("method").and_then(Value::as_str);
            let params = call.get("params").cloned().unwrap_or(Value::Array(Vec::new()));
            let metadata = call
                .get("metadata")
                .and_then(Value::as_object)
                .cloned()
                .unwrap_or_default();

            let Some(method) = method else {
                return empty(StatusCode::NOT_FOUND);
            };

            match Params::from_json(params) {
                Ok(params) => decoded.push(Call {
                    method: method.to_owned(),
                    params,
                    metadata,
                }),
                Err(_) => return empty(StatusCode::NOT_FOUND),
            }
        }

        parsed.push((snapshot, updates.clone(), decoded));
    }

    if let Some(max) = config.payload.max_components
        && parsed.len() > max
    {
        return LivewireError::TooManyComponents {
            count: parsed.len(),
            max,
        }
        .into_response(false);
    }

    if let Some(max) = config.payload.max_calls {
        let count: usize = parsed.iter().map(|(_, _, calls)| calls.len()).sum();
        if count > max {
            return LivewireError::TooManyCalls { count, max }.into_response(false);
        }
    }

    // One request holds the whole batch's Livewire state, so the components share their render
    // stack and their response-level assets.
    let state = Arc::new(LivewireRequest::default());
    state.set_http_request(Arc::new(request));

    let mut responses = Vec::with_capacity(parsed.len());
    let mut frames: Vec<Value> = Vec::new();

    for (json, updates, calls) in parsed {
        let snapshot = match Snapshot::parse(json) {
            Ok(snapshot) => snapshot,
            Err(error) => return error.into_response(config_is_debug(&registry)),
        };

        let result = update_one(&registry, &state, &snapshot, updates, calls).await;

        match result {
            Ok(Answer::Updated(response, streamed)) => {
                responses.push(response);
                frames.extend(streamed);
            }
            Ok(Answer::Refused(response)) => return response,
            Err(error) => return error.into_response(config_is_debug(&registry)),
        }
    }

    let body = serde_json::json!({
        "components": responses,
        "assets": state.take_assets(),
    });

    let payload = match serde_json::to_vec(&body) {
        Ok(bytes) => bytes,
        Err(_) => return empty(StatusCode::INTERNAL_SERVER_ERROR),
    };

    // A streamed answer is its frames, in order, followed by the payload a plain answer would
    // have carried; the client reads the frames as they arrive and then parses the payload.
    let (bytes, streamed) = if frames.is_empty() {
        (payload, false)
    } else {
        let mut bytes = Vec::with_capacity(payload.len());
        for frame in &frames {
            match serde_json::to_vec(frame) {
                Ok(frame) => bytes.extend(frame),
                Err(_) => return empty(StatusCode::INTERNAL_SERVER_ERROR),
            }
        }
        bytes.extend(payload);

        (bytes, true)
    };

    let mut response = Response::new(bytes);

    let headers: &[(&str, &str)] = if streamed {
        // The browser reads the frames as they arrive; nothing may buffer or cache them.
        &[
            ("content-type", "text/event-stream"),
            ("cache-control", "no-cache"),
            ("x-livewire-stream", "true"),
        ]
    } else {
        &[("content-type", "application/json")]
    };

    for (name, value) in headers {
        if let Ok(value) = value.parse() {
            response.headers_mut().insert(*name, value);
        }
    }

    response
}

/// Whether the application renders detailed errors, which its debug mode decides.
fn config_is_debug(registry: &ComponentRegistry) -> bool {
    let _ = registry;

    laravel_core::context::Context::current()
        .map(|context| {
            use laravel_core::context::Internals as _;

            context.config().app.debug
        })
        .unwrap_or(false)
}

/// The body of a request, read within its size limit.
enum ReadBody {
    /// The body, and the request rebuilt around a cheap clone of it so the session and the
    /// action's services still work.
    Bytes(Box<(bytes::Bytes, Request)>),
    /// How large the body was, when it passed the limit.
    TooLarge { size: usize },
    /// The status to answer with when the body could not be read.
    Unreadable(StatusCode),
}

/// Reads the request's body, keeping the request usable for the components that follow.
async fn read_body(request: Request, limit: usize) -> Result<ReadBody, Response> {
    use http_body_util::BodyExt as _;

    let (parts, body) = request.into_http().into_parts();
    let collected = body.collect().await;

    let Ok(collected) = collected else {
        return Ok(ReadBody::Unreadable(StatusCode::BAD_REQUEST));
    };

    let bytes = collected.to_bytes();
    if bytes.len() > limit {
        return Ok(ReadBody::TooLarge { size: bytes.len() });
    }

    let rebuilt = Request::from_http(http_request(parts, bytes.clone()));

    Ok(ReadBody::Bytes(Box::new((bytes, rebuilt))))
}

/// Rebuilds the HTTP request around a clone of its body, without copying the bytes.
fn http_request(
    parts: laravel::axum::http::request::Parts,
    bytes: bytes::Bytes,
) -> laravel::axum::http::Request<laravel::axum::body::Body> {
    laravel::axum::http::Request::from_parts(parts, laravel::axum::body::Body::from(bytes))
}

/// Updates one component and produces its entry in the response.
async fn update_one(
    registry: &Arc<ComponentRegistry>,
    state: &Arc<LivewireRequest>,
    snapshot: &Snapshot,
    updates: Map<String, Value>,
    calls: Vec<Call>,
) -> Result<Answer, LivewireError> {
    let id = snapshot.id()?.to_owned();

    // A batch with no calls at all must still prove its snapshot, so the checksum comes first.
    verify_checksum(registry, state, snapshot).await?;

    // An unchanged reactive child is answered without a render, but only after its snapshot is
    // verified: a caller that cannot prove it owns the component learns nothing.
    if crate::render::should_skip(registry, snapshot, &updates, &calls) {
        return Ok(Answer::Updated(serde_json::json!({"skip": true, "id": id}), Vec::new()));
    }

    let http = state.http_request();
    // A guard the application registered runs for the page the component was mounted from, so a
    // route's check holds while the browser drives the component.
    if let Some(page) = page_of(snapshot)
        && let Some(http) = state.http_request()
    {
        for guard in registry.persistent_guards() {
            if let Some(response) = guard.handle(&http, &page).await {
                return Ok(Answer::Refused(response));
            }
        }
    }

    let updated = crate::render::update(registry, snapshot, updates, calls, http).await?;

    let mut entry = Map::new();
    if let Some(snapshot) = &updated.snapshot {
        entry.insert("snapshot".to_owned(), Value::from(snapshot.encode()));
    }
    entry.insert("effects".to_owned(), Value::Object(updated.effects));

    Ok(Answer::Updated(Value::Object(entry), updated.frames))
}

/// What one component's answer is: its response, or the refusal a guard answered with.
enum Answer {
    /// The component updated.
    Updated(Value, Vec<Value>),
    /// A guard refused the update, and its response is the answer.
    Refused(Response),
}

/// The page a snapshot was mounted from, when it recorded one.
fn page_of(snapshot: &Snapshot) -> Option<crate::context::PageContext> {
    Some(crate::context::PageContext {
        path: snapshot.memo_value("path")?.as_str()?.to_owned(),
        method: snapshot.memo_value("method")?.as_str()?.to_owned(),
        origin: snapshot.memo_value("origin")?.as_str()?.to_owned(),
    })
}

/// Verifies a snapshot's checksum, enforcing the client's failure allowance once per batch.
async fn verify_checksum(
    registry: &Arc<ComponentRegistry>,
    state: &Arc<LivewireRequest>,
    snapshot: &Snapshot,
) -> Result<(), LivewireError> {
    let _ = registry;

    let ip = state
        .http_request()
        .map(|request| request.ip().to_string())
        .unwrap_or_else(|| "unknown".to_owned());

    if state.first_checksum_check() {
        checksum::ensure_allowed(&ip).await?;
    }

    match checksum::verify_or_error(snapshot, &app_key()?) {
        Ok(()) => Ok(()),
        Err(error) => {
            checksum::record_failure(&ip).await.ok();
            Err(error)
        }
    }
}

/// The application's encryption key, which signs and verifies snapshots.
fn app_key() -> Result<Vec<u8>, LivewireError> {
    use laravel_core::context::Internals as _;

    let context = laravel_core::context::Context::current().ok_or_else(|| {
        LivewireError::MalformedPayload("Livewire needs the application to sign a snapshot".to_owned())
    })?;

    let encrypter = context
        .encrypter()
        .map_err(|error| LivewireError::MalformedPayload(format!("the application's key is invalid: {error}")))?;

    Ok(encrypter.key().to_vec())
}

/// An empty response with a status, which the protocol's rejections use.
fn empty(status: StatusCode) -> Response {
    Response::new("").with_status(status)
}