1use std::collections::BTreeMap;
22use std::future::Future;
23
24use http::HeaderMap;
25use next_rust_core::config::CsrfMode;
26use serde::Serialize;
27use serde::de::DeserializeOwned;
28
29use crate::Cookie;
30use crate::action_token;
31use crate::app::AppInner;
32use crate::cookies::Cookies;
33use crate::error::{Error, ErrorKind, Result};
34use crate::request::Request;
35use crate::response::Response;
36
37pub const FLASH_COOKIE: &str = "nr_flash";
38
39const STALE_MESSAGE: &str = "This page is out of date. Reload it and try again.";
42
43#[derive(Clone)]
45pub struct ActionContext {
46 pub cookies: Cookies,
47 pub headers: HeaderMap,
48 pub extensions: http::Extensions,
49}
50
51impl ActionContext {
52 pub fn extension<T: Send + Sync + 'static>(&self) -> Option<&T> {
53 self.extensions.get::<T>()
54 }
55}
56
57pub(crate) async fn handle(inner: &AppInner, mut req: Request) -> Response {
58 if req.method() != http::Method::POST {
59 return Response::text("Method Not Allowed").with_status(405).with_header("allow", "POST");
60 }
61 let security = &inner.config.security;
62 if security.csrf != CsrfMode::Off && !same_origin(&req, &security.allowed_origins) {
63 crate::log::warn("server action rejected: cross-origin request");
64 return Response::text("Forbidden: cross-origin server action").with_status(403);
65 }
66 let token = req.path().trim_start_matches("/_nr/action/");
67 let binding = action_token::binding(req.cookies());
68 let found = action_token::verify(token, binding.as_deref())
69 .and_then(|key| inner.actions.get(&key).copied().ok_or(action_token::Rejection::Forged));
70 let index = match found {
71 Ok(index) => index,
72 Err(reason) => {
73 match reason {
74 action_token::Rejection::Expired => crate::log::debug("server action rejected: expired token"),
75 other => crate::log::warn(&format!("server action rejected: {}", other.as_str())),
76 }
77 return stale(&req);
78 }
79 };
80 if let Some(res) = check_content_type(&req) {
81 return res;
82 }
83 if security.csrf == CsrfMode::Token && !double_submit_ok(&mut req).await {
84 crate::log::warn("server action rejected: missing or invalid CSRF token");
85 return Response::text("Invalid CSRF token").with_status(403);
86 }
87 let mut res = (inner.routes.actions[index].handler)(req).await;
88 res.set_header("cache-control", "no-store");
89 res
90}
91
92pub(crate) fn signed_url(id: &str, binding: &str, ttl: u64) -> String {
94 format!("/_nr/action/{}", action_token::mint(&action_token::action_key(id), binding, ttl))
95}
96
97fn stale(req: &Request) -> Response {
98 let res = if wants_json(req) {
99 Response::json(&serde_json::json!({ "ok": false, "error": STALE_MESSAGE, "code": "nr_stale" })).with_status(403)
100 } else {
101 flash_back(req, &[], BTreeMap::new(), Some(STALE_MESSAGE.to_owned()))
103 };
104 res.with_header("cache-control", "no-store")
105}
106
107fn check_content_type(req: &Request) -> Option<Response> {
108 let ct = req.header("content-type")?;
109 let base = ct.split(';').next().unwrap_or_default().trim().to_ascii_lowercase();
110 match base.as_str() {
111 "application/json" | "application/x-www-form-urlencoded" => None,
112 b if b.starts_with("multipart/") => Some(
113 Response::text("multipart bodies are not supported by server actions; use an API route").with_status(415),
114 ),
115 _ => Some(Response::text("Unsupported Media Type").with_status(415)),
116 }
117}
118
119async fn double_submit_ok(req: &mut Request) -> bool {
120 let Some(cookie) = req.cookies().get(crate::CSRF_COOKIE) else { return false };
121 let provided = match req.header("x-csrf-token") {
122 Some(v) => Some(v.to_owned()),
123 None if is_form(req) => crate::middleware::form_field(req, "_csrf").await,
124 None => None,
125 };
126 provided.is_some_and(|p| crate::constant_time_eq(cookie.as_bytes(), p.as_bytes()))
127}
128
129pub(crate) fn same_origin(req: &Request, allowed: &[String]) -> bool {
131 let fetch_site = req.header("sec-fetch-site");
132 if matches!(fetch_site, Some("same-origin") | Some("none")) {
133 return true;
134 }
135 let Some(origin) = req.header("origin") else {
136 return fetch_site.is_none();
138 };
139 if allowed.iter().any(|a| a == origin) {
140 return true;
141 }
142 let host = if crate::trust_proxy() {
143 req.header("x-forwarded-host").or_else(|| req.header("host"))
144 } else {
145 req.header("host")
146 };
147 let origin_host = origin.split_once("://").map(|(_, h)| h);
148 matches!((origin_host, host), (Some(o), Some(h)) if o.eq_ignore_ascii_case(h))
149}
150
151fn is_form(req: &Request) -> bool {
152 req.header("content-type").is_some_and(|c| c.starts_with("application/x-www-form-urlencoded"))
153}
154
155fn wants_json(req: &Request) -> bool {
156 !is_form(req)
157 || req.header("x-nr-action").is_some()
158 || req.header("accept").is_some_and(|a| a.starts_with("application/json"))
159}
160
161async fn read_input<I: DeserializeOwned>(req: &mut Request) -> Result<(I, Vec<(String, String)>)> {
162 if req.header("content-type").is_some_and(|c| c.starts_with("multipart/")) {
163 return Err(Error::http(415, "multipart bodies are not supported by server actions; use an API route"));
164 }
165 let bytes = req.bytes().await?;
166 if is_form(req) {
167 let fields: Vec<(String, String)> = serde_urlencoded::from_bytes(&bytes).unwrap_or_default();
168 let input =
169 serde_urlencoded::from_bytes(&bytes).map_err(|e| Error::http(400, format!("invalid form data: {e}")))?;
170 Ok((input, fields))
171 } else {
172 let slice: &[u8] = if bytes.iter().all(u8::is_ascii_whitespace) { b"null" } else { &bytes };
173 let input = serde_json::from_slice(slice).map_err(|e| Error::http(400, format!("invalid JSON input: {e}")))?;
174 Ok((input, Vec::new()))
175 }
176}
177
178fn local_path(candidate: &str) -> Option<String> {
179 (candidate.starts_with('/') && !candidate.starts_with("//") && !candidate.contains('\\'))
180 .then(|| candidate.to_owned())
181}
182
183fn back_location(req: &Request, fields: &[(String, String)]) -> String {
184 if let Some(r) = fields.iter().find(|(k, _)| k == "_redirect").and_then(|(_, v)| local_path(v)) {
185 return r;
186 }
187 let host = req.header("host").unwrap_or_default();
188 req.header("referer")
189 .and_then(|r| r.split_once("://").map(|(_, rest)| rest.to_owned()))
190 .and_then(|rest| rest.strip_prefix(host).map(str::to_owned))
191 .and_then(|p| local_path(&p))
192 .unwrap_or_else(|| "/".into())
193}
194
195fn respond<O: Serialize>(req: &Request, json: bool, fields: &[(String, String)], result: Result<O>) -> Response {
196 match (json, result) {
197 (true, Ok(data)) => Response::json(&serde_json::json!({ "ok": true, "data": data })),
198 (false, Ok(_)) => Response::see_other(&back_location(req, fields)),
199 (json, Err(e)) => {
200 let status = e.status();
201 match e.into_kind() {
202 ErrorKind::Redirect { location, .. } => {
203 if json {
204 Response::json(&serde_json::json!({ "ok": false, "redirect": location }))
205 } else {
206 Response::see_other(&location)
207 }
208 }
209 ErrorKind::Validation(errors) => {
210 if json {
211 Response::json(&serde_json::json!({ "ok": false, "errors": errors })).with_status(422)
212 } else {
213 flash_back(req, fields, errors, None)
214 }
215 }
216 kind => {
217 let err = Error::new(kind);
218 if status.is_server_error() {
219 crate::log::error(&format!("server action failed: {}", err.detailed_message()));
220 }
221 let message = if crate::is_dev() { err.detailed_message() } else { err.public_message() };
222 if json {
223 Response::json(&serde_json::json!({ "ok": false, "error": message }))
224 .with_status(status.as_u16())
225 } else {
226 flash_back(req, fields, BTreeMap::new(), Some(message))
227 }
228 }
229 }
230 }
231 }
232}
233
234fn flash_back(
235 req: &Request,
236 fields: &[(String, String)],
237 errors: BTreeMap<String, String>,
238 message: Option<String>,
239) -> Response {
240 let values: BTreeMap<String, String> = fields
241 .iter()
242 .filter(|(k, _)| {
243 !k.starts_with('_')
244 && !k.to_ascii_lowercase().contains("password")
245 && !k.to_ascii_lowercase().contains("token")
246 })
247 .map(|(k, v)| (k.clone(), v.chars().take(256).collect()))
248 .collect();
249 let json = serde_json::json!({ "errors": errors, "message": message, "values": values }).to_string();
250 let json: String = json.chars().take(3000).collect();
251 req.cookies().set(Cookie::encoded(FLASH_COOKIE, &json).max_age(std::time::Duration::from_secs(60)));
252 Response::see_other(&back_location(req, fields))
253}
254
255pub(crate) fn decode_flash(raw: &str) -> crate::context::FormState {
256 #[derive(serde::Deserialize, Default)]
257 struct Flash {
258 #[serde(default)]
259 errors: BTreeMap<String, String>,
260 message: Option<String>,
261 #[serde(default)]
262 values: BTreeMap<String, String>,
263 }
264 let f: Flash = serde_json::from_str(raw).unwrap_or_default();
265 crate::context::FormState { errors: f.errors, message: f.message, values: f.values }
266}
267
268pub async fn run_action<I, O, F, Fut>(mut req: Request, f: F) -> Response
270where
271 I: DeserializeOwned,
272 O: Serialize,
273 F: FnOnce(I) -> Fut,
274 Fut: Future<Output = Result<O>>,
275{
276 let json = wants_json(&req);
277 match read_input::<I>(&mut req).await {
278 Ok((input, fields)) => {
279 let result = f(input).await;
280 respond(&req, json, &fields, result)
281 }
282 Err(e) => respond::<()>(&req, json, &[], Err(e)),
283 }
284}
285
286pub async fn run_action_ctx<I, O, F, Fut>(mut req: Request, f: F) -> Response
288where
289 I: DeserializeOwned,
290 O: Serialize,
291 F: FnOnce(ActionContext, I) -> Fut,
292 Fut: Future<Output = Result<O>>,
293{
294 let json = wants_json(&req);
295 let ctx = ActionContext {
296 cookies: req.cookies().clone(),
297 headers: req.headers().clone(),
298 extensions: req.extensions().clone(),
299 };
300 match read_input::<I>(&mut req).await {
301 Ok((input, fields)) => {
302 let result = f(ctx, input).await;
303 respond(&req, json, &fields, result)
304 }
305 Err(e) => respond::<()>(&req, json, &[], Err(e)),
306 }
307}
308
309pub async fn run_action0<O, F, Fut>(mut req: Request, f: F) -> Response
311where
312 O: Serialize,
313 F: FnOnce() -> Fut,
314 Fut: Future<Output = Result<O>>,
315{
316 let json = wants_json(&req);
317 let fields: Vec<(String, String)> = if is_form(&req) {
318 req.bytes().await.ok().and_then(|b| serde_urlencoded::from_bytes(&b).ok()).unwrap_or_default()
319 } else {
320 Vec::new()
321 };
322 let result = f().await;
323 respond(&req, json, &fields, result)
324}
325
326#[derive(Debug, Clone, Copy)]
332pub struct ActionRef {
333 pub id: &'static str,
334}
335
336impl ActionRef {
337 pub const fn new(id: &'static str) -> Self {
338 ActionRef { id }
339 }
340
341 pub fn url(&self) -> String {
344 action_token::marker_url(self.id)
345 }
346}
347
348impl From<ActionRef> for next_rust_ui::Press {
350 fn from(action: ActionRef) -> Self {
351 next_rust_ui::Press::action(action.url())
352 }
353}
354
355impl next_rust_view::Part for ActionRef {
356 fn apply(self, el: &mut next_rust_view::Element) {
357 el.set_attr(next_rust_view::attrs::action(self.url()));
358 el.set_attr(next_rust_view::attrs::method("post"));
359 el.set_attr(next_rust_view::attrs::data("nr-action", self.url()));
360 }
361}