Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(filesystem): keep the legacy file commands inside the data folder
James Damec369bb1d624
diff --git a/src-tauri/src/core/filesystem/commands.rs b/src-tauri/src/core/filesystem/commands.rsindex 2f67d4494..d0f764b37 100644--- a/src-tauri/src/core/filesystem/commands.rs+++ b/src-tauri/src/core/filesystem/commands.rs@@ -1,6 +1,8 @@// WARNING: These APIs will be deprecated soon due to removing FS API access from frontend.// It's added to ensure the legacy implementation from frontend still functions before removal.-use super::helpers::{resolve_app_path_within_jan_data_folder, resolve_path};+use super::helpers::{+ resolve_app_path_within_jan_data_folder, resolve_app_read_path, resolve_path,+};use super::models::{DialogOpenOptions, FileStat};use rfd::AsyncFileDialog;use std::fs;@@ -39,8 +41,7 @@ pub fn mkdir<R: Runtime>(app_handle: tauri::AppHandle<R>, args: Vec<String>) ->return Err("mkdir error: Invalid argument".to_string());}- let (_jan_data_folder, path) = resolve_app_path_within_jan_data_folder(app_handle, &args[0])- .map_err(|_| format!("mkdir error: path {} is not under jan data folder", args[0]))?;+ let (_, path) = resolve_app_path_within_jan_data_folder(app_handle, &args[0])?;fs::create_dir_all(&path).map_err(|e| e.to_string())}@@ -50,15 +51,8 @@ pub fn mv<R: Runtime>(app_handle: tauri::AppHandle<R>, args: Vec<String>) -> Resreturn Err("mv error: Invalid argument - source and destination required".to_string());}- let (_jan_data_folder, source) =- resolve_app_path_within_jan_data_folder(app_handle.clone(), &args[0]).map_err(|_| {- format!("mv error: source {} is not under jan data folder", args[0])- })?;- let (_jan_data_folder, destination) = resolve_app_path_within_jan_data_folder(- app_handle,- &args[1],- )- .map_err(|_| format!("mv error: destination {} is not under jan data folder", args[1]))?;+ let (_, source) = resolve_app_path_within_jan_data_folder(app_handle.clone(), &args[0])?;+ let (_, destination) = resolve_app_path_within_jan_data_folder(app_handle, &args[1])?;if !source.exists() {return Err("mv error: Source path does not exist".to_string());@@ -90,7 +84,7 @@ pub fn exists_sync<R: Runtime>(return Err("exist_sync error: Invalid argument".to_string());}- let path = resolve_path(app_handle, &args[0]);+ let path = resolve_app_read_path(app_handle, &args[0])?;Ok(path.exists())}@@ -103,7 +97,7 @@ pub fn file_stat<R: Runtime>(return Err("file_stat error: Invalid argument".to_string());}- let path = resolve_path(app_handle, &args);+ let path = resolve_app_read_path(app_handle, &args)?;let metadata = fs::metadata(&path).map_err(|e| e.to_string())?;let is_directory = metadata.is_dir();let size = if is_directory { 0 } else { metadata.len() };@@ -120,7 +114,7 @@ pub fn read_file_sync<R: Runtime>(return Err("read_file_sync error: Invalid argument".to_string());}- let path = resolve_path(app_handle, &args[0]);+ let path = resolve_app_read_path(app_handle, &args[0])?;fs::read_to_string(&path).map_err(|e| e.to_string())}@@ -133,13 +127,7 @@ pub fn write_file_sync<R: Runtime>(return Err("write_file_sync error: Invalid argument".to_string());}- let (_jan_data_folder, path) = resolve_app_path_within_jan_data_folder(app_handle, &args[0])- .map_err(|_| {- format!(- "write_file_sync error: path {} is not under jan data folder",- args[0]- )- })?;+ let (_, path) = resolve_app_path_within_jan_data_folder(app_handle, &args[0])?;let content = &args[1];fs::write(&path, content).map_err(|e| e.to_string())}@@ -153,7 +141,7 @@ pub fn readdir_sync<R: Runtime>(return Err("read_dir_sync error: Invalid argument".to_string());}- let path = resolve_path(app_handle, &args[0]);+ let path = resolve_app_read_path(app_handle, &args[0])?;let entries = fs::read_dir(&path).map_err(|e| e.to_string())?;let paths: Vec<String> = entries.filter_map(|entry| entry.ok())diff --git a/src-tauri/src/core/filesystem/helpers.rs b/src-tauri/src/core/filesystem/helpers.rsindex 928462977..8c33e4d37 100644--- a/src-tauri/src/core/filesystem/helpers.rs+++ b/src-tauri/src/core/filesystem/helpers.rs@@ -3,6 +3,9 @@ use jan_utils::{normalize_file_path, normalize_path};use std::path::{Path, PathBuf};use tauri::Runtime;+/// Builds a path string for `join_path`. It does no scope checks: the result is+/// only a string handed back to the caller, and every command that then touches+/// the file system resolves it again through one of the scoped resolvers below.pub fn resolve_path<R: Runtime>(app_handle: tauri::AppHandle<R>, path: &str) -> PathBuf {let path = if path.starts_with("file:/") || path.starts_with("file:\\") {let normalized = normalize_file_path(path);@@ -22,8 +25,12 @@ pub fn resolve_path<R: Runtime>(app_handle: tauri::AppHandle<R>, path: &str) ->}}+fn is_file_uri(path: &str) -> bool {+ path.starts_with("file:/") || path.starts_with("file:\\")+}+fn resolve_path_input(path: &str, jan_data_folder: &Path) -> PathBuf {- if path.starts_with("file:/") || path.starts_with("file:\\") {+ if is_file_uri(path) {let normalized = normalize_file_path(path);let relative_normalized = normalized.trim_start_matches(std::path::MAIN_SEPARATOR)@@ -98,6 +105,38 @@ pub fn resolve_path_within_jan_data_folder(Ok((canonical_data, canonical_path))}+/// Scope for the read-only legacy file commands (`exists_sync`, `file_stat`,+/// `read_file_sync`, `readdir_sync`).+///+/// `file:` URIs and relative paths are data-folder paths and must stay inside+/// it. A plain absolute path is let through, read-only, because the app reads+/// files the user chose wherever they live:+/// - `@path` references in the chat input, resolved against the home folder+/// or typed as absolute paths (web-app `lib/path-references.ts`);+/// - attachments and project files picked in a dialog or dropped on the window+/// (web-app `ChatInput.tsx`, `ProjectFiles.tsx`);+/// - models imported in place, whose `model_path` stays absolute (MLX reads+/// `config.json` and stats the folder; llama.cpp stats the weights).+///+/// The commands that create, move or write files never take this path; they+/// use [`resolve_path_within_jan_data_folder`].+pub fn resolve_read_path(jan_data_folder: &Path, path: &str) -> Result<PathBuf, String> {+ if is_file_uri(path) || !Path::new(path).is_absolute() {+ return resolve_path_within_jan_data_folder(jan_data_folder, path)+ .map(|(_, resolved)| resolved);+ }+ let path = PathBuf::from(path);+ Ok(path.canonicalize().unwrap_or(path))+}++pub fn resolve_app_read_path<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+ path: &str,+) -> Result<PathBuf, String> {+ let jan_data_folder = get_jan_data_folder_path(app_handle);+ resolve_read_path(&jan_data_folder, path)+}+pub fn resolve_app_path_within_jan_data_folder<R: Runtime>(app_handle: tauri::AppHandle<R>,path: &str,@@ -179,6 +218,50 @@ mod tests {assert!(result.is_err());}+ #[test]+ fn file_uri_parent_traversal_is_rejected() {+ let tmp = TempDir::new().unwrap();+ let data = tmp.path().join("data");+ fs::create_dir_all(&data).unwrap();++ for uri in ["file:/../..", "file://../outside", "file:/a/../../../outside"] {+ assert!(+ resolve_path_within_jan_data_folder(&data, uri).is_err(),+ "{uri} should be rejected"+ );+ assert!(+ resolve_read_path(&data, uri).is_err(),+ "{uri} should be rejected for reads"+ );+ }+ }++ #[test]+ fn read_path_keeps_relative_paths_inside_data_folder() {+ let tmp = TempDir::new().unwrap();+ let data = tmp.path().join("data");+ fs::create_dir_all(data.join("models")).unwrap();++ let resolved = resolve_read_path(&data, "models").expect("resolves");+ assert!(resolved.starts_with(data.canonicalize().unwrap()));+ let resolved = resolve_read_path(&data, "file://models").expect("resolves");+ assert!(resolved.ends_with("models"));+ assert!(resolve_read_path(&data, "../elsewhere").is_err());+ }++ #[test]+ fn read_path_allows_absolute_user_chosen_paths() {+ // Imported models and attachments live outside the data folder.+ let tmp = TempDir::new().unwrap();+ let data = tmp.path().join("data");+ let model = tmp.path().join("imported-model");+ fs::create_dir_all(&data).unwrap();+ fs::create_dir_all(&model).unwrap();++ let resolved = resolve_read_path(&data, &model.to_string_lossy()).expect("resolves");+ assert_eq!(resolved, model.canonicalize().unwrap());+ }+#[test]fn resolves_nonexistent_child_paths_under_data_folder() {// Used when creating new files; canonicalize must not fail.diff --git a/src-tauri/src/core/filesystem/tests.rs b/src-tauri/src/core/filesystem/tests.rsindex f02e8cb3e..4890d3f2c 100644--- a/src-tauri/src/core/filesystem/tests.rs+++ b/src-tauri/src/core/filesystem/tests.rs@@ -319,3 +319,91 @@ fn normalize_test_path(path: &Path) -> PathBuf {normalize_path(path)}++#[test]+fn test_mutating_commands_refuse_paths_outside_data_folder() {+ let app = mock_app();+ fs::create_dir_all(get_jan_data_folder_path(app.handle().clone())).unwrap();+ let outside = tempfile::tempdir().unwrap();+ let source = outside.path().join("source.txt");+ fs::write(&source, "keep").unwrap();+ let target = outside.path().join("written.txt");+ let target_dir = outside.path().join("made");++ let abs = |p: &Path| p.to_string_lossy().to_string();+ assert!(write_file_sync(app.handle().clone(), vec![abs(&target), "x".into()]).is_err());+ assert!(mkdir(app.handle().clone(), vec![abs(&target_dir)]).is_err());+ assert!(mv(+ app.handle().clone(),+ vec![abs(&source), "file://moved.txt".into()]+ )+ .is_err());+ assert!(mv(+ app.handle().clone(),+ vec!["file://does-not-matter".into(), abs(&target)]+ )+ .is_err());+ for escape in ["file:/../../escaped.txt", "file://../escaped.txt", "../escaped.txt"] {+ assert!(+ write_file_sync(app.handle().clone(), vec![escape.into(), "x".into()]).is_err(),+ "{escape} should be refused"+ );+ assert!(mkdir(app.handle().clone(), vec![escape.into()]).is_err());+ }++ assert!(!target.exists());+ assert!(!target_dir.exists());+ assert_eq!(fs::read_to_string(&source).unwrap(), "keep");+}++#[test]+fn test_write_file_sync_and_mv_inside_data_folder() {+ let app = mock_app();+ let data = get_jan_data_folder_path(app.handle().clone());+ fs::create_dir_all(&data).unwrap();+ let tmp = data.join("test_write_mv.tmp");+ let out = data.join("test_write_mv.json");++ write_file_sync(+ app.handle().clone(),+ vec![tmp.to_string_lossy().to_string(), "{}".into()],+ )+ .unwrap();+ mv(+ app.handle().clone(),+ vec![+ tmp.to_string_lossy().to_string(),+ "file://test_write_mv.json".into(),+ ],+ )+ .unwrap();+ assert_eq!(fs::read_to_string(&out).unwrap(), "{}");+ fs::remove_file(out).unwrap();+}++#[test]+fn test_read_commands_scope() {+ let app = mock_app();+ fs::create_dir_all(get_jan_data_folder_path(app.handle().clone())).unwrap();++ // file: URIs and relative paths may not leave the data folder.+ for escape in ["file:/../..", "file://../outside", "../outside"] {+ assert!(exists_sync(app.handle().clone(), vec![escape.into()]).is_err());+ assert!(file_stat(app.handle().clone(), escape.into()).is_err());+ assert!(read_file_sync(app.handle().clone(), vec![escape.into()]).is_err());+ assert!(readdir_sync(app.handle().clone(), vec![escape.into()]).is_err());+ }++ // Absolute paths the user chose (an imported model folder) stay readable.+ let model = tempfile::tempdir().unwrap();+ fs::write(model.path().join("config.json"), "{\"a\":1}").unwrap();+ let dir = model.path().to_string_lossy().to_string();+ let config = model.path().join("config.json").to_string_lossy().to_string();+ assert!(exists_sync(app.handle().clone(), vec![config.clone()]).unwrap());+ assert!(file_stat(app.handle().clone(), dir.clone()).unwrap().is_directory);+ assert_eq!(+ read_file_sync(app.handle().clone(), vec![config]).unwrap(),+ "{\"a\":1}"+ );+ assert_eq!(readdir_sync(app.handle().clone(), vec![dir]).unwrap().len(), 1);+}