tauri_plugin_compmd/
respond.rs1use std::path::{Component, Path};
5
6use tauri::http::header::{self, HeaderValue};
7use tauri::http::{Method, Request, Response, StatusCode};
8
9use crate::content_type::content_type;
10use crate::frames::{Frames, PREFIX};
11
12const HEADERS: [(&str, &str); 4] = [
14 ("content-security-policy", "sandbox allow-scripts"),
16 ("access-control-allow-origin", "*"),
18 ("x-content-type-options", "nosniff"),
19 ("cache-control", "max-age=31536000, immutable"),
21];
22
23const NOT_FRAMES: &str = "not a file of the sandbox's frames this app was built with";
25
26const ONLY_GET: &str = "the sandbox's frames are only read, with GET";
28
29impl Frames {
30 #[must_use]
32 pub fn respond(&self, request: &Request<Vec<u8>>) -> Response<Vec<u8>> {
33 if request.method() != Method::GET {
34 return refused(StatusCode::METHOD_NOT_ALLOWED, ONLY_GET);
35 }
36 let path = request.uri().path();
37 self.file(path).map_or_else(
38 || refused(StatusCode::NOT_FOUND, NOT_FRAMES),
39 |body| served(Path::new(path), body),
40 )
41 }
42
43 fn file(&self, path: &str) -> Option<Vec<u8>> {
46 let build = self.build()?;
47 let rest = path
48 .strip_prefix(PREFIX)?
49 .strip_prefix(build.hash.as_str())?
50 .strip_prefix('/')?;
51 let parts: Vec<&str> = rest.split('/').collect();
52 let plain = parts
53 .iter()
54 .all(|part| !part.is_empty() && *part != "." && *part != "..")
55 && Path::new(rest)
57 .components()
58 .all(|component| matches!(component, Component::Normal(_)));
59 if plain {
60 build.files.read(&parts)
61 } else {
62 None
63 }
64 }
65}
66
67fn served(path: &Path, body: Vec<u8>) -> Response<Vec<u8>> {
69 let mut response = with_type(StatusCode::OK, content_type(path), body);
70 let headers = response.headers_mut();
71 for (name, value) in HEADERS {
72 headers.insert(name, HeaderValue::from_static(value));
73 }
74 response
75}
76
77fn refused(status: StatusCode, why: &str) -> Response<Vec<u8>> {
79 with_type(status, "text/plain; charset=utf-8", why.as_bytes().to_vec())
80}
81
82fn with_type(status: StatusCode, kind: &'static str, body: Vec<u8>) -> Response<Vec<u8>> {
84 let mut response = Response::new(body);
85 *response.status_mut() = status;
86 response
87 .headers_mut()
88 .insert(header::CONTENT_TYPE, HeaderValue::from_static(kind));
89 response
90}
91
92#[cfg(test)]
93mod tests;