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