Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(agent-tools): keep screenshot windows to their own page
James Dam6a19212d81bb
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rsindex e9e85f972..3a43033c1 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs@@ -13,6 +13,7 @@ pub mod artifact;pub mod memory;pub mod permissions;pub mod preview;+pub mod screenshot_pages;pub mod skills;pub mod tools;pub mod workspace;@@ -30,7 +31,8 @@ mod webview_shot;/// Label prefix of the hidden windows the webview `screenshot` renderer opens./// The app's navigation guard keys on it: those windows load their target as a-/// `file:` URL, which no other webview may.+/// `file:` URL, which no other webview may, and only the files+/// [`screenshot_pages`] records for them.pub const SCREENSHOT_WINDOW_LABEL_PREFIX: &str = "jan-shot-";/// Runs the confined-spawn helper and exits, when this process was re-exec'd asdiff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/screenshot_pages.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/screenshot_pages.rsnew file mode 100644index 000000000..2ff26b94d--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/screenshot_pages.rs@@ -0,0 +1,147 @@+//! The files each hidden `screenshot` window may load.+//!+//! The webview renderer opens its target as a `file:` URL, and that page is+//! model-written, so it can point itself or a frame at any other file and the+//! PNG would carry it back. The renderer records each window's target here+//! before the window exists, and the app's navigation guard asks [`allows`]+//! before a screenshot window loads a `file:` URL: only the target and files+//! under its directory (its own css, images, scripts) pass.+//!+//! Tauri-free: the renderer registers, the guard in the app crate reads.+//!+//! [`allows`]: ScreenshotPages::allows++use std::collections::BTreeMap;+use std::path::{Path, PathBuf};+use std::sync::{Mutex, MutexGuard};++/// The pages of the windows the renderer has open, read by the navigation+/// guard.+pub static SCREENSHOT_PAGES: ScreenshotPages = ScreenshotPages::new();++struct Page {+ target: PathBuf,+ dir: PathBuf,+}++pub struct ScreenshotPages {+ pages: Mutex<BTreeMap<String, Page>>,+}++impl ScreenshotPages {+ pub const fn new() -> Self {+ Self {+ pages: Mutex::new(BTreeMap::new()),+ }+ }++ /// Lets the window labelled `label` load `target` and the files under its+ /// directory, both as they resolve now.+ pub fn register(&self, label: &str, target: &Path) -> Result<(), String> {+ let target = std::fs::canonicalize(target)+ .map_err(|e| format!("cannot resolve {}: {e}", target.display()))?;+ let dir = target+ .parent()+ .ok_or_else(|| format!("{} has no parent directory", target.display()))?+ .to_path_buf();+ self.lock().insert(label.to_string(), Page { target, dir });+ Ok(())+ }++ pub fn unregister(&self, label: &str) {+ self.lock().remove(label);+ }++ /// Whether the window labelled `label` may load the file at `path`.+ /// Canonicalized first, so `..` segments and symlinks are judged by where+ /// they land; a path that does not resolve to a regular file is refused.+ pub fn allows(&self, label: &str, path: &Path) -> bool {+ let Ok(canon) = std::fs::canonicalize(path) else {+ return false;+ };+ if !canon.is_file() {+ return false;+ }+ self.lock()+ .get(label)+ .is_some_and(|page| canon == page.target || canon.starts_with(&page.dir))+ }++ fn lock(&self) -> MutexGuard<'_, BTreeMap<String, Page>> {+ self.pages.lock().unwrap_or_else(|p| p.into_inner())+ }+}++impl Default for ScreenshotPages {+ fn default() -> Self {+ Self::new()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn temp_dir(tag: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!(+ "jan-shot-pages-{tag}-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0)+ ));+ std::fs::create_dir_all(dir.join("assets")).unwrap();+ std::fs::write(dir.join("chart.html"), "<svg></svg>").unwrap();+ std::fs::write(dir.join("assets/style.css"), "body{}").unwrap();+ dir+ }++ #[test]+ fn the_target_and_files_beside_it_are_allowed_for_its_window_only() {+ let dir = temp_dir("in");+ let pages = ScreenshotPages::new();+ assert!(!pages.allows("jan-shot-1", &dir.join("chart.html")));+ pages.register("jan-shot-1", &dir.join("chart.html")).unwrap();+ assert!(pages.allows("jan-shot-1", &dir.join("chart.html")));+ assert!(pages.allows("jan-shot-1", &dir.join("assets/style.css")));+ assert!(!pages.allows("jan-shot-2", &dir.join("chart.html")));+ // A directory is not a page.+ assert!(!pages.allows("jan-shot-1", &dir.join("assets")));+ pages.unregister("jan-shot-1");+ assert!(!pages.allows("jan-shot-1", &dir.join("chart.html")));+ }++ #[test]+ fn files_outside_the_target_directory_are_refused_however_spelled() {+ let dir = temp_dir("out");+ let other = temp_dir("other");+ let pages = ScreenshotPages::new();+ pages.register("jan-shot-1", &dir.join("chart.html")).unwrap();+ assert!(!pages.allows("jan-shot-1", &other.join("chart.html")));+ let escape = dir+ .join("..")+ .join(other.file_name().unwrap())+ .join("chart.html");+ assert!(!pages.allows("jan-shot-1", &escape));+ }++ #[cfg(unix)]+ #[test]+ fn a_symlink_out_of_the_target_directory_is_refused() {+ let dir = temp_dir("link");+ let other = temp_dir("secret");+ std::os::unix::fs::symlink(other.join("chart.html"), dir.join("leak.html")).unwrap();+ let pages = ScreenshotPages::new();+ pages.register("jan-shot-1", &dir.join("chart.html")).unwrap();+ assert!(!pages.allows("jan-shot-1", &dir.join("leak.html")));+ }++ #[test]+ fn registering_a_missing_target_errors() {+ let pages = ScreenshotPages::new();+ assert!(pages+ .register("jan-shot-1", Path::new("/definitely/not/here.html"))+ .is_err());+ }+}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/webview_shot.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/webview_shot.rsindex 1ca70cf52..373a3a0e3 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/webview_shot.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/webview_shot.rs@@ -71,6 +71,11 @@ async fn capture<R: Runtime>(std::process::id());+ // Before the window exists, so its first navigation already finds it.+ // Dropped after `destroy()`, and on every early return.+ crate::screenshot_pages::SCREENSHOT_PAGES.register(&label, &target)?;+ let _registered = Registered(label.clone());+let (load_tx, load_rx) = oneshot::channel::<()>();let load_signal = Arc::new(Mutex::new(Some(load_tx)));let (win_tx, win_rx) = oneshot::channel::<Result<tauri::WebviewWindow<R>, String>>();@@ -114,6 +119,15 @@ async fn capture<R: Runtime>(result}+/// Removes a window's entry from the screenshot page registry when dropped.+struct Registered(String);++impl Drop for Registered {+ fn drop(&mut self) {+ crate::screenshot_pages::SCREENSHOT_PAGES.unregister(&self.0);+ }+}+async fn capture_loaded<R: Runtime>(window: &tauri::WebviewWindow<R>,load_rx: oneshot::Receiver<()>,diff --git a/src-tauri/src/core/navigation.rs b/src-tauri/src/core/navigation.rsindex 62c967891..c981ffc18 100644--- a/src-tauri/src/core/navigation.rs+++ b/src-tauri/src/core/navigation.rs@@ -15,6 +15,7 @@ use std::time::{Duration, Instant};use tauri::plugin::{Builder, TauriPlugin};use tauri::{Manager, Runtime, Url};+use tauri_plugin_agent_tools::screenshot_pages::ScreenshotPages;use tauri_plugin_opener::OpenerExt;/// Hosts the app's own content is served from on Windows and Android, where@@ -79,11 +80,38 @@ fn is_app_url_on(url: &Url, dev_url: Option<&Url>, localhost_hosts: &[&str]) ->/// Whether the webview labelled `label` may navigate to `url`: an app URL, or,/// for the hidden windows the `screenshot` tool renders into, the `file:` page-/// it loads. Those windows match no capability, so the page gets no IPC.+/// it loads and the files under that page's directory. Those windows match no+/// capability, so the page gets no IPC.+///+/// The page is model-written, so a frame in it may name any other file; only+/// what the renderer recorded for the window passes. On Windows, WebView2+/// raises the hook for main-frame navigations alone, so there a subframe's+/// `file:` load is not checked here.pub(crate) fn allows_navigation(label: &str, url: &Url, dev_url: Option<&Url>) -> bool {+ allows_navigation_with(+ label,+ url,+ dev_url,+ &tauri_plugin_agent_tools::screenshot_pages::SCREENSHOT_PAGES,+ )+}++fn allows_navigation_with(+ label: &str,+ url: &Url,+ dev_url: Option<&Url>,+ pages: &ScreenshotPages,+) -> bool {is_app_url(url, dev_url)|| (url.scheme() == "file"- && label.starts_with(tauri_plugin_agent_tools::SCREENSHOT_WINDOW_LABEL_PREFIX))+ && is_screenshot_window(label)+ && url+ .to_file_path()+ .is_ok_and(|path| pages.allows(label, &path)))+}++fn is_screenshot_window(label: &str) -> bool {+ label.starts_with(tauri_plugin_agent_tools::SCREENSHOT_WINDOW_LABEL_PREFIX)}fn same_origin(a: &Url, b: &Url) -> bool {@@ -97,6 +125,13 @@ pub(crate) fn opens_externally(url: &Url) -> bool {matches!(url.scheme(), "http" | "https")}+/// Whether a navigation the webview labelled `label` was refused should open+/// in the system browser. Never from a screenshot window: nobody clicked+/// anything there, the page is model-written and off-screen.+fn hands_off(label: &str, url: &Url) -> bool {+ opens_externally(url) && !is_screenshot_window(label)+}+/// At most one hand-off per this window. A refused navigation is normally a/// click, but a script in a preview frame can retry one in a loop, and each try/// would otherwise open another browser tab.@@ -131,7 +166,7 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {webview.label(),url);- if opens_externally(url) && handoff_allowed(&LAST_HANDOFF, Instant::now()) {+ if hands_off(webview.label(), url) && handoff_allowed(&LAST_HANDOFF, Instant::now()) {if let Err(e) = webview.opener().open_url(url.as_str(), None::<&str>) {log::error!("Failed to open {url} in the system browser: {e}");}@@ -257,14 +292,45 @@ mod tests {assert!(!is_app_url(&u("http://localhost:1420/"), None));}- #[test]- fn only_screenshot_windows_may_load_files() {- let file = u("file:///tmp/jan-agent-s1/chart.html");- let shot = format!(+ /// A directory holding `chart.html` and `assets/style.css`, unique per call.+ fn shot_dir(tag: &str) -> std::path::PathBuf {+ let dir = std::env::temp_dir().join(format!(+ "jan-nav-{tag}-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0)+ ));+ std::fs::create_dir_all(dir.join("assets")).unwrap();+ std::fs::write(dir.join("chart.html"), "<svg></svg>").unwrap();+ std::fs::write(dir.join("assets/style.css"), "body{}").unwrap();+ dir+ }++ fn file_url(p: &std::path::Path) -> Url {+ Url::from_file_path(p).unwrap()+ }++ fn shot_label() -> String {+ format!("{}4242-1700000000",tauri_plugin_agent_tools::SCREENSHOT_WINDOW_LABEL_PREFIX- );- assert!(allows_navigation(&shot, &file, None));+ )+ }++ #[test]+ fn a_screenshot_window_may_load_its_target_and_files_beside_it() {+ let dir = shot_dir("target");+ let pages = ScreenshotPages::new();+ let shot = shot_label();+ let target = file_url(&dir.join("chart.html"));+ // Nothing recorded for the window yet.+ assert!(!allows_navigation_with(&shot, &target, None, &pages));+ pages.register(&shot, &dir.join("chart.html")).unwrap();+ assert!(allows_navigation_with(&shot, &target, None, &pages));+ let sibling = file_url(&dir.join("assets/style.css"));+ assert!(allows_navigation_with(&shot, &sibling, None, &pages));for label in ["main","logs-app-window",@@ -272,15 +338,73 @@ mod tests {"jan-shot","x-jan-shot-1",] {- assert!(!allows_navigation(label, &file, None), "{label}");+ assert!(+ !allows_navigation_with(label, &target, None, &pages),+ "{label}"+ );+ }+ }++ #[test]+ fn a_screenshot_window_may_not_load_other_files() {+ let dir = shot_dir("own");+ let secret = shot_dir("ssh");+ std::fs::write(secret.join("id_rsa"), "key").unwrap();+ let pages = ScreenshotPages::new();+ let shot = shot_label();+ pages.register(&shot, &dir.join("chart.html")).unwrap();+ assert!(!allows_navigation_with(+ &shot,+ &file_url(&secret.join("id_rsa")),+ None,+ &pages+ ));+ let home = std::env::var_os("HOME").map(std::path::PathBuf::from);+ if let Some(home) = home {+ let key = file_url(&home.join(".ssh/id_rsa"));+ assert!(!allows_navigation_with(&shot, &key, None, &pages));}+ assert!(!allows_navigation_with(+ &shot,+ &u("file:///etc/passwd"),+ None,+ &pages+ ));+ // `..` out of the target's directory, spelled in the URL.+ let escape = Url::parse(&format!(+ "{}/../{}/id_rsa",+ file_url(&dir).as_str().trim_end_matches('/'),+ secret.file_name().unwrap().to_string_lossy()+ ))+ .unwrap();+ assert!(!allows_navigation_with(&shot, &escape, None, &pages));// The exception is `file:` alone: a screenshot window is otherwise// held to the app's origins like any other.- assert!(!allows_navigation(&shot, &u("https://evil.example/"), None));- assert!(!allows_navigation(&shot, &u("asset://localhost/x"), None));+ assert!(!allows_navigation_with(+ &shot,+ &u("https://evil.example/"),+ None,+ &pages+ ));+ assert!(!allows_navigation_with(+ &shot,+ &u("asset://localhost/x"),+ None,+ &pages+ ));assert!(allows_navigation("main", &u("tauri://localhost/"), None));}+ #[test]+ fn a_screenshot_window_never_hands_off_to_the_browser() {+ let shot = shot_label();+ let web = u("https://evil.example/");+ assert!(!allows_navigation(&shot, &web, None));+ assert!(!hands_off(&shot, &web));+ assert!(!hands_off(&shot, &u("http://example.com/")));+ assert!(hands_off("main", &web));+ }+#[test]fn only_web_urls_are_handed_to_the_browser() {assert!(opens_externally(&u("https://jan.ai/docs")));