Skip to main content

braid_core/core/server/
utils.rs

1//! Server utilities for Braid protocol.
2
3use axum::response::Response;
4
5/// Escape non-ASCII characters in headers for structured header format.
6pub fn ascii_ify(s: &str) -> String {
7    let mut result = String::with_capacity(s.len());
8    for c in s.chars() {
9        let code = c as u32;
10        if (0x20..=0x7E).contains(&code) {
11            result.push(c);
12        } else {
13            result.push_str(&format!("\\u{:04x}", code));
14        }
15    }
16    result
17}
18
19/// Set permissive CORS headers on a response.
20pub fn free_cors_headers() -> Vec<(&'static str, &'static str)> {
21    vec![
22        ("access-control-allow-origin", "*"),
23        ("access-control-allow-methods", "*"),
24        ("access-control-allow-headers", "*"),
25        ("access-control-expose-headers", "*"),
26    ]
27}
28
29/// Apply permissive CORS headers to a response builder.
30pub fn apply_free_cors(response: &mut Response) {
31    let headers = response.headers_mut();
32    for (name, value) in free_cors_headers() {
33        headers.insert(
34            axum::http::header::HeaderName::from_static(name),
35            axum::http::header::HeaderValue::from_static(value),
36        );
37    }
38}
39
40/// Number of extra newlines to add for Firefox workaround.
41pub const FIREFOX_EXTRA_NEWLINES: usize = 240;