Skip to main content

tauri_plugin_compmd/
respond.rs

1//! The scheme's handler (docs/tauri-plugin.md, decision 4): the build's files with the headers that sandbox them, and
2//! a refusal, saying why, for anything else.
3
4use 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
12/// The headers every file of the frames is served with.
13const HEADERS: [(&str, &str); 4] = [
14    // Sandboxed even when a frame document is opened outside a frame.
15    ("content-security-policy", "sandbox allow-scripts"),
16    // A frame's module scripts come from an opaque origin, so they are cross-origin requests.
17    ("access-control-allow-origin", "*"),
18    ("x-content-type-options", "nosniff"),
19    // A path names its build, so what it serves never changes.
20    ("cache-control", "max-age=31536000, immutable"),
21];
22
23/// Why a request that isn't for a file of the build is refused.
24const NOT_FRAMES: &str = "not a file of the sandbox's frames this app was built with";
25
26/// Why a request with another method is refused.
27const ONLY_GET: &str = "the sandbox's frames are only read, with GET";
28
29impl Frames {
30    /// The answer to `request`: the file of the build it names, or a refusal saying why.
31    #[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    /// The bytes of the file `path` names in the build, when it names one: `/frames/<hash>/<parts>`, with no empty,
44    /// `.` or `..` part.
45    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            // A part that is a path of its own (`C:` on Windows) would leave the folder.
56            && 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
67/// `body`, the file at `path`, with its type and the frames' headers.
68fn 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
77/// A refusal with `status`, saying `why` in plain text.
78fn refused(status: StatusCode, why: &str) -> Response<Vec<u8>> {
79    with_type(status, "text/plain; charset=utf-8", why.as_bytes().to_vec())
80}
81
82/// `body` with `status` and the content type `kind`.
83fn 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;