diff --git a/apps/desktop/src-tauri/capabilities/main.json b/apps/desktop/src-tauri/capabilities/main.json index 83ad7618..300d2a21 100644 --- a/apps/desktop/src-tauri/capabilities/main.json +++ b/apps/desktop/src-tauri/capabilities/main.json @@ -45,6 +45,10 @@ "allow-notify", "allow-app-reset", "allow-update-check", - "allow-update-install" + "allow-update-install", + "allow-project-import-fastlane", + "allow-export-save", + "allow-price-sheet-pick", + "allow-project-reveal" ] } diff --git a/apps/desktop/src-tauri/permissions/autogenerated/export_save.toml b/apps/desktop/src-tauri/permissions/autogenerated/export_save.toml new file mode 100644 index 00000000..a3679030 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/export_save.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-export-save" +description = "Enables the export_save command without any pre-configured scope." +commands.allow = ["export_save"] + +[[permission]] +identifier = "deny-export-save" +description = "Denies the export_save command without any pre-configured scope." +commands.deny = ["export_save"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/price_sheet_pick.toml b/apps/desktop/src-tauri/permissions/autogenerated/price_sheet_pick.toml new file mode 100644 index 00000000..e4756f9c --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/price_sheet_pick.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-price-sheet-pick" +description = "Enables the price_sheet_pick command without any pre-configured scope." +commands.allow = ["price_sheet_pick"] + +[[permission]] +identifier = "deny-price-sheet-pick" +description = "Denies the price_sheet_pick command without any pre-configured scope." +commands.deny = ["price_sheet_pick"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/project_import_fastlane.toml b/apps/desktop/src-tauri/permissions/autogenerated/project_import_fastlane.toml new file mode 100644 index 00000000..f08245e8 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/project_import_fastlane.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-project-import-fastlane" +description = "Enables the project_import_fastlane command without any pre-configured scope." +commands.allow = ["project_import_fastlane"] + +[[permission]] +identifier = "deny-project-import-fastlane" +description = "Denies the project_import_fastlane command without any pre-configured scope." +commands.deny = ["project_import_fastlane"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/project_reveal.toml b/apps/desktop/src-tauri/permissions/autogenerated/project_reveal.toml new file mode 100644 index 00000000..3a54e056 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/project_reveal.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-project-reveal" +description = "Enables the project_reveal command without any pre-configured scope." +commands.allow = ["project_reveal"] + +[[permission]] +identifier = "deny-project-reveal" +description = "Denies the project_reveal command without any pre-configured scope." +commands.deny = ["project_reveal"] diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index 43a31b86..741eebb4 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -165,7 +165,7 @@ pub async fn sidecar_call(window: WebviewWindow, app: AppHandle, state: State<'_ if !creds.is_empty() && method != "project.inspect" { o.insert("credentials".into(), Value::Object(creds)); } - if kind == Some(Kind::Read) { + if kind == Some(Kind::Read) && !policy::NO_CACHE_METHODS.contains(&method.as_str()) { cache_project = Some(id); } } @@ -286,7 +286,7 @@ pub async fn write_with_confirm(window: WebviewWindow, app: AppHandle, state: St let job = job_of(job)?; let r = state.sidecar.get(&app).await?; let kind = r.kind(&method); - if !matches!(kind, Some(Kind::Write | Kind::Owner)) || method == "project.init" { + if !matches!(kind, Some(Kind::Write | Kind::Owner)) || policy::NEW_FOLDER_METHODS.contains(&method.as_str()) { return Err(Fail::host(format!("{method} is not a write method of an app folder"))); } let kind = kind.unwrap_or(Kind::Write); @@ -413,6 +413,128 @@ pub async fn project_init(window: WebviewWindow, app: AppHandle, state: State<'_ add_folder(&app, &state, &dir).await.map(Some) } +/// `storebound import fastlane` for a folder with a fastlane setup and no storebound config yet: native folder picker, +/// the dry run (the import plan and the report of what it does not map) in a native dialog, then the files are written +/// (fastlane stays untouched, nothing is overwritten) and the folder is added. None = cancelled at any step. +#[tauri::command] +pub async fn project_import_fastlane(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, profile: Option) -> Res> { + guard(&window)?; + if let Some(p) = &profile { + if !PROFILES.contains(&p.as_str()) { + return Err(Fail::host("profile: app, game or subscription-app")); + } + } + let Some(dir) = pick_folder(&window, "Choose the app folder that has the fastlane folder").await? else { return Ok(None) }; + if has_config(&dir) { + return Err(Fail::host("this folder already has a storebound config: add it instead")); + } + let path = dir.to_string_lossy().to_string(); + let args = match &profile { + Some(p) => json!({ "profile": p }), + None => json!({}), + }; + let r = state.sidecar.get(&app).await?; + let home = app.path().home_dir().ok().map(|h| h.to_string_lossy().to_string()); + let dry = r.call("import.fastlane", json!({ "project": path, "args": args, "dryRun": true })).await?; + if dry["ok"] != Value::Bool(true) { + return Err(Fail::host(tilde(&format!("fastlane import: {}", dialog_excerpt(dry["output"].as_str().unwrap_or_default())), home.as_deref()))); + } + let text = format!( + "Import from fastlane\n\n{path}\n\nReads the fastlane folder (Appfile, deliver and supply metadata, screenshots) and writes storebound.config.ts, the listing files and screenshot frames next to it. fastlane stays untouched and no existing file is overwritten. Keys, team ids and the App Review contact are only named, never copied.\n\nDry run:\n{}", + dialog_excerpt(dry["output"].as_str().unwrap_or_default()) + ); + if !confirm_dialog(&window, "Apply: Import from fastlane".into(), tilde(&text, home.as_deref())).await? { + return Ok(None); + } + let token = r.mint("import.fastlane", &json!({ "project": path, "args": args })).map_err(Fail::host)?; + let res = r.call("import.fastlane", json!({ "project": path, "args": args, "dryRun": false, "confirmToken": token })).await?; + if res["ok"] != Value::Bool(true) { + return Err(Fail::host(tilde(&format!("fastlane import failed: {}", dialog_excerpt(res["output"].as_str().unwrap_or_default())), home.as_deref()))); + } + if !has_config(&dir) { + return Err(Fail::host("the import wrote no storebound config")); + } + add_folder(&app, &state, &dir).await.map(Some) +} + +/// Saves an export the window made (prices CSV, listings, reviews, reports) where the owner picks in a native save +/// dialog (default: Downloads). Only text, only the known kinds, at most EXPORT_MAX_BYTES. None = cancelled; else the +/// path written, with the home folder as "~". +#[tauri::command] +pub async fn export_save(window: WebviewWindow, app: AppHandle, name: String, kind: String, content: String, personal: Option) -> Res> { + guard(&window)?; + let file = policy::export_file_name(&name, &kind).ok_or_else(|| Fail::host("export: unknown kind or empty name"))?; + if content.len() > policy::EXPORT_MAX_BYTES { + return Err(Fail::host("export: too big")); + } + // reviewer names and review texts: say where they may go before the file exists + if personal == Some(true) && !confirm_dialog_with(&window, "Personal data".into(), policy::PERSONAL_EXPORT_NOTE.into(), "Save on this computer".into()).await? { + return Ok(None); + } + let w = window.clone(); + let dir = app.path().download_dir().ok(); + let ext = kind.clone(); + let picked = tauri::async_runtime::spawn_blocking(move || { + let mut d = w.app_handle().dialog().file().set_title("Export").set_file_name(&file).add_filter(ext.to_uppercase(), &[ext.as_str()]).set_parent(&w); + if let Some(dir) = dir { + d = d.set_directory(dir); + } + d.blocking_save_file() + }) + .await + .map_err(|e| Fail::host(e.to_string()))?; + let Some(picked) = picked else { return Ok(None) }; + let path = picked.into_path().map_err(|e| Fail::host(e.to_string()))?; + std::fs::write(&path, content.as_bytes()).map_err(|e| Fail::host(format!("export: {e}")))?; + let home = app.path().home_dir().ok().map(|h| h.to_string_lossy().to_string()); + Ok(Some(tilde(&path.to_string_lossy(), home.as_deref()))) +} + +/// A price sheet (CSV) to compare with the stores, picked in a native dialog. None = cancelled. The path goes back +/// to the window only as the `csv` argument of prices.diff / owner.prices_import (both read it, neither writes it). +#[tauri::command] +pub async fn price_sheet_pick(window: WebviewWindow, state: State<'_, AppState>, project_id: String) -> Res> { + guard(&window)?; + let start = saved(&state)?.projects.iter().find(|p| p.id == project_id).map(|p| PathBuf::from(&p.path)).ok_or_else(|| Fail::host("unknown project"))?; + let w = window.clone(); + let picked = tauri::async_runtime::spawn_blocking(move || w.app_handle().dialog().file().set_title("Choose a price sheet (CSV)").add_filter("CSV", &["csv"]).set_directory(start).set_parent(&w).blocking_pick_file()) + .await + .map_err(|e| Fail::host(e.to_string()))?; + let Some(picked) = picked else { return Ok(None) }; + let p = picked.into_path().map_err(|e| Fail::host(e.to_string()))?; + if !p.extension().is_some_and(|e| e.eq_ignore_ascii_case("csv")) { + return Err(Fail::host("a price sheet is a .csv file")); + } + Ok(Some(p.to_string_lossy().to_string())) +} + +/// Shows a folder or file of an app folder in the file manager (`rel` empty: the app folder), or opens it with +/// `open` (a folder, or the gallery page storebound writes: /index.html in the default browser). +#[tauri::command] +pub fn project_reveal(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, project_id: String, rel: Option, open: Option) -> Res<()> { + guard(&window)?; + let root = saved(&state)?.projects.iter().find(|p| p.id == project_id).map(|p| PathBuf::from(&p.path)).ok_or_else(|| Fail::host("unknown project"))?; + let rel = rel.unwrap_or_default(); + let (target, relp) = if rel.is_empty() { + (root.clone(), PathBuf::new()) + } else { + let r = policy::project_relative(&rel).ok_or_else(|| Fail::host("not a path inside the app folder"))?; + (root.join(&r), r) + }; + let real = std::fs::canonicalize(&target).map_err(|_| Fail::host(format!("{rel}: not there yet")))?; + let real_root = std::fs::canonicalize(&root).map_err(|e| Fail::host(e.to_string()))?; + if !real.starts_with(&real_root) { + return Err(Fail::host("not a path inside the app folder")); + } + if open == Some(true) { + if !policy::openable(&relp, real.is_dir()) { + return Err(Fail::host("only folders and the gallery page open from here")); + } + return app.opener().open_path(real.to_string_lossy(), None::<&str>).map_err(|e| Fail::host(e.to_string())); + } + app.opener().reveal_item_in_dir(&real).map_err(|e| Fail::host(e.to_string())) +} + #[tauri::command] pub fn project_remove(window: WebviewWindow, state: State<'_, AppState>, id: String) -> Res<()> { guard(&window)?; diff --git a/apps/desktop/src-tauri/src/commands_list.rs b/apps/desktop/src-tauri/src/commands_list.rs index e7fa104e..967dd3ca 100644 --- a/apps/desktop/src-tauri/src/commands_list.rs +++ b/apps/desktop/src-tauri/src/commands_list.rs @@ -38,4 +38,8 @@ pub const COMMANDS: &[&str] = &[ "app_reset", "update_check", "update_install", + "project_import_fastlane", + "export_save", + "price_sheet_pick", + "project_reveal", ]; diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index c525d63f..c0b273cf 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -221,6 +221,10 @@ pub fn run() { commands::app_reset, commands::update_check, commands::update_install, + commands::project_import_fastlane, + commands::export_save, + commands::price_sheet_pick, + commands::project_reveal, ]) .build(tauri::generate_context!()) .expect("storebound desktop failed to start"); diff --git a/apps/desktop/src-tauri/src/policy.rs b/apps/desktop/src-tauri/src/policy.rs index 25b016ed..09b2b22b 100644 --- a/apps/desktop/src-tauri/src/policy.rs +++ b/apps/desktop/src-tauri/src/policy.rs @@ -106,6 +106,58 @@ pub fn sanitize_js_call(method: &str, kind: Option, params: &Value) -> Res Ok(Value::Object(out)) } +/// Write methods whose project is a new folder without a config (the host picks it in a native dialog and runs them +/// in its own commands: `project_init`, `project_import_fastlane`); `write_with_confirm` never runs them. +pub const NEW_FOLDER_METHODS: &[&str] = &["project.init", "import.fastlane"]; + +/// Reads that are never kept in the offline cache (big: one rendered image as a data: URL). +pub const NO_CACHE_METHODS: &[&str] = &["project.render"]; + +/// File kinds the window may export through `export_save`, with their extension. +pub const EXPORT_KINDS: &[&str] = &["csv", "md", "json", "txt"]; +/// Shown before an export with personal data (reviews: reviewer names, texts, territories) is saved. +pub const PERSONAL_EXPORT_NOTE: &str = "This file contains personal data: reviewer names, review texts and where they wrote from.\n\nKeep it on this computer (for example in the app's .storebound folder, which git ignores). Do not put it into issues, docs, chats or commits."; +/// Largest export the window may hand over (bytes of text). +pub const EXPORT_MAX_BYTES: usize = 16 * 1024 * 1024; + +/// The suggested file name of an export: letters, digits, space, dot, dash, underscore and parentheses only, at most +/// 120 characters, never hidden, always ending in the kind's extension. None for an unknown kind or an empty name. +pub fn export_file_name(name: &str, kind: &str) -> Option { + if !EXPORT_KINDS.contains(&kind) { + return None; + } + let clean: String = name + .chars() + .map(|c| if c.is_alphanumeric() || matches!(c, ' ' | '.' | '-' | '_' | '(' | ')') { c } else { '-' }) + .take(120) + .collect(); + let clean = clean.trim().trim_start_matches('.').trim().to_string(); + let ext = format!(".{kind}"); + let stem = clean.strip_suffix(&ext).unwrap_or(&clean).trim_end_matches('.').to_string(); + if stem.is_empty() { + return None; + } + Some(format!("{stem}{ext}")) +} + +/// A path inside an app folder named by the window (the renders folder, the gallery page): relative, plain +/// components only (no `..`, no root, no drive), at most 400 bytes. None otherwise. +pub fn project_relative(rel: &str) -> Option { + if rel.is_empty() || rel.len() > 400 || rel.chars().any(char::is_control) || rel.contains('\\') { + return None; + } + let p = std::path::Path::new(rel); + if p.is_absolute() || !p.components().all(|c| matches!(c, std::path::Component::Normal(_))) { + return None; + } + Some(p.to_path_buf()) +} + +/// What `project_reveal` may open (not only show in the file manager): a folder, or the gallery page storebound writes. +pub fn openable(rel: &std::path::Path, is_dir: bool) -> bool { + is_dir || rel.file_name().and_then(|n| n.to_str()) == Some("index.html") +} + /// Hosts `open_external` may open in the browser: the two store consoles and storebound's own site. pub const EXTERNAL_HOSTS: &[&str] = &[ "play.google.com", diff --git a/apps/desktop/src-tauri/tests/complete.rs b/apps/desktop/src-tauri/tests/complete.rs new file mode 100644 index 00000000..c786de8f --- /dev/null +++ b/apps/desktop/src-tauri/tests/complete.rs @@ -0,0 +1,45 @@ +//! Full CLI coverage, host side: exports only as named text files of known kinds, app-folder paths only inside the +//! folder, only folders and the gallery page open, new-folder methods and big reads stay out of the generic paths. +use std::path::Path; +use storebound_desktop::COMMANDS; +use storebound_desktop::policy::{export_file_name, openable, project_relative, NEW_FOLDER_METHODS, NO_CACHE_METHODS, PERSONAL_EXPORT_NOTE}; + +#[test] +fn export_names() { + assert_eq!(export_file_name("Prism Puddle prices 2026-10-11", "csv").as_deref(), Some("Prism Puddle prices 2026-10-11.csv")); + assert_eq!(export_file_name("x.csv", "csv").as_deref(), Some("x.csv")); + assert_eq!(export_file_name("../../etc/passwd", "md").as_deref(), Some("-..-etc-passwd.md")); + assert_eq!(export_file_name(".hidden", "txt").as_deref(), Some("hidden.txt")); + assert!(export_file_name("a", "exe").is_none()); + assert!(export_file_name("a", "html").is_none()); + assert!(export_file_name(" ", "csv").is_none()); + let long = "a".repeat(400); + assert!(export_file_name(&long, "csv").unwrap().len() <= 124); + for n in ["a/b", "a\\b", "a:b", "a\nb"] { + let f = export_file_name(n, "csv").unwrap(); + assert!(!f.contains(['/', '\\', ':', '\n']), "{f}"); + } + assert!(PERSONAL_EXPORT_NOTE.contains("personal data")); +} + +#[test] +fn app_folder_paths() { + assert!(project_relative("store/renders").is_some()); + assert!(project_relative("store/renders/index.html").is_some()); + for bad in ["", "/etc", "../x", "store/../../x", "./store", "a\\b", "a\u{0}b"] { + assert!(project_relative(bad).is_none(), "{bad}"); + } + assert!(openable(Path::new("store/renders/index.html"), false)); + assert!(openable(Path::new("store/renders"), true)); + assert!(!openable(Path::new("store/renders/run.sh"), false)); + assert!(!openable(Path::new("store/prices.csv"), false)); +} + +#[test] +fn new_folder_methods_and_big_reads() { + assert_eq!(NEW_FOLDER_METHODS, &["project.init", "import.fastlane"]); + assert_eq!(NO_CACHE_METHODS, &["project.render"]); + for c in ["project_import_fastlane", "export_save", "price_sheet_pick", "project_reveal"] { + assert!(COMMANDS.contains(&c), "{c}"); + } +}