rightkit-tauri-shell 0.4.0

Shared Tauri desktop shell for Right Suite apps: webview hardening, window state, native menu, tray, single instance, deep links, autostart, rich clipboard, watchdog and engine wiring.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Site-root serving: a second custom scheme (`<app>-site://`) that serves allowlisted
//! subresources beneath a granted site root.
//!
//! Donor: ViewRight `site_root.rs` (root inference, MIME allowlist, containment checked after
//! canonicalization, opaque per-grant tokens) and `stream_http.rs`.
//!
//! Flow: the app grants a document it already holds through the broker (the
//! `rk_shell_site_grant` command, or [`grant_document_site`]). The shell infers a site root (the
//! nearest enclosing project marker, never a filesystem root or the home directory, falling back to
//! the document's own folder), mints an opaque token and returns `<scheme>://localhost/<token>/`.
//! A document whose `<base href>` points there resolves `src`, CSS `url()`, fonts and scripts
//! natively.
//!
//! Security model:
//! * Tokens are opaque and per grant. [`PathBroker::revoke_site_root`] ends one permanently.
//! * A request is percent-decoded, refused when it carries `..`, a root or a prefix component,
//!   canonicalized, and re-checked against the canonical root, so a symlink that leaves the tree
//!   fails after resolution.
//! * Denied file names (by default the dotenv family and the npm and netrc credential files;
//!   configurable on [`SitePolicy`]) are refused as requested and again after symlink resolution.
//! * Only the MIME allowlist ([`site_mime`]) is served, with `nosniff` on every body. Page script
//!   gets no `fetch()` access to this scheme (the app's CSP decides that).
//! * A site root authorises this protocol only. It is not a file grant: the document commands
//!   still refuse any file the person did not hand to the app.

use std::path::{Component, Path, PathBuf};

use tauri::http::{header, Method, Request, Response, StatusCode};

use crate::broker::{path_to_string, PathBroker};
use crate::error::ShellError;
use crate::stream::{cors, empty, finish, method_gate_status, parse_range, ranged, read_range};

/// Directory names that mark a plausible project root when walking up from a document.
pub const ROOT_MARKERS: [&str; 3] = [".git", ".hg", ".svn"];

/// File names that mark a plausible project root when walking up from a document.
pub const ROOT_MARKER_FILES: [&str; 5] = [
    "package.json",
    "pnpm-workspace.yaml",
    "Cargo.toml",
    "go.mod",
    "pyproject.toml",
];

/// How many directory levels above the document are considered. Bounds both the stat cost of
/// inference and how far a single grant can reach.
pub const MAX_ROOT_DEPTH: usize = 12;

/// Policy for site serving: which names are refused and which extra markers mark a root.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SitePolicy {
    /// File names refused regardless of extension. Each entry is an exact name, or a prefix ending
    /// in `*`. Matching is case-insensitive against the final path component.
    pub denied_names: Vec<String>,
    /// Extra file or directory names (beside the built-in project markers) that mark a site root.
    pub root_markers: Vec<String>,
}

impl Default for SitePolicy {
    fn default() -> Self {
        // Credential and environment files a page must never be able to read back.
        let denied = [
            ".env".to_owned(),
            ".env.*".to_owned(),
            ".npmrc".to_owned(),
            ".netrc".to_owned(),
        ];
        Self {
            denied_names: denied.to_vec(),
            root_markers: Vec::new(),
        }
    }
}

impl SitePolicy {
    /// Refuse one more file name (exact, or a prefix ending in `*`).
    pub fn deny(mut self, name: &str) -> Self {
        self.denied_names.push(name.to_owned());
        self
    }

    /// Treat one more name as a root marker.
    pub fn marker(mut self, name: &str) -> Self {
        self.root_markers.push(name.to_owned());
        self
    }

    /// True when `name` is refused by the denied-name list.
    pub fn is_denied(&self, name: &str) -> bool {
        let lower = name.to_ascii_lowercase();
        self.denied_names.iter().any(|pattern| {
            let pattern = pattern.to_ascii_lowercase();
            match pattern.strip_suffix('*') {
                Some(prefix) => lower.starts_with(prefix),
                None => lower == pattern,
            }
        })
    }
}

/// MIME allowlist for site subresources. Deliberately narrow: an extension absent from this table
/// is refused (415) rather than served as `application/octet-stream`.
pub fn site_mime(ext: &str) -> Option<&'static str> {
    Some(match ext.to_ascii_lowercase().as_str() {
        "css" => "text/css",
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "gif" => "image/gif",
        "webp" => "image/webp",
        "avif" => "image/avif",
        "svg" => "image/svg+xml",
        "ico" => "image/x-icon",
        "bmp" => "image/bmp",
        "apng" => "image/apng",
        "woff" => "font/woff",
        "woff2" => "font/woff2",
        "ttf" => "font/ttf",
        "otf" => "font/otf",
        "eot" => "application/vnd.ms-fontobject",
        "wav" => "audio/wav",
        "mp3" => "audio/mpeg",
        "m4a" => "audio/mp4",
        "aac" => "audio/aac",
        "flac" => "audio/flac",
        "ogg" | "oga" => "audio/ogg",
        "webm" => "video/webm",
        "mp4" | "m4v" => "video/mp4",
        "mov" => "video/quicktime",
        "ogv" => "video/ogg",
        "vtt" => "text/vtt",
        "srt" => "application/x-subrip",
        "js" | "mjs" | "cjs" => "text/javascript",
        "json" => "application/json",
        "map" => "application/json",
        "wasm" => "application/wasm",
        _ => return None,
    })
}

/// The user's home directory, used only to refuse it as a site root.
fn home_dir() -> Option<PathBuf> {
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
        .filter(|p| !p.as_os_str().is_empty())
}

/// True when `dir` is too broad to ever be a site root: a filesystem root, a bare volume root, or
/// the user's home directory.
fn is_too_broad(dir: &Path) -> bool {
    if dir.parent().is_none() {
        return true;
    }
    let depth = dir
        .components()
        .filter(|c| matches!(c, Component::Normal(_)))
        .count();
    if depth == 0 {
        return true;
    }
    home_dir().is_some_and(|home| {
        std::fs::canonicalize(&home).is_ok_and(|home| home == dir) || home == dir
    })
}

fn has_root_marker(dir: &Path, policy: &SitePolicy) -> bool {
    ROOT_MARKERS.iter().any(|m| dir.join(m).exists())
        || policy.root_markers.iter().any(|m| dir.join(m).exists())
        || ROOT_MARKER_FILES.iter().any(|m| dir.join(m).is_file())
}

/// Infer the site root for a document: the nearest enclosing directory with a project marker,
/// searching upward at most [`MAX_ROOT_DEPTH`] levels and never returning a directory
/// [`is_too_broad`] rejects. Falls back to the document's own directory (the pre-existing
/// behaviour), so a loose HTML file grants no more than before.
pub fn infer_site_root(doc_path: &Path, policy: &SitePolicy) -> Option<PathBuf> {
    infer_site_root_report(doc_path, policy).map(|found| found.root)
}

/// The result of [`infer_site_root_report`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InferredSiteRoot {
    /// The inferred root (canonical).
    pub root: PathBuf,
    /// True when `root` is a directory that carries a project marker; false when inference found
    /// none and fell back to the document's own folder.
    pub marker_found: bool,
}

/// Like [`infer_site_root`], and also reports whether a project marker was found, so an app can
/// ask the person to confirm a fallback folder (see [`validate_chosen_site_root`]).
pub fn infer_site_root_report(doc_path: &Path, policy: &SitePolicy) -> Option<InferredSiteRoot> {
    let doc_dir = std::fs::canonicalize(doc_path.parent()?).ok()?;
    let mut candidate = doc_dir.as_path();
    for _ in 0..MAX_ROOT_DEPTH {
        if is_too_broad(candidate) {
            break;
        }
        if has_root_marker(candidate, policy) {
            return Some(InferredSiteRoot {
                root: candidate.to_path_buf(),
                marker_found: true,
            });
        }
        match candidate.parent() {
            Some(parent) => candidate = parent,
            None => break,
        }
    }
    Some(InferredSiteRoot {
        root: doc_dir,
        marker_found: false,
    })
}

/// Validate a directory the person chose as a site root (for example from a folder dialog):
/// it must exist, be a directory, and not be too broad (a filesystem or volume root, or the home
/// directory). Returns the canonical path. This is the check the shell applies to a root it
/// accepts; apps call it before [`PathBroker::grant_site_root`].
pub fn validate_chosen_site_root(dir: &Path) -> Result<PathBuf, ShellError> {
    let canonical = std::fs::canonicalize(dir)?;
    if !canonical.is_dir() {
        return Err(ShellError::Invalid("site root is not a directory".into()));
    }
    if is_too_broad(&canonical) {
        return Err(ShellError::BrokerDenied(
            "site root is too broad (a filesystem root or the home directory)".into(),
        ));
    }
    Ok(canonical)
}

/// Split a request path `/<token>/<relative path>` into `(token, percent-decoded relative path)`.
pub fn split_site_request(uri_path: &str) -> Option<(String, String)> {
    let trimmed = uri_path.trim_start_matches('/');
    let (token, rest) = trimmed.split_once('/')?;
    if token.is_empty() || rest.is_empty() {
        return None;
    }
    Some((token.to_string(), percent_decode(rest)))
}

/// Minimal percent-decoder for URL paths. An invalid escape passes through literally, so a file
/// whose name contains a bare `%` still resolves.
pub fn percent_decode(input: &str) -> String {
    let bytes = input.as_bytes();
    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok();
            if let Some(byte) = hex.and_then(|h| u8::from_str_radix(h, 16).ok()) {
                out.push(byte);
                i += 3;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// Resolve `rel` beneath `root`. Refuses `..`, root and prefix components and denied names up
/// front, then canonicalizes and re-checks containment and the denied name on the real target, so
/// a symlink pointing outside the tree (or at a denied file) fails.
pub fn resolve_in_root(root: &Path, rel: &str, policy: &SitePolicy) -> Result<PathBuf, ShellError> {
    let rel = rel.trim_start_matches('/');
    if rel.is_empty() {
        return Err(ShellError::FileNotFound("empty asset path".into()));
    }
    if rel.contains('\0') {
        return Err(ShellError::Invalid("path contains a NUL byte".into()));
    }
    let requested = Path::new(rel);
    let escapes = requested.components().any(|c| {
        matches!(
            c,
            Component::ParentDir | Component::Prefix(_) | Component::RootDir
        )
    });
    if escapes {
        return Err(ShellError::BrokerDenied(
            "asset is outside the granted site root".into(),
        ));
    }
    if requested
        .file_name()
        .and_then(|n| n.to_str())
        .is_some_and(|n| policy.is_denied(n))
    {
        return Err(ShellError::BrokerDenied("asset type is not allowed".into()));
    }
    let target = std::fs::canonicalize(root.join(requested))?;
    let root = std::fs::canonicalize(root)?;
    if !target.starts_with(&root) {
        return Err(ShellError::BrokerDenied(
            "asset is outside the granted site root".into(),
        ));
    }
    if target
        .file_name()
        .and_then(|n| n.to_str())
        .is_some_and(|n| policy.is_denied(n))
    {
        return Err(ShellError::BrokerDenied("asset type is not allowed".into()));
    }
    Ok(target)
}

/// A site grant: the opaque token and the directory it serves.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SiteGrant {
    pub token: String,
    pub root: PathBuf,
}

/// Grant the site root of a document the person already opened. The document must be a granted
/// file; its root is inferred with `policy`, and the grant covers only this protocol.
pub fn grant_document_site(
    broker: &PathBroker,
    document: &str,
    policy: &SitePolicy,
) -> Result<SiteGrant, ShellError> {
    let granted = broker.require_file(document)?;
    let root = infer_site_root(Path::new(&granted), policy)
        .ok_or_else(|| ShellError::Invalid("document has no parent directory".into()))?;
    let token = broker.grant_site_root(&root)?;
    Ok(SiteGrant {
        token,
        root: PathBuf::from(path_to_string(&root)),
    })
}

/// The base URL a document uses for a site token (`<base href>`), per platform convention.
pub fn site_base_url(scheme: &str, token: &str) -> String {
    if cfg!(windows) {
        format!("http://{scheme}.localhost/{token}/")
    } else {
        format!("{scheme}://localhost/{token}/")
    }
}

fn base_builder(status: StatusCode, mime: &str, len: u64) -> tauri::http::response::Builder {
    ranged(status, mime, len).header(header::X_CONTENT_TYPE_OPTIONS, "nosniff")
}

/// Serve one `<scheme>://localhost/<token>/<relative path>` request. Validation (token, containment,
/// denied names, MIME, stat, range) is synchronous; only the body read runs on a worker thread.
/// `respond` runs exactly once.
pub fn serve_site_request<F>(
    broker: &PathBroker,
    policy: &SitePolicy,
    request: &Request<Vec<u8>>,
    respond: F,
) where
    F: FnOnce(Response<Vec<u8>>) + Send + 'static,
{
    if let Some(status) = method_gate_status(request.method()) {
        return respond(empty(status));
    }
    let Some((token, rel)) = split_site_request(request.uri().path()) else {
        return respond(empty(StatusCode::BAD_REQUEST));
    };
    let Ok(root) = broker.resolve_site_root(&token) else {
        return respond(empty(StatusCode::FORBIDDEN));
    };
    let target = match resolve_in_root(&root, &rel, policy) {
        Ok(target) => target,
        // A policy refusal (403) stays distinct from a missing file (404) so the UI never reports
        // a containment failure as "not found".
        Err(ShellError::BrokerDenied(_)) => return respond(empty(StatusCode::FORBIDDEN)),
        Err(ShellError::Invalid(_)) => return respond(empty(StatusCode::BAD_REQUEST)),
        Err(_) => return respond(empty(StatusCode::NOT_FOUND)),
    };
    let Some(mime) = target
        .extension()
        .and_then(|e| e.to_str())
        .and_then(site_mime)
    else {
        return respond(empty(StatusCode::UNSUPPORTED_MEDIA_TYPE));
    };
    let Ok(meta) = std::fs::metadata(&target) else {
        return respond(empty(StatusCode::NOT_FOUND));
    };
    if !meta.is_file() {
        return respond(empty(StatusCode::NOT_FOUND));
    }
    let total = meta.len();
    let is_head = request.method() == Method::HEAD;

    if let Some(range_header) = request.headers().get(header::RANGE) {
        let Some((start, end)) = range_header
            .to_str()
            .ok()
            .and_then(|text| parse_range(text, total))
        else {
            return respond(finish(
                cors(StatusCode::RANGE_NOT_SATISFIABLE)
                    .header(header::CONTENT_RANGE, format!("bytes */{total}")),
                Vec::new(),
            ));
        };
        let content_range = format!("bytes {start}-{end}/{total}");
        if is_head {
            return respond(finish(
                base_builder(StatusCode::PARTIAL_CONTENT, mime, end - start + 1)
                    .header(header::CONTENT_RANGE, content_range),
                Vec::new(),
            ));
        }
        std::thread::spawn(move || {
            let response = match read_range(&target, start, end) {
                Ok(bytes) => finish(
                    base_builder(StatusCode::PARTIAL_CONTENT, mime, end - start + 1)
                        .header(header::CONTENT_RANGE, content_range),
                    bytes,
                ),
                Err(_) => empty(StatusCode::NOT_FOUND),
            };
            respond(response);
        });
        return;
    }

    if is_head {
        return respond(finish(
            base_builder(StatusCode::OK, mime, total),
            Vec::new(),
        ));
    }
    std::thread::spawn(move || {
        let response = match std::fs::read(&target) {
            Ok(bytes) => finish(base_builder(StatusCode::OK, mime, total), bytes),
            Err(_) => empty(StatusCode::NOT_FOUND),
        };
        respond(response);
    });
}