larust_live/routes.rs
1use crate::lock::with_session_lock;
2use crate::mount::wrap;
3use crate::registry;
4use crate::state::{load_components, save_components};
5use axum::extract::Path;
6use axum::http::header::{HeaderName, HeaderValue, CONTENT_TYPE};
7use axum::response::{IntoResponse, Response};
8use axum::Json;
9use larust_core::AppError;
10use larust_http::session::Session;
11use serde::Deserialize;
12use std::collections::HashMap;
13
14/// A `wire:submit`/`wire:click` action that returns `Some(path)` from
15/// `WireComponent::call` (Livewire's own `redirect()`) signals "navigate
16/// the browser to `path`" through this response header - read by the
17/// client runtime's `sync()` before it ever looks at the body. A header,
18/// not a body-shaped convention, so the response's `Content-Type` stays
19/// `text/html` and its body stays the same `<div data-wire-id="...">`
20/// fragment shape in both cases (still saved/rendered normally either way,
21/// in case the redirect target itself reads this component's now-updated
22/// state back out of the session).
23const REDIRECT_HEADER: &str = "x-wire-redirect";
24
25/// Any content this component's `render()` pushed to `'head'` during *this*
26/// re-render (via `larust_view::push_registry`) - e.g. a component that
27/// updates the page `<title>`/meta description as its own state changes.
28/// Only the `<!--wire-head:{id}-->...<!--/wire-head:{id}-->` region `mount()`
29/// already wrapped this component's *initial* head contribution in (see
30/// that function's own comment) ever gets patched - there's no surrounding
31/// layout being rendered concurrently with this endpoint to hand fresh
32/// content to a `@stack('head')` directly, so the client runtime patches
33/// the matching marker in `document.head` itself instead. A header, not the
34/// body, for the same reason `REDIRECT_HEADER` is - the response's
35/// `Content-Type`/body shape stays uniform whether or not this component
36/// happens to push anything. Base64-encoded (unlike `REDIRECT_HEADER`'s
37/// plain path): pushed content is arbitrary HTML, which can contain bytes
38/// that aren't valid in a raw header value, and silently dropping it on an
39/// encoding failure would reintroduce exactly the "renders as nothing, no
40/// error anywhere" failure this whole mechanism exists to close.
41const HEAD_PATCH_HEADER: &str = "x-wire-head-patch";
42const HEAD_PATCH_STACK: &str = "head";
43
44const RUNTIME_JS: &str = include_str!("../assets/wire-runtime.js");
45
46/// A deeply-nested `props`/`args` payload (an attacker-controlled input,
47/// gated only by CSRF) can't stack-overflow this endpoint's JSON parsing:
48/// `axum::Json`'s `serde_json::from_slice` runs with `serde_json`'s default
49/// recursion limit (128 levels, `Deserializer::disable_recursion_limit`
50/// left uncalled) already in force - confirmed against `serde_json`'s own
51/// source, not assumed.
52#[derive(Debug, Deserialize)]
53pub struct UpdatePayload {
54 #[serde(default)]
55 props: HashMap<String, serde_json::Value>,
56 #[serde(default)]
57 action: Option<ActionCall>,
58}
59
60#[derive(Debug, Deserialize)]
61struct ActionCall {
62 name: String,
63 #[serde(default)]
64 args: serde_json::Value,
65}
66
67/// `POST /__larust_wire/{component_id}` - handles both a `wire:model`-style
68/// prop sync and a `wire:click`-style action call in one request (see
69/// `UpdatePayload`): every sync carries the component's *entire* current
70/// `wire:model` field set, not a delta, which is what correctly threads a
71/// deferred field's just-typed value through when a different element's
72/// click/wire-sync is what actually triggers the request.
73///
74/// The whole sync is atomic: if the prop merge or the action call fails,
75/// nothing is written back to the session - the previously-stored state is
76/// left untouched. Response is `200 text/html`, the same
77/// `<div data-wire-id="...">` wrapper shape `mount()` produces.
78pub async fn update(
79 session: Session,
80 Path(component_id): Path<String>,
81 Json(payload): Json<UpdatePayload>,
82) -> Result<Response, AppError> {
83 with_session_lock(&session, || async {
84 let mut components = load_components(&session).await?;
85 let index = components
86 .iter()
87 .position(|(id, _)| id == &component_id)
88 .ok_or(AppError::NotFound)?;
89
90 let entry = registry::lookup(&components[index].1.name).ok_or(AppError::NotFound)?;
91
92 let mut state = (entry.set_many)(components[index].1.state.clone(), &payload.props)?;
93 let mut redirect = None;
94 if let Some(action) = &payload.action {
95 let (new_state, action_redirect) =
96 (entry.call)(state, &session, &action.name, &action.args).await?;
97 state = new_state;
98 redirect = action_redirect;
99 }
100 let html = (entry.render)(&state).await?;
101 // Each request gets a fresh, empty-at-start registry (see
102 // `larust_http::push_registry_scope`), so a plain `drain` - not
103 // `mark`/`drain_since` the way `mount()` needs - is enough: there's
104 // no unrelated earlier content in *this* request to avoid
105 // disturbing.
106 let head_patch = larust_view::push_registry::drain(HEAD_PATCH_STACK);
107
108 components[index].1.state = state;
109 save_components(&session, &components).await?;
110
111 Ok(html_response(
112 wrap(&component_id, &html),
113 redirect,
114 head_patch,
115 ))
116 })
117 .await
118}
119
120fn html_response(html: String, redirect: Option<String>, head_patch: String) -> Response {
121 let mut response = ([(CONTENT_TYPE, "text/html; charset=utf-8")], html).into_response();
122 if let Some(path) = redirect {
123 // A malformed path (non-ASCII, a stray control character) can't
124 // become a valid header value - falls back to a safe default
125 // rather than let an otherwise-successful action response 500 on
126 // header construction. Component authors control this string, but
127 // it's still worth not panicking/erroring on a typo.
128 let value = HeaderValue::from_str(&path).unwrap_or_else(|_| HeaderValue::from_static("/"));
129 response
130 .headers_mut()
131 .insert(HeaderName::from_static(REDIRECT_HEADER), value);
132 }
133 if !head_patch.is_empty() {
134 // Base64 output is always valid header-value bytes - no fallible
135 // path here, unlike the redirect header above.
136 let encoded = base64::Engine::encode(
137 &base64::engine::general_purpose::STANDARD,
138 head_patch.as_bytes(),
139 );
140 response.headers_mut().insert(
141 HeaderName::from_static(HEAD_PATCH_HEADER),
142 HeaderValue::from_str(&encoded).expect("base64 output is always a valid header value"),
143 );
144 }
145 response
146}
147
148/// `GET /__larust_wire/runtime.js` - the vendored client runtime, served
149/// from the installed `larust-live` crate itself (`include_str!`'d, not
150/// vendored into every scaffolded app's `public/js/`) so it stays
151/// version-locked to the framework with zero drift/"forgot to re-copy
152/// after an upgrade" risk.
153pub async fn runtime_js() -> impl IntoResponse {
154 (
155 [(CONTENT_TYPE, "text/javascript; charset=utf-8")],
156 RUNTIME_JS,
157 )
158}