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
//! Path broker: the renderer never names a file the user did not hand to the app.
//!
//! Donor: ViewRight `path_broker.rs` (granted file set, save-target grants with a bounded
//! write-target ring, one-shot recent-file tokens, stable per-file stream tokens, per-tab site
//! roots). Differences from the donor: errors are [`ShellError`] values, random ids come straight
//! from the OS entropy call with no extra crate, and the broker is a plain type any app can embed.
//!
//! Grants are made by Rust code (a file dialog result, a drag-drop, the launch argv, a recent-files
//! table). The renderer can only *use* grants: check a path, mint a stream id for a granted file,
//! trade a one-shot recent id. Nothing here lets the renderer grant an arbitrary path.

use std::collections::{HashMap, HashSet, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::Mutex;

use crate::error::ShellError;

/// Upper bound on live recent-file ids. Old ones are disposable (the renderer re-lists).
pub const KNOWN_TOKEN_CAP: usize = 256;
/// Ring of recently written save targets that `regrant_saved_target` may re-grant.
pub const WRITE_TARGET_RING_CAP: usize = 8;

#[derive(Default)]
struct KnownTokens {
    map: HashMap<String, PathBuf>,
    order: VecDeque<String>,
}

#[derive(Default)]
pub struct PathBroker {
    allowed: Mutex<HashSet<PathBuf>>,
    known: Mutex<KnownTokens>,
    stream_tokens: Mutex<HashMap<String, PathBuf>>,
    site_roots: Mutex<HashMap<String, PathBuf>>,
    recent_writes: Mutex<VecDeque<PathBuf>>,
    /// Name used in denial text ("through {name} first"); empty reads as "the app".
    app_name: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StreamTarget {
    pub path: PathBuf,
}

fn poisoned<T>(_: T) -> ShellError {
    ShellError::Other("path broker lock poisoned".into())
}

/// Display form of a normalised path (drops the Windows verbatim prefix).
pub fn path_to_string(path: &Path) -> String {
    let raw = path.to_string_lossy();
    #[cfg(windows)]
    {
        if let Some(stripped) = raw.strip_prefix(r"\\?\UNC\") {
            return format!(r"\\{stripped}");
        }
        if let Some(stripped) = raw.strip_prefix(r"\\?\") {
            return stripped.to_string();
        }
    }
    raw.into_owned()
}

fn display_matches(path: &Path, display: &str) -> bool {
    let normalized = path_to_string(path);
    // Windows and macOS volumes are case-insensitive by default, so a differently-cased display
    // string must still match (a deleted file cannot be re-resolved to its true case).
    #[cfg(any(windows, target_os = "macos"))]
    {
        normalized.to_lowercase() == display.to_lowercase()
    }
    #[cfg(not(any(windows, target_os = "macos")))]
    {
        normalized == display
    }
}

pub fn normalize_existing_file(path: impl AsRef<Path>) -> Result<PathBuf, ShellError> {
    let path = path.as_ref();
    let meta = std::fs::metadata(path)?;
    if !meta.is_file() {
        return Err(ShellError::FileNotFound("path is not a file".into()));
    }
    Ok(std::fs::canonicalize(path)?)
}

/// Canonical form of a path that may not exist yet (a save target): the parent must exist.
pub fn normalize_write_target(path: impl AsRef<Path>) -> Result<PathBuf, ShellError> {
    let path = path.as_ref();
    if path.as_os_str().is_empty() {
        return Err(ShellError::Invalid("empty path".into()));
    }
    if let Ok(meta) = std::fs::metadata(path) {
        if meta.is_dir() {
            return Err(ShellError::Invalid("path is a directory".into()));
        }
        return Ok(std::fs::canonicalize(path)?);
    }
    let parent = path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));
    let parent = std::fs::canonicalize(parent)?;
    let name = path
        .file_name()
        .ok_or_else(|| ShellError::Invalid("path has no file name".into()))?;
    Ok(parent.join(name))
}

#[cfg(unix)]
fn fill_entropy(buf: &mut [u8]) -> std::io::Result<()> {
    extern "C" {
        fn getentropy(buf: *mut std::ffi::c_void, len: usize) -> std::ffi::c_int;
    }
    // SAFETY: `buf` is a valid writable slice of at most 256 bytes.
    if unsafe { getentropy(buf.as_mut_ptr().cast(), buf.len()) } == 0 {
        Ok(())
    } else {
        Err(std::io::Error::last_os_error())
    }
}

#[cfg(windows)]
fn fill_entropy(buf: &mut [u8]) -> std::io::Result<()> {
    #[link(name = "advapi32")]
    extern "system" {
        #[link_name = "SystemFunction036"]
        fn RtlGenRandom(buf: *mut u8, len: u32) -> u8;
    }
    // SAFETY: `buf` is a valid writable slice for `len` bytes.
    if unsafe { RtlGenRandom(buf.as_mut_ptr(), buf.len() as u32) } != 0 {
        Ok(())
    } else {
        Err(std::io::Error::last_os_error())
    }
}

fn random_id(prefix: &str) -> Result<String, ShellError> {
    let mut bytes = [0_u8; 16];
    fill_entropy(&mut bytes)
        .map_err(|e| ShellError::Other(format!("entropy source unavailable: {e}")))?;
    let mut id = String::with_capacity(prefix.len() + 32);
    id.push_str(prefix);
    for b in bytes {
        use std::fmt::Write;
        let _ = write!(id, "{b:02x}");
    }
    Ok(id)
}

fn mint_unique<V>(map: &HashMap<String, V>, prefix: &str) -> Result<String, ShellError> {
    loop {
        let t = random_id(prefix)?;
        if !map.contains_key(&t) {
            return Ok(t);
        }
    }
}

/// Strip the macOS quarantine attribute from a file the user explicitly chose to open, so
/// Gatekeeper does not block later opens. Best effort; in-process `removexattr`, no fork.
#[cfg(target_os = "macos")]
fn clear_quarantine(path: &Path) {
    use std::os::unix::ffi::OsStrExt;
    extern "C" {
        fn removexattr(
            path: *const std::ffi::c_char,
            name: *const std::ffi::c_char,
            options: i32,
        ) -> i32;
    }
    const XATTR_NOFOLLOW: i32 = 0x0001;
    let Ok(p) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
        return;
    };
    // SAFETY: both pointers are valid NUL-terminated strings for the duration of the call; the
    // result (ENOATTR when the file was never quarantined) is intentionally ignored.
    unsafe {
        removexattr(p.as_ptr(), c"com.apple.quarantine".as_ptr(), XATTR_NOFOLLOW);
    }
}

impl PathBroker {
    pub fn new() -> Self {
        Self::default()
    }

    /// A broker whose denial text names the app ("open it through {app_name} first"), taken from
    /// the shell's `app_name` config. An empty name reads as "the app".
    pub fn with_app_name(app_name: &str) -> Self {
        Self {
            app_name: app_name.trim().to_owned(),
            ..Self::default()
        }
    }

    fn app(&self) -> &str {
        if self.app_name.is_empty() {
            "the app"
        } else {
            &self.app_name
        }
    }

    /// Grant an existing file the user chose. Returns the display path.
    pub fn grant_file(&self, path: impl AsRef<Path>) -> Result<String, ShellError> {
        let normalized = normalize_existing_file(path)?;
        #[cfg(target_os = "macos")]
        clear_quarantine(&normalized);
        self.grant_normalized(normalized)
    }

    /// Grant a path the user picked in a save dialog (it need not exist).
    pub fn grant_save_target(&self, path: impl AsRef<Path>) -> Result<String, ShellError> {
        self.grant_normalized(normalize_write_target(path)?)
    }

    pub fn grant_normalized(&self, path: PathBuf) -> Result<String, ShellError> {
        let display = path_to_string(&path);
        self.allowed.lock().map_err(poisoned)?.insert(path);
        Ok(display)
    }

    pub fn is_granted_normalized(&self, path: &Path) -> Result<bool, ShellError> {
        Ok(self.allowed.lock().map_err(poisoned)?.contains(path))
    }

    /// Canonicalise `path` and require it to be a granted existing file.
    pub fn require_file(&self, path: &str) -> Result<String, ShellError> {
        let normalized = normalize_existing_file(path)?;
        if self.is_granted_normalized(&normalized)? {
            Ok(path_to_string(&normalized))
        } else {
            Err(ShellError::BrokerDenied(format!(
                "path is not authorized; open it through {} first",
                self.app()
            )))
        }
    }

    pub fn require_write_target(&self, path: &str) -> Result<String, ShellError> {
        let normalized = normalize_write_target(path)?;
        if self.is_granted_normalized(&normalized)? {
            Ok(path_to_string(&normalized))
        } else {
            Err(ShellError::BrokerDenied(format!(
                "path is not authorized; choose it through {} first",
                self.app()
            )))
        }
    }

    /// Record a path the app just wrote; evicts the oldest past [`WRITE_TARGET_RING_CAP`].
    pub fn record_write_target(&self, path: &Path) -> Result<(), ShellError> {
        let mut ring = self.recent_writes.lock().map_err(poisoned)?;
        ring.retain(|p| p != path);
        ring.push_back(path.to_path_buf());
        while ring.len() > WRITE_TARGET_RING_CAP {
            ring.pop_front();
        }
        Ok(())
    }

    pub fn was_recently_written(&self, path: &Path) -> Result<bool, ShellError> {
        Ok(self
            .recent_writes
            .lock()
            .map_err(poisoned)?
            .iter()
            .any(|p| p == path))
    }

    /// Re-grant a save-as target that was just written (so the renderer cannot ask for any
    /// existing path to be granted).
    pub fn regrant_saved_target(&self, path: &str) -> Result<String, ShellError> {
        let normalized = normalize_write_target(path)?;
        if !self.was_recently_written(&normalized)? {
            return Err(ShellError::BrokerDenied(format!(
                "path was not just written by the app; save it through {} first",
                self.app()
            )));
        }
        self.grant_normalized(normalized)
    }

    /// Mint a one-shot recent-file id for a stored path (re-canonicalised: older rows or platform
    /// spelling differences must not grant something later checks reject).
    pub fn register_known_path(&self, path: &str) -> Result<String, ShellError> {
        let normalized = normalize_existing_file(path)?;
        let mut known = self.known.lock().map_err(poisoned)?;
        let id = mint_unique(&known.map, "known:")?;
        known.map.insert(id.clone(), normalized);
        known.order.push_back(id.clone());
        while known.order.len() > KNOWN_TOKEN_CAP {
            if let Some(old) = known.order.pop_front() {
                known.map.remove(&old);
            }
        }
        Ok(id)
    }

    /// Trade a recent-file id for a grant. One shot: replaying it fails.
    pub fn grant_known(&self, id: &str) -> Result<String, ShellError> {
        let normalized = self
            .known
            .lock()
            .map_err(poisoned)?
            .map
            .remove(id)
            .ok_or_else(|| {
                ShellError::BrokerDenied("unknown or already-used recent-file id".into())
            })?;
        self.grant_normalized(normalized)
    }

    /// Revoke a grant (its last tab closed) and every stream id for that file, so old stream URLs
    /// die now and never revive on reopen. Matches by display string, so a file deleted after
    /// opening is still revoked.
    pub fn revoke_path(&self, display: &str) -> Result<(), ShellError> {
        let mut revoked = Vec::new();
        self.allowed.lock().map_err(poisoned)?.retain(|p| {
            let keep = !display_matches(p, display);
            if !keep {
                revoked.push(p.clone());
            }
            keep
        });
        if !revoked.is_empty() {
            self.stream_tokens
                .lock()
                .map_err(poisoned)?
                .retain(|_, p| !revoked.iter().any(|r| r == p));
        }
        Ok(())
    }

    /// Opaque URL id for a granted file. One stable live id per file: re-reading after an atomic
    /// edit overlaps in-flight range requests, and rotating would 403 the URL still loading.
    pub fn grant_stream(&self, path: &str) -> Result<String, ShellError> {
        let normalized = normalize_existing_file(path)?;
        let allowed = self.allowed.lock().map_err(poisoned)?;
        if !allowed.contains(&normalized) {
            return Err(ShellError::BrokerDenied(format!(
                "path is not authorized; open it through {} first",
                self.app()
            )));
        }
        let mut streams = self.stream_tokens.lock().map_err(poisoned)?;
        if let Some((id, _)) = streams.iter().find(|(_, p)| *p == &normalized) {
            return Ok(id.clone());
        }
        let id = mint_unique(&streams, "stream-")?;
        streams.insert(id.clone(), normalized);
        Ok(id)
    }

    pub fn resolve_stream(&self, id: &str) -> Result<StreamTarget, ShellError> {
        let path = self
            .stream_tokens
            .lock()
            .map_err(poisoned)?
            .get(id)
            .cloned()
            .ok_or_else(|| ShellError::BrokerDenied("unknown or revoked stream id".into()))?;
        Ok(StreamTarget { path })
    }

    /// Opaque id for a directory the preview may read subresources from. Authorises only
    /// containment-checked reads through [`PathBroker::resolve_in_site_root`], never general
    /// document access. One id per grant (not deduplicated by directory) so two tabs on the same
    /// project do not revoke each other.
    pub fn grant_site_root(&self, dir: impl AsRef<Path>) -> Result<String, ShellError> {
        let dir = std::fs::canonicalize(dir.as_ref())?;
        if !dir.is_dir() {
            return Err(ShellError::Invalid("site root is not a directory".into()));
        }
        let mut roots = self.site_roots.lock().map_err(poisoned)?;
        let id = mint_unique(&roots, "site-")?;
        roots.insert(id.clone(), dir);
        Ok(id)
    }

    pub fn resolve_site_root(&self, id: &str) -> Result<PathBuf, ShellError> {
        self.site_roots
            .lock()
            .map_err(poisoned)?
            .get(id)
            .cloned()
            .ok_or_else(|| ShellError::BrokerDenied("unknown or revoked site root id".into()))
    }

    /// Resolve `relative` under a site root; refuses anything that escapes it (`..`, symlinks).
    pub fn resolve_in_site_root(&self, id: &str, relative: &str) -> Result<PathBuf, ShellError> {
        let root = self.resolve_site_root(id)?;
        let rel = relative.trim_start_matches('/');
        let escapes = rel.contains('\0')
            || Path::new(rel).components().any(|c| {
                matches!(
                    c,
                    std::path::Component::ParentDir
                        | std::path::Component::Prefix(_)
                        | std::path::Component::RootDir
                )
            });
        if escapes {
            return Err(ShellError::BrokerDenied(
                "path escapes the site root".into(),
            ));
        }
        let full = std::fs::canonicalize(root.join(rel))?;
        if !full.starts_with(&root) {
            return Err(ShellError::BrokerDenied(
                "path escapes the site root".into(),
            ));
        }
        Ok(full)
    }

    pub fn revoke_site_root(&self, id: &str) -> Result<(), ShellError> {
        self.site_roots.lock().map_err(poisoned)?.remove(id);
        Ok(())
    }
}