use std::path::{Component, Path};
use tauri::http::header::{self, HeaderValue};
use tauri::http::{Method, Request, Response, StatusCode};
use crate::content_type::content_type;
use crate::frames::{Frames, PREFIX};
const HEADERS: [(&str, &str); 4] = [
("content-security-policy", "sandbox allow-scripts"),
("access-control-allow-origin", "*"),
("x-content-type-options", "nosniff"),
("cache-control", "max-age=31536000, immutable"),
];
const NOT_FRAMES: &str = "not a file of the sandbox's frames this app was built with";
const ONLY_GET: &str = "the sandbox's frames are only read, with GET";
impl Frames {
#[must_use]
pub fn respond(&self, request: &Request<Vec<u8>>) -> Response<Vec<u8>> {
if request.method() != Method::GET {
return refused(StatusCode::METHOD_NOT_ALLOWED, ONLY_GET);
}
let path = request.uri().path();
self.file(path).map_or_else(
|| refused(StatusCode::NOT_FOUND, NOT_FRAMES),
|body| served(Path::new(path), body),
)
}
fn file(&self, path: &str) -> Option<Vec<u8>> {
let build = self.build()?;
let rest = path
.strip_prefix(PREFIX)?
.strip_prefix(build.hash.as_str())?
.strip_prefix('/')?;
let parts: Vec<&str> = rest.split('/').collect();
let plain = parts
.iter()
.all(|part| !part.is_empty() && *part != "." && *part != "..")
&& Path::new(rest)
.components()
.all(|component| matches!(component, Component::Normal(_)));
if plain {
build.files.read(&parts)
} else {
None
}
}
}
fn served(path: &Path, body: Vec<u8>) -> Response<Vec<u8>> {
let mut response = with_type(StatusCode::OK, content_type(path), body);
let headers = response.headers_mut();
for (name, value) in HEADERS {
headers.insert(name, HeaderValue::from_static(value));
}
response
}
fn refused(status: StatusCode, why: &str) -> Response<Vec<u8>> {
with_type(status, "text/plain; charset=utf-8", why.as_bytes().to_vec())
}
fn with_type(status: StatusCode, kind: &'static str, body: Vec<u8>) -> Response<Vec<u8>> {
let mut response = Response::new(body);
*response.status_mut() = status;
response
.headers_mut()
.insert(header::CONTENT_TYPE, HeaderValue::from_static(kind));
response
}
#[cfg(test)]
mod tests;