use serde::Deserialize;
use std::{
collections::HashMap,
sync::Mutex,
time::{Duration, Instant},
};
use tauri::{
Url,
http::{Method, Request, Response},
};
use uuid::Uuid;
const PREFIX: &str = "gent-board://localhost/";
const MAX_DOCUMENT: usize = 64 * 1024;
const LOAD_TIMEOUT: Duration = Duration::from_secs(60);
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct Document {
html: String,
interactive: bool,
}
#[derive(Default)]
pub(super) struct Boards(Mutex<HashMap<Uuid, (Instant, Document)>>);
pub(super) fn identifier(url: &str) -> Option<Uuid> {
let id = url.strip_prefix(PREFIX)?;
let uuid = Uuid::parse_str(id).ok()?;
(uuid.simple().to_string() == id).then_some(uuid)
}
impl Boards {
pub(super) fn prepare(
&self,
mut document: Document,
scripts_available: bool,
) -> Result<String, &'static str> {
if document.html.is_empty() || document.html.len() > MAX_DOCUMENT {
return Err("Invalid board document size");
}
document.interactive &= scripts_available;
let mut entries = self.0.lock().expect("desktop board lock");
entries.retain(|_, (created, _)| created.elapsed() < LOAD_TIMEOUT);
let id = Uuid::new_v4();
entries.insert(id, (Instant::now(), document));
Ok(format!("{PREFIX}{}", id.simple()))
}
pub(super) fn release(&self, url: &str) {
if let Some(id) = identifier(url) {
self.0.lock().expect("desktop board lock").remove(&id);
}
}
pub(super) fn response(&self, request: &Request<Vec<u8>>) -> Response<Vec<u8>> {
let document = (request.method() == Method::GET)
.then(|| identifier(&request.uri().to_string()))
.flatten()
.and_then(|id| self.0.lock().expect("desktop board lock").remove(&id))
.filter(|(created, _)| created.elapsed() < LOAD_TIMEOUT)
.map(|(_, document)| document);
let (sandbox, scripts) = if document.as_ref().is_some_and(|d| d.interactive) {
("sandbox allow-scripts", "script-src 'unsafe-inline'")
} else {
("sandbox", "script-src 'none'")
};
let csp = format!(
"{sandbox}; default-src 'none'; {scripts}; style-src 'unsafe-inline'; img-src data:; connect-src 'none'; worker-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors tauri://localhost"
);
Response::builder()
.status(if document.is_some() { 200 } else { 404 })
.header("Content-Type", "text/html; charset=utf-8")
.header("Cache-Control", "no-store")
.header("Referrer-Policy", "no-referrer")
.header("X-DNS-Prefetch-Control", "off")
.header("X-Content-Type-Options", "nosniff")
.header("Content-Security-Policy", csp)
.body(document.map(|d| d.html.into_bytes()).unwrap_or_default())
.expect("fixed board response headers")
}
}
pub(super) fn navigation(url: &Url) -> bool {
identifier(url.as_str()).is_some()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn private_documents_are_single_use_and_have_distinct_sandbox_policies() {
for (interactive, available, scripts) in [
(true, true, true),
(false, true, false),
(true, false, false),
] {
let boards = Boards::default();
let url = boards
.prepare(
Document {
html: "<article>Local result</article>".into(),
interactive,
},
available,
)
.unwrap();
let get = Request::get(&url).body(Vec::new()).unwrap();
let response = boards.response(&get);
assert_eq!(response.status(), 200);
assert_eq!(response.headers()["Cache-Control"], "no-store");
let csp = response.headers()["Content-Security-Policy"]
.to_str()
.unwrap();
assert_eq!(csp.contains("sandbox allow-scripts"), scripts);
assert!(!csp.contains("allow-same-origin"));
assert!(csp.contains("connect-src 'none'"));
assert_eq!(boards.response(&get).status(), 404);
}
}
}