diff --git a/CLAUDE.md b/CLAUDE.md index c81c8aa..1593029 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -127,7 +127,7 @@ LICENSES/ # license texts for REUSE 3. **Profiles vs presets vs templates**: profile = channel (rarely changes), preset = game (reused across parts), template = the whole form. The field lists live in `src/config/library-fields.ts`. 4. **Tags are generated**, then trimmed to YouTube's own length count. 5. **Your data stays on your device.** localStorage is the only store; backups are files the user controls (plus automatic backups in the desktop app's data folder). -6. **The desktop webview never names a path**: Rust commands take file names under the app data folder or open the native dialog themselves. +6. **The desktop webview never names a path**: Rust commands take file names under the app data folder or open the native dialog themselves. Blocking work in an `async` command (a dialog, file I/O) goes through `tauri::async_runtime::spawn_blocking` — SonarCloud flags it otherwise (`rust:S7493`). 7. **The web app is gated** by Turnstile, verified server-side in the Worker; the gate fails open if its secret is missing. ## Development Commands diff --git a/docs/PACKAGING.md b/docs/PACKAGING.md index 231f51e..ae678fc 100644 --- a/docs/PACKAGING.md +++ b/docs/PACKAGING.md @@ -208,10 +208,10 @@ The commands: What makes them safe: - **Names, not paths.** `storage.rs` builds every path itself, under Tauri's `app_data_dir()`, from a name that must match `ytdescgen-.json` (at most 100 bytes) for backups or `ytdescgen-YYYYMMDD.jsonl` for logs. Anything else — `..`, separators, other extensions — is rejected before a path exists. -- **Dialogs run in Rust.** `file_dialog.rs` accepts only the extensions `json`, `jsonl`, `txt`, `csv` and `md`; reduces a suggested name to its file name (`../../x/backup.json` → `backup.json`); makes a saved file end in an allowed extension (`backup` → `backup.json`, `backup.exe` → `backup.exe.json`); and refuses imports over 20 MB or that are not UTF-8 (a byte-order mark is stripped). The chosen path never passes through JavaScript. On desktop the dialog is attached to the app window. +- **Dialogs run in Rust.** `file_dialog.rs` accepts only the extensions `json`, `jsonl`, `txt`, `csv` and `md`; reduces a suggested name to its file name (`../../x/backup.json` → `backup.json`); makes a saved file end in an allowed extension (`backup` → `backup.json`, `backup.exe` → `backup.exe.json`); and refuses imports over 20 MB or that are not UTF-8 (a byte-order mark is stripped). The chosen path never passes through JavaScript. On desktop the dialog is attached to the app window. Both commands are `async` and run the dialog and the file I/O through `tauri::async_runtime::spawn_blocking`: the dialogs' blocking API must stay off the main thread, and blocking work must not hold one of the async runtime's workers (SonarCloud `rust:S7493`). - **Removed in v1.0.0**: the five commands that read, wrote, appended to, listed and deleted any path the webview sent (`save_to_file`, `read_from_file`, `append_to_file`, `list_dir`, `delete_file`), and the fs and shell plugins. -Both modules have unit tests (`cargo test` in `src-tauri/`): the name rules, path rejection, backup pruning, legacy recovery, dialog filters and the import checks. +Both modules have unit tests (`cargo test` in `src-tauri/`): the name rules, path rejection, backup pruning, legacy recovery, dialog filters, writing the picked file and the import checks. ### 4. Frontend Tauri Integration diff --git a/src-tauri/src/file_dialog.rs b/src-tauri/src/file_dialog.rs index f12e9f9..3670ec4 100644 --- a/src-tauri/src/file_dialog.rs +++ b/src-tauri/src/file_dialog.rs @@ -85,6 +85,9 @@ fn dialog( /// Ask where to save, then write `content` there. Returns the file name that /// was written, or `None` when the user cancelled. +/// +/// Waiting for the dialog and writing the file both block, so they run on the +/// blocking thread pool instead of holding one of the async runtime's workers. #[tauri::command] pub async fn export_text_file( app: AppHandle, @@ -96,15 +99,29 @@ pub async fn export_text_file( title: Option, ) -> Result, String> { let filter = allowed_filter(&extensions)?; - let refs: Vec<&str> = filter.iter().map(String::as_str).collect(); - let picked = dialog(&app, &window, title) - .set_file_name(suggested_file_name(&suggested_name)) - .add_filter(filter_name, &refs) - .blocking_save_file(); - let Some(picked) = picked else { - return Ok(None); - }; - let path = with_allowed_extension(picked_path(picked)?, &filter[0]); + tauri::async_runtime::spawn_blocking(move || { + let refs: Vec<&str> = filter.iter().map(String::as_str).collect(); + let picked = dialog(&app, &window, title) + .set_file_name(suggested_file_name(&suggested_name)) + .add_filter(filter_name, &refs) + .blocking_save_file(); + match picked { + None => Ok(None), + Some(picked) => write_picked(picked, &filter[0], &content), + } + }) + .await + .map_err(|e| e.to_string())? +} + +/// Write `content` where the user chose, ending in an allowed extension, and +/// return the file name that was written. +fn write_picked( + picked: FilePath, + default_ext: &str, + content: &str, +) -> Result, String> { + let path = with_allowed_extension(picked_path(picked)?, default_ext); fs::write(&path, content).map_err(|e| e.to_string())?; Ok(path.file_name().map(|n| n.to_string_lossy().into_owned())) } @@ -141,6 +158,7 @@ fn read_picked(path: &Path, filter: &[String]) -> Result { } /// Ask for a file, then return its name and text. `None` when cancelled. +/// Runs on the blocking thread pool, like `export_text_file`. #[tauri::command] pub async fn import_text_file( app: AppHandle, @@ -150,14 +168,18 @@ pub async fn import_text_file( title: Option, ) -> Result, String> { let filter = allowed_filter(&extensions)?; - let refs: Vec<&str> = filter.iter().map(String::as_str).collect(); - let picked = dialog(&app, &window, title) - .add_filter(filter_name, &refs) - .blocking_pick_file(); - match picked { - None => Ok(None), - Some(picked) => read_picked(&picked_path(picked)?, &filter).map(Some), - } + tauri::async_runtime::spawn_blocking(move || { + let refs: Vec<&str> = filter.iter().map(String::as_str).collect(); + let picked = dialog(&app, &window, title) + .add_filter(filter_name, &refs) + .blocking_pick_file(); + match picked { + None => Ok(None), + Some(picked) => read_picked(&picked_path(picked)?, &filter).map(Some), + } + }) + .await + .map_err(|e| e.to_string())? } #[cfg(test)] @@ -204,6 +226,22 @@ mod tests { ); } + #[test] + fn writing_keeps_the_name_and_adds_an_allowed_extension() { + let dir = std::env::temp_dir().join(format!("ytdescgen-export-{}", std::process::id())); + fs::create_dir_all(&dir).unwrap(); + + let name = write_picked(FilePath::Path(dir.join("backup")), "json", "{}").unwrap(); + assert_eq!(name.as_deref(), Some("backup.json")); + assert_eq!(fs::read_to_string(dir.join("backup.json")).unwrap(), "{}"); + + let name = write_picked(FilePath::Path(dir.join("notes.MD")), "json", "# x").unwrap(); + assert_eq!(name.as_deref(), Some("notes.MD")); + assert_eq!(fs::read_to_string(dir.join("notes.MD")).unwrap(), "# x"); + + let _ = fs::remove_dir_all(&dir); + } + #[test] fn reading_checks_type_size_and_encoding() { let dir = std::env::temp_dir().join(format!("ytdescgen-dialog-{}", std::process::id()));