From 22f5ca3cbf45b925fabdaf12f486f6cd0661e4cd Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Fri, 27 Nov 2026 23:55:40 +0530 Subject: [PATCH] Language packs: review fixes, and plug-ins can't call proof commands - proof.installPack, proof.removePack and proof.packs {refresh} are refused under automation roots: the shared font store is outside them. - Plug-ins may not call proof.* (DENIED_PREFIXES), which plugin_call's every_command_is_reviewed requires of new commands. - A synchronous install or refresh returns its own result, not one read back from the shared errors. - proof.packs reads the jobs before the installed packs, and poll_language_packs reads busy() before the generation, so an install that ends between the reads is never missed. - A pack change measures type with a language of its own again (refresh_document_text_bounds), so selection boxes and hits follow. - The tests' Reset cancels and waits for background jobs. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/packs.rs | 24 +++++-- crates/engine/src/cmd/plugin_call.rs | 2 + crates/engine/src/packs.rs | 90 +++++++++++++------------- crates/engine/src/session/documents.rs | 2 +- crates/engine/src/store.rs | 14 +++- crates/engine/src/tests/packs.rs | 35 +++++++++- docs/mcp.md | 4 +- 7 files changed, 117 insertions(+), 54 deletions(-) diff --git a/crates/engine/src/cmd/packs.rs b/crates/engine/src/cmd/packs.rs index b90cec9c3d..9dd85a79f9 100644 --- a/crates/engine/src/cmd/packs.rs +++ b/crates/engine/src/cmd/packs.rs @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "Language Packs", [], None, - "{refresh?: bool (fetch the pinned pack index again; needs downloading on; in the desktop app it runs in the background: see refreshing)} the Language packs that spell-check and hyphenate languages other than English, shared by the Craft apps → {packs: [{locale, name, size: bytes, licence: SPDX, class, spelling: bool, hyphenation: bool, installed: bool}…] (the index fetched last; empty before the first fetch), installed: [{locale, name, licence}…] (the packs spelling and hyphenation use), installing: [{locale, done, total}…] (bytes), refreshing: bool, errors: {locale: message} (the last failure of each install or removal; \"\": of the index fetch), downloads: bool (the person allowed downloading), indexOverride: string|null (a test index used instead of the pinned one), available: bool (there is a font store folder to install into)}", + "{refresh?: bool (fetch the pinned pack index again; needs downloading on; refused under automation roots; in the desktop app it runs in the background: see refreshing)} the Language packs that spell-check and hyphenate languages other than English, shared by the Craft apps → {packs: [{locale, name, size: bytes, licence: SPDX, class, spelling: bool, hyphenation: bool, installed: bool}…] (the index fetched last; empty before the first fetch), installed: [{locale, name, licence}…] (the packs spelling and hyphenation use), installing: [{locale, done, total}…] (bytes), refreshing: bool, errors: {locale: message} (the last failure of each install or removal; \"\": of the index fetch), downloads: bool (the person allowed downloading), indexOverride: string|null (a test index used instead of the pinned one), available: bool (there is a font store folder to install into)}", always, list ), @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Install Language Pack", [], None, - "{locale: language tag (a pack's locale from proof.packs, like nl or pt-br)} downloads the pack, checks its sha256 and installs it; spelling and hyphenation in that language use it at once, in every open document. Needs downloading on, which only the person using a Craft app can turn on. Opens nothing. In the desktop app it runs in the background → {locale, started: true}: follow it with proof.packs (installing, then installed or errors); elsewhere it returns once installed → {locale, installed: true}", + "{locale: language tag (a pack's locale from proof.packs, like nl or pt-br)} downloads the pack, checks its sha256 and installs it; spelling and hyphenation in that language use it at once, in every open document. Needs downloading on, which only the person using a Craft app can turn on. Refused under automation roots (the store is outside them). Opens nothing. In the desktop app it runs in the background → {locale, started: true}: follow it with proof.packs (installing, then installed or errors); elsewhere it returns once installed → {locale, installed: true}", always, install ), @@ -34,7 +34,7 @@ pub fn specs() -> Vec { "Remove Language Pack", [], None, - "{locale} removes the installed pack (not while it installs); that language is no longer checked with it → {locale, installed: false}", + "{locale} removes the installed pack (not while it installs; refused under automation roots); that language is no longer checked with it → {locale, installed: false}", always, remove ), @@ -51,10 +51,14 @@ fn list(s: &mut Session, p: &Value) -> Result { match p.get("refresh") { None | Some(Value::Null) | Some(Value::Bool(false)) => {} Some(Value::Bool(true)) => { + not_confined(C)?; packs::refresh().map_err(EngineError::Other)?; } Some(_) => return Err(bad(C, "`refresh` must be true or false")), } + // The jobs before the installed packs: an install makes craft-proof read its pack before it + // leaves the jobs, so one that ends between the two reads is in one list or the other. + let packs::Status { installing, refreshing, errors } = packs::status(); let installed = craft_proof::packs::installed(); let backend = packs::backend(); let rows: Vec = packs::available() @@ -67,7 +71,6 @@ fn list(s: &mut Session, p: &Value) -> Result { }) }) .collect(); - let packs::Status { installing, refreshing, errors } = packs::status(); // An install that ended since the last frame shows in every document's layout. s.poll_language_packs(); Ok(json!({ @@ -82,8 +85,20 @@ fn list(s: &mut Session, p: &Value) -> Result { })) } +/// Refuses `command` for a caller confined to automation roots: the packs are written into the font +/// store the Craft apps share, which is outside them. +fn not_confined(command: &str) -> Result<()> { + if crate::file_access::current().is_some() { + return Err(EngineError::Other(format!( + "automation path rejected: {command} writes the Language packs into the font store the Craft apps share, outside the automation roots" + ))); + } + Ok(()) +} + fn install(s: &mut Session, p: &Value) -> Result { let locale = locale_param(p, "proof.installPack")?; + not_confined("proof.installPack")?; match packs::install(&locale).map_err(EngineError::Other)? { Outcome::Started => Ok(json!({"locale": locale, "started": true})), Outcome::Done => { @@ -95,6 +110,7 @@ fn install(s: &mut Session, p: &Value) -> Result { fn remove(s: &mut Session, p: &Value) -> Result { let locale = locale_param(p, "proof.removePack")?; + not_confined("proof.removePack")?; packs::remove(&locale).map_err(EngineError::Other)?; s.poll_language_packs(); Ok(json!({"locale": locale, "installed": false})) diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs index 867c1f2ff0..fc69773561 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -70,6 +70,8 @@ const DENIED_PREFIXES: &[&str] = &[ "text.rescanFonts", "text.fontList", "text.spelling.", + // Language packs: downloads into, and removals from, the font store the Craft apps share. + "proof.", "colorTheme.", "magicWand.", "eyedropper.", diff --git a/crates/engine/src/packs.rs b/crates/engine/src/packs.rs index 8ab8f2be17..fec380c1c2 100644 --- a/crates/engine/src/packs.rs +++ b/crates/engine/src/packs.rs @@ -183,17 +183,23 @@ pub enum Outcome { Started, } -/// Runs `f` on a thread of its own in the background, else here. -fn run(f: impl FnOnce() + Send + 'static) -> Result { +/// Runs `job` on a thread of its own in the background, else here and gives its own result (never +/// another call's, which the shared errors also hold). `undo` takes the job's entry back when its +/// thread can't start. +fn run(job: impl FnOnce() -> Result<(), String> + Send + 'static, undo: impl FnOnce()) -> Result { if !BACKGROUND.load(Ordering::Relaxed) { - f(); - return Ok(Outcome::Done); + return job().map(|()| Outcome::Done); + } + match std::thread::Builder::new().name("language-pack".into()).spawn(move || { + // The result is kept in the shared errors for `proof.packs`. + let _ = job(); + }) { + Ok(_) => Ok(Outcome::Started), + Err(e) => { + undo(); + Err(format!("couldn't start the download: {e}")) + } } - std::thread::Builder::new() - .name("language-pack".into()) - .spawn(f) - .map(|_| Outcome::Started) - .map_err(|e| format!("couldn't start the download: {e}")) } /// Fetches the pinned pack index again. Needs downloads on. @@ -212,22 +218,18 @@ pub fn refresh() -> Result { j.errors.remove(""); cancel }; - let outcome = run(move || { - let r = b.fetch_index(&cancel); - let mut j = jobs(); - j.refreshing = None; - if let Err(e) = r { - j.errors.insert(String::new(), e); - } - }); - if outcome.is_err() { - jobs().refreshing = None; - } - let outcome = outcome?; - match jobs().errors.get("") { - Some(e) if outcome == Outcome::Done => Err(e.clone()), - _ => Ok(outcome), - } + run( + move || { + let r = b.fetch_index(&cancel).map(|_| ()); + let mut j = jobs(); + j.refreshing = None; + if let Err(e) = &r { + j.errors.insert(String::new(), e.clone()); + } + r + }, + || jobs().refreshing = None, + ) } /// Installs the pack for `locale` (fetching the index first when it doesn't list it). Needs @@ -249,25 +251,25 @@ pub fn install(locale: &str) -> Result { cancel }; let l = locale.clone(); - let outcome = run(move || { - let r = install_now(&*b, &l, &cancel); - if r.is_ok() { - changed(); - } - let mut j = jobs(); - j.installing.remove(&l); - if let Err(e) = r { - j.errors.insert(l, e); - } - }); - if outcome.is_err() { - jobs().installing.remove(&locale); - } - let outcome = outcome?; - match jobs().errors.get(&locale) { - Some(e) if outcome == Outcome::Done => Err(e.clone()), - _ => Ok(outcome), - } + run( + move || { + let r = install_now(&*b, &l, &cancel); + // craft-proof reads the new pack before the job ends, so a caller that sees no + // install running sees the pack installed (`proof.packs`, `busy`). + if r.is_ok() { + changed(); + } + let mut j = jobs(); + j.installing.remove(&l); + if let Err(e) = &r { + j.errors.insert(l, e.clone()); + } + r + }, + || { + jobs().installing.remove(&locale); + }, + ) } fn install_now(b: &dyn Backend, locale: &str, cancel: &Cancel) -> Result<(), String> { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 2d249a7091..2ed3cd6a34 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -335,7 +335,7 @@ impl Session { /// [`Session::refresh_text_bounds`] walks them), as a change that is not an edit: a saved /// document stays saved, and its undo history keeps its documents as they are. The document is /// left as it is when `stale` picks nothing. - fn refresh_document_text_bounds(&mut self, index: usize, mut stale: impl FnMut(&TextObject) -> bool) { + pub(crate) fn refresh_document_text_bounds(&mut self, index: usize, mut stale: impl FnMut(&TextObject) -> bool) { let Some(st) = self.docs.get_mut(index) else { return }; if !text_trees(&st.doc).any(|n| has_text_where(n, &mut stale)) { return; diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index eeb730b0ac..428b88d51c 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -981,14 +981,22 @@ impl Session { pub fn poll_language_packs(&mut self) -> bool { #[cfg(not(target_arch = "wasm32"))] { + // Busy first: an install moves the generation on before it ends, so when none is + // running any more its change is read below. + let busy = crate::packs::busy(); let now = crate::packs::generation(); if now != self.packs_seen { self.packs_seen = now; - for st in &mut self.docs { - st.revision += 1; + for index in 0..self.docs.len() { + // Type in a language of its own may break its lines elsewhere now: it is + // measured again (not an edit), so its selection box and hits follow. + self.refresh_document_text_bounds(index, |t| t.runs.iter().any(|r| r.style.language.is_some())); + if let Some(st) = self.docs.get_mut(index) { + st.revision += 1; + } } } - crate::packs::busy() + busy } // The web build has no packs. #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/tests/packs.rs b/crates/engine/src/tests/packs.rs index 37825e8cd2..0218a9d39d 100644 --- a/crates/engine/src/tests/packs.rs +++ b/crates/engine/src/tests/packs.rs @@ -18,11 +18,19 @@ fn packs_lock() -> MutexGuard<'static, ()> { } /// Puts the process back to no packs and no background installs when dropped, also when the test -/// panicked, and deletes the test's folder. +/// panicked: the jobs still running are cancelled and waited for, so none outlives its test. Then +/// it deletes the test's folder. struct Reset(PathBuf); impl Drop for Reset { fn drop(&mut self) { + while packs::busy() { + for (locale, _, _) in packs::status().installing { + packs::cancel(&locale); + } + packs::cancel(""); + std::thread::yield_now(); + } packs::run_in_background(false); packs::set_backend(None); let _ = std::fs::remove_dir_all(&self.0); @@ -217,3 +225,28 @@ fn a_cancelled_background_install_installs_nothing() { assert!(installed_locales(&mut s).is_empty()); assert!(s.execute("proof.packs", &json!({})).unwrap()["errors"]["nl"].as_str().unwrap_or_default().contains("cancelled")); } + +/// A caller confined to automation roots lists the packs but can't fetch, install or remove them: +/// the store they are written into is outside its roots. +#[test] +fn a_confined_caller_lists_packs_but_cannot_change_them() { + let _turn = packs_lock(); + let root = folder("confined"); + let _reset = Reset(root.clone()); + let roots_dir = folder("confined-roots"); + std::fs::create_dir_all(&roots_dir).unwrap(); + let mut s = dutch_session(); + write_dutch_pack(&root); + packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(false) }))); + let roots = crate::file_access::AutomationRoots::new(&[roots_dir.as_path()], &[roots_dir.as_path()]).unwrap(); + let mut confined = |cmd: &str, p: Value| crate::file_access::confine(roots.as_ref(), || s.execute(cmd, &p)).map_err(|e| e.to_string()); + for (cmd, p) in + [("proof.installPack", json!({"locale": "nl"})), ("proof.removePack", json!({"locale": "nl"})), ("proof.packs", json!({"refresh": true}))] + { + let e = confined(cmd, p).unwrap_err(); + assert!(e.contains("automation path rejected"), "{cmd}: {e}"); + } + assert_eq!(confined("proof.packs", json!({})).unwrap()["installed"][0]["locale"], "nl", "listing is allowed"); + assert!(root.join("nl").join("pack.toml").exists(), "the pack is still there"); + let _ = std::fs::remove_dir_all(&roots_dir); +} diff --git a/docs/mcp.md b/docs/mcp.md index e26c2a193c..5b083aa51e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12685,7 +12685,9 @@ installed packs; the web app has none, and no `proof.*` commands. Installs and index fetches need downloading on. Only the person using a Craft app turns it on, with their own click (the setting is the font store's, shared by the apps): no command turns it on, and until then an install is an error -that says so. In the desktop app installs and fetches run in the background: `proof.installPack` returns +that says so. A caller with automation roots (`--automation-read-root`, `--automation-write-root`) can list packs +but not fetch, install or remove them, since the store is outside its roots. In the desktop app installs and fetches +run in the background: `proof.installPack` returns `{locale, started: true}` and `proof.packs` shows the install in `installing`, then in `installed` or `errors`. In `vectorcraft-cli` they return once done.