use std::path::{Path, PathBuf};
use sha2::{Digest, Sha256};
pub const PREFIX: &str = "/cad/app/";
pub const ENTRY: &str = "/cad/app/web/index.html";
pub const DEFAULT_DIR: &str = "cad-app";
pub fn safe_relative(path: &str) -> Option<PathBuf> {
if path.is_empty() || path.contains('\\') || path.contains('\0') {
return None;
}
let mut out = PathBuf::new();
for part in path.split('/') {
if part.is_empty() || part.starts_with('.') {
return None;
}
out.push(part);
}
Some(out)
}
pub fn resolve(root: &Path, path: &str) -> Option<PathBuf> {
let relative = safe_relative(path)?;
let root = root.canonicalize().ok()?;
let file = root.join(relative).canonicalize().ok()?;
(file.starts_with(&root) && file.is_file()).then_some(file)
}
pub fn media_type(path: &Path) -> &'static str {
let extension = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
match extension.as_str() {
"wasm" => "application/wasm",
"js" | "mjs" => "text/javascript; charset=utf-8",
"html" | "htm" => "text/html; charset=utf-8",
"css" => "text/css; charset=utf-8",
"json" | "map" => "application/json",
"svg" => "image/svg+xml",
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"webp" => "image/webp",
"ico" => "image/x-icon",
"woff2" => "font/woff2",
"woff" => "font/woff",
"ttf" => "font/ttf",
"otf" => "font/otf",
"txt" | "md" | "sh" | "ps1" => "text/plain; charset=utf-8",
_ => "application/octet-stream",
}
}
pub fn inline_hashes(html: &str) -> (Vec<String>, Vec<String>) {
(blocks(html, "script"), blocks(html, "style"))
}
fn blocks(html: &str, tag: &str) -> Vec<String> {
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
let lower = html.to_ascii_lowercase();
let open = format!("<{tag}");
let close = format!("</{tag}");
let mut out = Vec::new();
let mut at = 0;
while let Some(found) = lower[at..].find(&open) {
let start = at + found;
let after_name = start + open.len();
if !lower[after_name..].starts_with(|c: char| c == '>' || c.is_ascii_whitespace() || c == '/') {
at = after_name;
continue;
}
let Some(tag_end) = lower[after_name..].find('>').map(|i| after_name + i) else { break };
let attributes = &lower[after_name..tag_end];
let body_start = tag_end + 1;
let Some(body_end) = lower[body_start..].find(&close).map(|i| body_start + i) else { break };
let external = tag == "script" && attributes.split(|c: char| c.is_ascii_whitespace()).any(|a| a.starts_with("src="));
if !external {
let digest = Sha256::digest(html[body_start..body_end].as_bytes());
out.push(format!("'sha256-{}'", STANDARD.encode(digest)));
}
at = body_end + close.len();
}
out
}
pub fn policy(hashes: &(Vec<String>, Vec<String>), connect: &[String]) -> String {
let join = |extra: &[String]| extra.iter().map(|h| format!(" {h}")).collect::<String>();
format!(
"default-src 'none'; script-src 'self' 'wasm-unsafe-eval'{scripts}; \
style-src 'self'{styles}; img-src 'self' data:; connect-src 'self'{connect}; \
worker-src 'self'; font-src 'self'; manifest-src 'self'; form-action 'self'; \
frame-ancestors 'none'; base-uri 'none'",
scripts = join(&hashes.0),
styles = join(&hashes.1),
connect = join(connect),
)
}
pub fn check_connect_origin(origin: &str) -> Result<(), String> {
let Some((scheme, host)) = origin.split_once("://") else {
return Err(format!("'{origin}' is not an origin like https://gitlab.com"));
};
let good_scheme = matches!(scheme, "https" | "http" | "wss" | "ws");
let good_host = !host.is_empty()
&& host.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | ':' | '*' | '[' | ']'));
if good_scheme && good_host {
Ok(())
} else {
Err(format!("'{origin}' is not an origin like https://gitlab.com (a scheme and a host, no path)"))
}
}
pub const NATIVE: &[(&str, &str)] = &[
("linux-x86_64", "native/linux-x86_64/brep-app"),
("windows-x86_64", "native/windows-x86_64/brep-app.exe"),
];
pub const INSTALLERS: &[(&str, &str)] = &[("linux", "install/install.sh"), ("windows", "install/install.ps1")];
#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
pub struct Listed {
pub path: String,
pub size: u64,
pub sha256: String,
}
type HashCache = std::sync::Mutex<std::collections::HashMap<PathBuf, (u64, String, String)>>;
static HASHES: std::sync::OnceLock<HashCache> = std::sync::OnceLock::new();
static HASHED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
pub fn files_hashed() -> usize {
HASHED.load(std::sync::atomic::Ordering::Relaxed)
}
pub fn listed(root: &Path, relative: &str) -> Option<Listed> {
let file = resolve(root, relative)?;
let meta = std::fs::metadata(&file).ok()?;
let tag = etag(&meta);
let cache = HASHES.get_or_init(Default::default);
let cached = cache.lock().ok()?.get(&file).filter(|(_, t, _)| *t == tag).map(|(_, _, h)| h.clone());
let sha256 = match cached {
Some(hash) => hash,
None => {
let mut hasher = Sha256::new();
let mut reader = std::fs::File::open(&file).ok()?;
std::io::copy(&mut reader, &mut hasher).ok()?;
let hash = format!("{:x}", hasher.finalize());
HASHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
cache.lock().ok()?.insert(file.clone(), (meta.len(), tag, hash.clone()));
hash
}
};
Some(Listed { path: format!("{PREFIX}{relative}"), size: meta.len(), sha256 })
}
pub fn etag(meta: &std::fs::Metadata) -> String {
let modified = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_nanos())
.unwrap_or(0);
format!("\"{:x}-{:x}\"", meta.len(), modified)
}