1use mlua::{ExternalResult as _, Function, Lua, ObjectLike as _, Table, Value};
16use sha2::Sha256;
17
18mod cookies;
19
20pub use cookies::{
21 CookieDefaults, RequestCookies, ResponseCookies, SetCookie, parse_set_cookie, sign, verify,
22};
23pub(crate) use cookies::{attach_cookie, build_cookie, merge_cookie_opts};
24
25pub fn response_table(lua: &Lua, status: u16) -> mlua::Result<Table> {
28 let table = lua.create_table()?;
29 table.set("status", status)?;
30 table.set("headers", lua.create_table()?)?;
31 table.set("cookies", ResponseCookies::default())?;
32 Ok(table)
33}
34
35fn set_content_type(table: &Table, value: &str) -> mlua::Result<()> {
36 table.get::<Table>("headers")?.set("Content-Type", value)
37}
38
39pub(crate) fn register(lua: &Lua, nitr: &Table) -> mlua::Result<()> {
43 nitr.set(
44 "text",
45 lua.create_function(|lua, (body, status): (mlua::LuaString, Option<u16>)| {
46 let table = response_table(lua, status.unwrap_or(200))?;
47 set_content_type(&table, "text/plain; charset=utf-8")?;
48 table.set("body", body)?;
49 Ok(table)
50 })?,
51 )?;
52
53 nitr.set(
54 "html",
55 lua.create_function(|lua, (body, status): (mlua::LuaString, Option<u16>)| {
56 let table = response_table(lua, status.unwrap_or(200))?;
57 set_content_type(&table, "text/html; charset=utf-8")?;
58 table.set("body", body)?;
59 Ok(table)
60 })?,
61 )?;
62
63 nitr.set(
64 "redirect",
65 lua.create_function(|lua, (location, status): (String, Option<u16>)| {
66 let table = response_table(lua, status.unwrap_or(302))?;
67 table.get::<Table>("headers")?.set("Location", location)?;
68 Ok(table)
69 })?,
70 )?;
71
72 nitr.set(
73 "status",
74 lua.create_function(|lua, code: u16| response_table(lua, code))?,
75 )?;
76
77 nitr.set(
81 "sse",
82 lua.create_function(|lua, handler: Function| {
83 let table = response_table(lua, 200)?;
84 let headers = table.get::<Table>("headers")?;
85 headers.set("Content-Type", "text/event-stream")?;
86 headers.set("Cache-Control", "no-cache")?;
87
88 let body = lua.create_async_function(move |lua, writer: mlua::AnyUserData| {
89 let handler = handler.clone();
90 async move {
91 let send =
92 lua.create_async_function(move |_, (event, data): (String, Value)| {
93 let writer = writer.clone();
94 async move {
95 writer
96 .call_async_method::<()>("write", format_event(&event, data)?)
97 .await
98 }
99 })?;
100 handler.call_async::<()>(send).await
101 }
102 })?;
103 table.set("body", body)?;
104 Ok(table)
105 })?,
106 )?;
107
108 nitr.set(
109 "negotiate",
110 lua.create_async_function(|lua, (req, offers): (Value, Table)| async move {
111 negotiate(&lua, req, offers).await
112 })?,
113 )?;
114
115 nitr.set(
116 "error",
117 lua.create_function(|lua, (code, body): (u16, Option<Value>)| {
118 let table = response_table(lua, code)?;
119 match body {
120 None => {}
121 Some(Value::String(s)) => {
122 set_content_type(&table, "text/plain; charset=utf-8")?;
123 table.set("body", s)?;
124 }
125 Some(Value::Table(t)) => {
127 let t = Value::Table(t);
128 let body = crate::bounded::to_json_string(&t).into_lua_err()?;
129 set_content_type(&table, "application/json")?;
130 table.set("body", body)?;
131 }
132 Some(other) => {
133 return Err(mlua::Error::RuntimeError(format!(
134 "nitr.error body must be a string or a table, got {}",
135 other.type_name()
136 )));
137 }
138 }
139 Ok(table)
140 })?,
141 )?;
142
143 nitr.set(
151 "etag",
152 lua.create_function(|lua, (value, weak): (Value, Option<bool>)| {
153 let bytes = match &value {
154 Value::String(s) => s.as_bytes().to_vec(),
155 Value::Integer(n) => n.to_string().into_bytes(),
156 Value::Number(n) => n.to_string().into_bytes(),
157 other => crate::bounded::to_json_vec(other).into_lua_err()?,
158 };
159 let digest = <Sha256 as sha2::Digest>::digest(&bytes);
162 let tag = digest[..8].iter().fold(String::new(), |mut acc, byte| {
163 use std::fmt::Write as _;
164 let _ = write!(acc, "{byte:02x}");
165 acc
166 });
167 let prefix = if weak.unwrap_or(false) { "W/" } else { "" };
168 lua.create_string(format!("{prefix}\"{tag}\""))
169 })?,
170 )?;
171
172 let cookie = lua.create_table()?;
177 cookie.set(
178 "sign",
179 lua.create_function(|_, (name, value, secret): (String, String, String)| {
180 Ok(sign(&name, &value, &secret))
181 })?,
182 )?;
183 cookie.set(
184 "verify",
185 lua.create_function(
186 |lua, (name, signed, secret): (String, String, String)| match verify(
187 &name, &signed, &secret,
188 ) {
189 Some(value) => Ok(Value::String(lua.create_string(value)?)),
190 None => Ok(Value::Nil),
191 },
192 )?,
193 )?;
194 nitr.set("cookie", cookie)?;
195
196 Ok(())
197}
198
199fn format_event(event: &str, data: Value) -> mlua::Result<String> {
208 if event.contains(['\r', '\n']) {
209 return Err(mlua::Error::RuntimeError(
210 "an SSE event name cannot contain a line break".into(),
211 ));
212 }
213 let data = match data {
214 Value::String(s) => s.to_string_lossy().to_string(),
215 other => crate::bounded::to_json_string(&other).into_lua_err()?,
216 };
217 let mut out = format!("event: {event}\n");
218 for line in data.replace("\r\n", "\n").split(['\r', '\n']) {
219 out.push_str("data: ");
220 out.push_str(line);
221 out.push('\n');
222 }
223 out.push('\n');
224 Ok(out)
225}
226
227async fn negotiate(lua: &Lua, req: Value, offers: Table) -> mlua::Result<Value> {
231 let headers: Option<Table> = match &req {
234 Value::UserData(ud) => ud.get("headers").ok(),
235 Value::Table(t) => t.get("headers").ok(),
236 _ => None,
237 };
238 let accept = headers
239 .and_then(|h| h.get::<Option<String>>("accept").ok().flatten())
240 .unwrap_or_else(|| "*/*".to_string());
241
242 let (offered, mut values) = offer_list(&offers)?;
243
244 let offered_refs: Vec<&str> = offered.iter().map(String::as_str).collect();
245 match best_match(&accept, &offered_refs) {
246 Some(i) => match values.swap_remove(i) {
247 Value::Function(f) => f.call_async(req).await,
248 value => Ok(value),
249 },
250 None => {
251 let table = response_table(lua, 406)?;
252 set_content_type(&table, "text/plain; charset=utf-8")?;
253 table.set("body", "Not Acceptable")?;
254 Ok(Value::Table(table))
255 }
256 }
257}
258
259fn offer_list(offers: &Table) -> mlua::Result<(Vec<String>, Vec<Value>)> {
264 let mut pairs = Vec::new();
265 if offers.raw_len() > 0 {
266 for offer in offers.sequence_values::<Table>() {
267 let offer = offer?;
268 pairs.push((offer.raw_get::<String>(1)?, offer.raw_get::<Value>(2)?));
269 }
270 } else {
271 for pair in offers.pairs::<String, Value>() {
272 pairs.push(pair?);
273 }
274 pairs.sort_by(|a, b| a.0.cmp(&b.0));
275 }
276 Ok(pairs.into_iter().unzip())
277}
278
279pub fn best_match(accept: &str, offered: &[&str]) -> Option<usize> {
283 let mut best: Option<(usize, f32, u8)> = None;
285 for item in accept.split(',') {
286 let mut parts = item.trim().split(';');
287 let range = match parts.next() {
288 Some(r) if !r.trim().is_empty() => r.trim(),
289 _ => continue,
290 };
291 let mut q = 1.0_f32;
292 for param in parts {
293 if let Some(v) = param.trim().strip_prefix("q=") {
294 q = v.trim().parse().unwrap_or(0.0);
295 }
296 }
297 if q <= 0.0 {
298 continue;
299 }
300 for (i, offer) in offered.iter().enumerate() {
301 let specificity = if range.eq_ignore_ascii_case(offer) {
302 2
303 } else if range == "*/*" {
304 0
305 } else if let Some(main) = range.strip_suffix("/*") {
306 match offer.split('/').next() {
307 Some(offer_main) if offer_main.eq_ignore_ascii_case(main) => 1,
308 _ => continue,
309 }
310 } else {
311 continue;
312 };
313 let better = match best {
314 None => true,
315 Some((bi, bq, bs)) => {
316 q > bq || (q == bq && (specificity > bs || (specificity == bs && i < bi)))
317 }
318 };
319 if better {
320 best = Some((i, q, specificity));
321 }
322 }
323 }
324 best.map(|(i, _, _)| i)
325}
326
327#[cfg(test)]
328mod tests {
329 use super::*;
330
331 #[test]
334 fn sse_framing_cannot_be_broken_out_of() {
335 let lua = Lua::new();
336 let data = |s: &str| Value::String(lua.create_string(s).expect("string"));
337 assert_eq!(
338 format_event("msg", data("hi\rretry: 1\revent: admin")).expect("event"),
339 "event: msg\ndata: hi\ndata: retry: 1\ndata: event: admin\n\n"
340 );
341 assert_eq!(
342 format_event("msg", data("a\r\nb\nc")).expect("event"),
343 "event: msg\ndata: a\ndata: b\ndata: c\n\n"
344 );
345 assert!(format_event("x\nretry: 1", data("d")).is_err());
346 assert!(format_event("x\r", data("d")).is_err());
347 }
348
349 #[tokio::test]
353 async fn negotiation_ties_are_the_same_in_every_state() {
354 for _ in 0..32 {
355 let lua = Lua::new();
356 let req: Value = lua
357 .load("{ headers = { accept = '*/*' } }")
358 .eval()
359 .expect("req");
360 let map: Table = lua
361 .load("{ ['text/html'] = 'html', ['application/json'] = 'json', ['text/plain'] = 'text' }")
362 .eval()
363 .expect("offers");
364 let picked = negotiate(&lua, req.clone(), map).await.expect("negotiate");
365 assert_eq!(picked.as_string().expect("string"), "json");
366
367 let list: Table = lua
368 .load("{ { 'text/html', 'html' }, { 'application/json', 'json' } }")
369 .eval()
370 .expect("offers");
371 let picked = negotiate(&lua, req, list).await.expect("negotiate");
372 assert_eq!(picked.as_string().expect("string"), "html");
373 }
374 }
375
376 #[test]
377 fn accept_header_negotiation_honors_quality_and_wildcards() {
378 let offers = &["application/json", "text/html"];
379 assert_eq!(best_match("text/html, */*;q=0.5", offers), Some(1));
381 assert_eq!(
383 best_match("application/json;q=0.2, text/html;q=0.9", offers),
384 Some(1)
385 );
386 assert_eq!(best_match("text/*", offers), Some(1));
388 assert_eq!(best_match("*/*", offers), Some(0));
390 assert_eq!(best_match("text/html;q=0", offers), None);
392 assert_eq!(best_match("image/png", offers), None);
393 }
394}