1use std::collections::BTreeMap;
14use std::future::Future;
15
16use http::HeaderMap;
17use next_rust_core::config::CsrfMode;
18use serde::Serialize;
19use serde::de::DeserializeOwned;
20
21use crate::Cookie;
22use crate::app::AppInner;
23use crate::cookies::Cookies;
24use crate::error::{Error, ErrorKind, Result};
25use crate::request::Request;
26use crate::response::Response;
27
28pub const FLASH_COOKIE: &str = "nr_flash";
29
30pub fn action_hash(id: &str) -> String {
32 next_rust_assets::content_hash(id.as_bytes())
33}
34
35pub fn action_url(id: &str) -> String {
37 format!("/_nr/action/{}", action_hash(id))
38}
39
40#[derive(Clone)]
42pub struct ActionContext {
43 pub cookies: Cookies,
44 pub headers: HeaderMap,
45 pub extensions: http::Extensions,
46}
47
48impl ActionContext {
49 pub fn extension<T: Send + Sync + 'static>(&self) -> Option<&T> {
50 self.extensions.get::<T>()
51 }
52}
53
54pub(crate) async fn handle(inner: &AppInner, req: Request) -> Response {
55 if req.method() != http::Method::POST {
56 return Response::text("Method Not Allowed").with_status(405).with_header("allow", "POST");
57 }
58 let hash = req.path().trim_start_matches("/_nr/action/");
59 let Some(&index) = inner.actions.get(hash) else {
60 return Response::text("Unknown server action").with_status(404);
61 };
62 if inner.config.security.csrf != CsrfMode::Off && !same_origin(&req, &inner.config.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 (inner.routes.actions[index].handler)(req).await
67}
68
69pub(crate) fn same_origin(req: &Request, allowed: &[String]) -> bool {
71 let fetch_site = req.header("sec-fetch-site");
72 if matches!(fetch_site, Some("same-origin") | Some("none")) {
73 return true;
74 }
75 let Some(origin) = req.header("origin") else {
76 return fetch_site.is_none();
78 };
79 if allowed.iter().any(|a| a == origin) {
80 return true;
81 }
82 let host = if crate::trust_proxy() {
83 req.header("x-forwarded-host").or_else(|| req.header("host"))
84 } else {
85 req.header("host")
86 };
87 let origin_host = origin.split_once("://").map(|(_, h)| h);
88 matches!((origin_host, host), (Some(o), Some(h)) if o.eq_ignore_ascii_case(h))
89}
90
91fn is_form(req: &Request) -> bool {
92 req.header("content-type").is_some_and(|c| c.starts_with("application/x-www-form-urlencoded"))
93}
94
95fn wants_json(req: &Request) -> bool {
96 !is_form(req)
97 || req.header("x-nr-action").is_some()
98 || req.header("accept").is_some_and(|a| a.starts_with("application/json"))
99}
100
101async fn read_input<I: DeserializeOwned>(req: &mut Request) -> Result<(I, Vec<(String, String)>)> {
102 if req.header("content-type").is_some_and(|c| c.starts_with("multipart/")) {
103 return Err(Error::http(415, "multipart bodies are not supported by server actions; use an API route"));
104 }
105 let bytes = req.bytes().await?;
106 if is_form(req) {
107 let fields: Vec<(String, String)> = serde_urlencoded::from_bytes(&bytes).unwrap_or_default();
108 let input =
109 serde_urlencoded::from_bytes(&bytes).map_err(|e| Error::http(400, format!("invalid form data: {e}")))?;
110 Ok((input, fields))
111 } else {
112 let slice: &[u8] = if bytes.iter().all(u8::is_ascii_whitespace) { b"null" } else { &bytes };
113 let input = serde_json::from_slice(slice).map_err(|e| Error::http(400, format!("invalid JSON input: {e}")))?;
114 Ok((input, Vec::new()))
115 }
116}
117
118fn local_path(candidate: &str) -> Option<String> {
119 (candidate.starts_with('/') && !candidate.starts_with("//") && !candidate.contains('\\'))
120 .then(|| candidate.to_owned())
121}
122
123fn back_location(req: &Request, fields: &[(String, String)]) -> String {
124 if let Some(r) = fields.iter().find(|(k, _)| k == "_redirect").and_then(|(_, v)| local_path(v)) {
125 return r;
126 }
127 let host = req.header("host").unwrap_or_default();
128 req.header("referer")
129 .and_then(|r| r.split_once("://").map(|(_, rest)| rest.to_owned()))
130 .and_then(|rest| rest.strip_prefix(host).map(str::to_owned))
131 .and_then(|p| local_path(&p))
132 .unwrap_or_else(|| "/".into())
133}
134
135fn respond<O: Serialize>(req: &Request, json: bool, fields: &[(String, String)], result: Result<O>) -> Response {
136 match (json, result) {
137 (true, Ok(data)) => Response::json(&serde_json::json!({ "ok": true, "data": data })),
138 (false, Ok(_)) => Response::see_other(&back_location(req, fields)),
139 (json, Err(e)) => {
140 let status = e.status();
141 match e.into_kind() {
142 ErrorKind::Redirect { location, .. } => {
143 if json {
144 Response::json(&serde_json::json!({ "ok": false, "redirect": location }))
145 } else {
146 Response::see_other(&location)
147 }
148 }
149 ErrorKind::Validation(errors) => {
150 if json {
151 Response::json(&serde_json::json!({ "ok": false, "errors": errors })).with_status(422)
152 } else {
153 flash_back(req, fields, errors, None)
154 }
155 }
156 kind => {
157 let err = Error::new(kind);
158 if status.is_server_error() {
159 crate::log::error(&format!("server action failed: {}", err.detailed_message()));
160 }
161 let message = if crate::is_dev() { err.detailed_message() } else { err.public_message() };
162 if json {
163 Response::json(&serde_json::json!({ "ok": false, "error": message }))
164 .with_status(status.as_u16())
165 } else {
166 flash_back(req, fields, BTreeMap::new(), Some(message))
167 }
168 }
169 }
170 }
171 }
172}
173
174fn flash_back(
175 req: &Request,
176 fields: &[(String, String)],
177 errors: BTreeMap<String, String>,
178 message: Option<String>,
179) -> Response {
180 let values: BTreeMap<String, String> = fields
181 .iter()
182 .filter(|(k, _)| {
183 !k.starts_with('_')
184 && !k.to_ascii_lowercase().contains("password")
185 && !k.to_ascii_lowercase().contains("token")
186 })
187 .map(|(k, v)| (k.clone(), v.chars().take(256).collect()))
188 .collect();
189 let json = serde_json::json!({ "errors": errors, "message": message, "values": values }).to_string();
190 let json: String = json.chars().take(3000).collect();
191 req.cookies().set(Cookie::encoded(FLASH_COOKIE, &json).max_age(std::time::Duration::from_secs(60)));
192 Response::see_other(&back_location(req, fields))
193}
194
195pub(crate) fn decode_flash(raw: &str) -> crate::context::FormState {
196 #[derive(serde::Deserialize, Default)]
197 struct Flash {
198 #[serde(default)]
199 errors: BTreeMap<String, String>,
200 message: Option<String>,
201 #[serde(default)]
202 values: BTreeMap<String, String>,
203 }
204 let f: Flash = serde_json::from_str(raw).unwrap_or_default();
205 crate::context::FormState { errors: f.errors, message: f.message, values: f.values }
206}
207
208pub async fn run_action<I, O, F, Fut>(mut req: Request, f: F) -> Response
210where
211 I: DeserializeOwned,
212 O: Serialize,
213 F: FnOnce(I) -> Fut,
214 Fut: Future<Output = Result<O>>,
215{
216 let json = wants_json(&req);
217 match read_input::<I>(&mut req).await {
218 Ok((input, fields)) => {
219 let result = f(input).await;
220 respond(&req, json, &fields, result)
221 }
222 Err(e) => respond::<()>(&req, json, &[], Err(e)),
223 }
224}
225
226pub async fn run_action_ctx<I, O, F, Fut>(mut req: Request, f: F) -> Response
228where
229 I: DeserializeOwned,
230 O: Serialize,
231 F: FnOnce(ActionContext, I) -> Fut,
232 Fut: Future<Output = Result<O>>,
233{
234 let json = wants_json(&req);
235 let ctx = ActionContext {
236 cookies: req.cookies().clone(),
237 headers: req.headers().clone(),
238 extensions: req.extensions().clone(),
239 };
240 match read_input::<I>(&mut req).await {
241 Ok((input, fields)) => {
242 let result = f(ctx, input).await;
243 respond(&req, json, &fields, result)
244 }
245 Err(e) => respond::<()>(&req, json, &[], Err(e)),
246 }
247}
248
249pub async fn run_action0<O, F, Fut>(mut req: Request, f: F) -> Response
251where
252 O: Serialize,
253 F: FnOnce() -> Fut,
254 Fut: Future<Output = Result<O>>,
255{
256 let json = wants_json(&req);
257 let fields: Vec<(String, String)> = if is_form(&req) {
258 req.bytes().await.ok().and_then(|b| serde_urlencoded::from_bytes(&b).ok()).unwrap_or_default()
259 } else {
260 Vec::new()
261 };
262 let result = f().await;
263 respond(&req, json, &fields, result)
264}
265
266#[derive(Debug, Clone, Copy)]
272pub struct ActionRef {
273 pub id: &'static str,
274}
275
276impl ActionRef {
277 pub const fn new(id: &'static str) -> Self {
278 ActionRef { id }
279 }
280
281 pub fn url(&self) -> String {
282 action_url(self.id)
283 }
284}
285
286impl next_rust_view::Part for ActionRef {
287 fn apply(self, el: &mut next_rust_view::Element) {
288 el.set_attr(next_rust_view::attrs::action(self.url()));
289 el.set_attr(next_rust_view::attrs::method("post"));
290 el.set_attr(next_rust_view::attrs::data("nr-action", self.url()));
291 }
292}