From 9758ece7efae40e3b7cd20e537b3abb8f4962afc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:07:34 -0800 Subject: [PATCH 1/6] Scripts: vc.run export of an open document reads its own linked files A command a script runs with vc.run could read only the script's own places and the open documents' own files, so an export, save, print or package of a document whose linked images or placed files sit elsewhere fell back to the saved previews. The script gate now also reads, and never writes, the files that the documents open when the run began link to: linked images, placed files, the plate files of a DCS image and the images their data sets name. The list is taken once, at the run's first vc.run, from those documents as they were when the run began, and holds real paths, so a path that leads to another file later is refused. A link the script adds or re-points, a path it names itself and a document it opens give it no further file to read, a document it opens from one of these files is not saved over it, and the automation read roots and the name and traversal rules still apply first. --- crates/engine/src/cmd/links.rs | 29 +++++- crates/engine/src/file_access.rs | 128 ++++++++++++++++++++++++-- crates/engine/src/script/files.rs | 15 +-- crates/engine/src/script/mod.rs | 40 +++++++- crates/engine/src/tests/script_run.rs | 62 +++++++++++++ docs/mcp.md | 7 ++ docs/target-app-parity.md | 3 +- 7 files changed, 267 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index fccff66c0c..9f1e7c3d79 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -328,7 +328,12 @@ impl<'a> LinkBase<'a> { /// The open document `st`'s. One with no file of its own looks beside the file it was read from. pub(crate) fn of(st: &'a crate::DocState) -> Self { - let (path, from) = (st.path.as_deref(), st.links_from.as_deref()); + Self::of_files(st.path.as_deref(), st.links_from.as_deref()) + } + + /// An open document's, by its own file `path` and the file it was read from, `from` + /// ([`crate::DocState::links_from`]), as [`Self::of`] gives them. + pub(crate) fn of_files(path: Option<&'a str>, from: Option<&'a str>) -> Self { Self { doc: path.or(from), relative: from.or(path) } } } @@ -401,6 +406,28 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option { Some(f) } +/// The files the links of `d` (a document looking from `base`) lead to now: where [`locate`] +/// finds each linked image's and placed document's file from `base` and from no document (as +/// output reads them, [`full_linked_images`]), the plate files of their own of images placed from +/// DCS files, and the image files its data sets name. The commands a script runs may read these +/// for the documents open when the run began ([`crate::file_access::ScriptGate::linked`]). +pub(crate) fn files_linked(d: &Document, base: LinkBase) -> Vec { + let mut out = vec![]; + for g in groups(d, None) { + for from in [base, LinkBase::default()] { + let Some(f) = locate(&g.link, from) else { continue }; + out.extend(g.plate_files.iter().filter_map(|p| super::place::dcs::plate_file_path(&f.path, &p.name))); + out.push(f.path); + } + } + let values = d.variables.datasets.iter().flat_map(|set| set.values.values()); + out.extend(values.filter_map(|v| match v { + DataValue::Image(path) => fileio::document_path(path, base.doc).ok(), + _ => None, + })); + out +} + /// The place `stored` names from the file `from`, as `resolve` ([`fileio::document_path`]) follows /// it, when it also follows that place from the document's own file `doc`: a network share the /// document is no longer on is refused. diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c5ecee374e..525094a990 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -27,7 +27,8 @@ //! [`ScriptScope`] holds the folders a running script's own files (its includes and `$.evalFile`) //! are read from, and the places its `File` and `Folder` objects read and write, inside the roots. //! [`ScriptGate`] holds the same places for the commands the script runs with `vc.run`, with the -//! files of the open documents. +//! files of the open documents, and for reading, the files the documents open when the run began +//! link to. use std::cell::RefCell; use std::ffi::OsString; @@ -276,19 +277,53 @@ impl ScopeHandle { /// What a command a running script runs (`vc.run`) may read and write: the places the script's /// `File` and `Folder` objects may ([`ScriptScope`]), and the files the documents open in the app -/// were opened from or saved to. The automation roots apply as well. A path refused by its name -/// alone ([`ScriptScope::refused_by_name`]) is refused here too. +/// were opened from or saved to. Reading, and only reading, the files the documents open when the +/// run began link to is allowed as well ([`ScriptGate::linked`]). The automation roots apply as +/// well. A path refused by its name alone ([`ScriptScope::refused_by_name`]) is refused here too. #[derive(Clone, Debug)] pub(crate) struct ScriptGate { pub(crate) read: ScriptScope, pub(crate) write: ScriptScope, /// The paths of the open documents' files, as the documents hold them. pub(crate) documents: Vec, + /// The real paths of the files the documents open when the run began link to, as they were + /// when the run's first command was run ([`ScriptGate::real_files`]): readable, not writable. + /// A path that leads to another file now is not one of them. + pub(crate) linked: Arc<[PathBuf]>, /// Another gate a path must pass as well ([`ScopeHandle::within_current`]). pub(crate) also: Option>, } impl ScriptGate { + /// The real paths of the files at `paths` that are files now, each once, for + /// [`ScriptGate::linked`]. A path refused by its name alone, and one that cannot be resolved, + /// is left out. + pub(crate) fn real_files(paths: impl IntoIterator) -> Arc<[PathBuf]> { + let mut real: Vec = paths + .into_iter() + .filter(|p| !ScriptScope::refused_by_name(Path::new(p))) + .filter_map(|p| resolve(&p).ok()) + .filter(|p| p.is_file()) + .collect(); + real.sort(); + real.dedup(); + real.into() + } + + /// This gate without the documents whose files only [`ScriptGate::linked`] lets it read, unless + /// they are among `before`, the files of the documents open when the run began: a document the + /// run opened from such a file is read, never written. + pub(crate) fn keeping_linked_read_only(mut self, before: &[String]) -> Self { + let plain = ScriptGate { documents: vec![], linked: Arc::new([]), also: None, ..self.clone() }; + let linked = self.linked.clone(); + let only_linked = |d: &String| { + let real = if ScriptScope::refused_by_name(Path::new(d)) { None } else { resolve(d).ok() }; + real.is_some_and(|real| linked.binary_search(&real).is_ok()) && plain.check(d, Access::Read).is_err() + }; + self.documents.retain(|d| before.contains(d) || !only_linked(d)); + self + } + /// This gate with `next` at the end of its chain of `also` gates, so a path must pass every /// gate already in the chain as well as `next`. fn followed_by(&self, next: Arc) -> ScriptGate { @@ -307,7 +342,7 @@ impl ScriptGate { let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() }; let allowed = real.is_some_and(|real| { let scoped = match access { - Access::Read => self.read.allows(&real) || self.write.allows(&real), + Access::Read => self.read.allows(&real) || self.write.allows(&real) || self.linked.binary_search(&real).is_ok(), Access::Write => self.write.allows(&real), }; scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) @@ -918,8 +953,13 @@ mod tests { #[test] fn a_narrowed_scope_keeps_the_script_gates_of_both() { let (base, _) = folders("narrowed-gate"); - let gate = - |dir: &str| ScriptGate { read: ScriptScope::of_folder(&base.join(dir)), write: ScriptScope::default(), documents: vec![], also: None }; + let gate = |dir: &str| ScriptGate { + read: ScriptScope::of_folder(&base.join(dir)), + write: ScriptScope::default(), + documents: vec![], + linked: Arc::new([]), + also: None, + }; let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); let reads = |saved: ScopeHandle, gate_here: Option| { let narrowed = match gate_here { @@ -942,7 +982,13 @@ mod tests { #[test] fn a_scope_narrowed_several_times_keeps_every_gate() { let (base, _) = folders("narrowed-thrice"); - let gate = |dir: &Path| ScriptGate { read: ScriptScope::of_folder(dir), write: ScriptScope::default(), documents: vec![], also: None }; + let gate = |dir: &Path| ScriptGate { + read: ScriptScope::of_folder(dir), + write: ScriptScope::default(), + documents: vec![], + linked: Arc::new([]), + also: None, + }; let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); let narrow = |saved: ScopeHandle, g: ScriptGate| with_script_gate(g, || saved.within_current()); let reads = |h: &ScopeHandle| h.clone().run(|| (check_read(&inside).is_ok(), check_read(&other).is_ok())); @@ -957,6 +1003,74 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// A file an open document linked to when the run began is readable through the gate; its path + /// written with `..`, writing it, a file next to it and a file that was not there when the gate + /// was made are not allowed, and the automation roots still apply. + #[test] + fn a_gate_reads_only_the_linked_files_it_was_given() { + let (base, roots) = folders("linked"); + let (secret, other) = (base.join("outside/secret.svg"), base.join("outside/other.svg")); + std::fs::write(&other, "").unwrap(); + let later = base.join("outside/later.svg"); + let linked = ScriptGate::real_files([s(secret.clone()), s(later.clone()), s(base.join("outside"))]); + assert_eq!(linked.len(), 1, "a missing file and a folder are left out: {linked:?}"); + let gate = + ScriptGate { read: ScriptScope::of_folder(&base.join("in")), write: ScriptScope::default(), documents: vec![], linked, also: None }; + std::fs::write(&later, "").unwrap(); + let (read, write) = + (|p: &Path| gate.check(&s(p.to_path_buf()), Access::Read).is_ok(), |p: &Path| gate.check(&s(p.to_path_buf()), Access::Write).is_ok()); + assert!(read(&secret)); + assert!(!read(&base.join("outside/../outside/secret.svg")), "a path with `..` is refused by its name"); + assert!(!write(&secret), "linked files are not written"); + assert!(!read(&other), "a file next to a linked one"); + assert!(!read(&later), "a file made after the gate"); + assert!(!read(&base.join("outside")), "the linked file's folder"); + let g = gate.clone(); + assert!(confine(Some(&roots), || with_script_gate(g, || check_read(&s(secret.clone())).is_err())), "the roots apply first"); + let _ = std::fs::remove_dir_all(base); + } + + /// A document the run opened from a file only the linked files let it read is not written + /// through the document-file rule; one open when the run began, and one in the script's own + /// places, still is. + #[test] + fn a_document_opened_from_a_linked_file_stays_read_only() { + let (base, _) = folders("linked-doc"); + let (secret, own) = (s(base.join("outside/secret.svg")), s(base.join("in/a.svg"))); + let gate = ScriptGate { + read: ScriptScope::of_folder(&base.join("in")), + write: ScriptScope::of_folder(&base.join("in")), + documents: vec![secret.clone(), own.clone()], + linked: ScriptGate::real_files([secret.clone(), own.clone()]), + also: None, + }; + let opened = gate.clone().keeping_linked_read_only(&[]); + assert!(opened.check(&secret, Access::Read).is_ok()); + assert!(opened.check(&secret, Access::Write).is_err(), "opened by the run from a linked file"); + assert!(opened.check(&own, Access::Write).is_ok(), "a file in the script's own places"); + let before = gate.keeping_linked_read_only(std::slice::from_ref(&secret)); + assert!(before.check(&secret, Access::Write).is_ok(), "open when the run began"); + let _ = std::fs::remove_dir_all(base); + } + + /// A link to a linked file read through the gate counts only while it leads to that file. + #[cfg(unix)] + #[test] + fn a_gate_refuses_a_link_that_now_leads_elsewhere() { + let (base, _) = folders("linked-moved"); + let (secret, other, link) = (base.join("outside/secret.svg"), base.join("outside/other.svg"), base.join("outside/link.svg")); + std::fs::write(&other, "").unwrap(); + std::os::unix::fs::symlink(&secret, &link).unwrap(); + let linked = ScriptGate::real_files([s(link.clone())]); + let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::default(), documents: vec![], linked, also: None }; + assert!(gate.check(&s(link.clone()), Access::Read).is_ok() && gate.check(&s(secret.clone()), Access::Read).is_ok()); + std::fs::remove_file(&link).unwrap(); + std::os::unix::fs::symlink(&other, &link).unwrap(); + assert!(gate.check(&s(link.clone()), Access::Read).is_err(), "the link leads to another file now"); + assert!(gate.check(&s(other), Access::Read).is_err()); + let _ = std::fs::remove_dir_all(base); + } + #[test] fn network_paths_are_told_by_name() { for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] { diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index c0694bbd81..34179a55b5 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -54,7 +54,8 @@ //! for, loses the grant before that code runs. A run with nobody to ask gets `null` and //! [`NO_PICKER`]. //! - The commands a script runs with `vc.run` read and write only in the places above and in the -//! files of the open documents ([`crate::file_access::ScriptGate`]). +//! files of the open documents ([`crate::file_access::ScriptGate`]). They also read the files that +//! the documents open when the run began link to, as those links were then. //! - `open('w')` empties the file at once; what a script writes is kept in memory, at most //! [`MAX_FILE_BYTES`] a file, and written when it closes the file or the run ends; a run writes at //! most [`MAX_RUN_BYTES`] in all and ends past that. `write` encodes in the file's encoding (an @@ -72,8 +73,9 @@ //! - In a wasm build every lookup fails with [`NO_WEB`]. use std::collections::HashMap; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::rc::Rc; +use std::sync::Arc; use std::sync::atomic::{AtomicU32, Ordering}; use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError}; @@ -454,10 +456,11 @@ impl Disk { } } - /// The gate for a command the script runs: the places it reads and writes now, and the files of - /// the open documents, `documents`. - pub(crate) fn gate(&self, documents: Vec) -> crate::file_access::ScriptGate { - crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, also: None } + /// The gate for a command the script runs: the places it reads and writes now, the files of the + /// open documents, `documents`, and the files it may only read because the documents open when + /// the run began link to them, `linked`. + pub(crate) fn gate(&self, documents: Vec, linked: Arc<[PathBuf]>) -> crate::file_access::ScriptGate { + crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, linked, also: None } } /// The files written since this was last asked, to name in the report. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..62dc11df23 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -799,6 +799,36 @@ struct Host { dollar: dollar::RunState, /// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it. args: RefCell<(Data, u64)>, + /// The documents open when the run began, each with its own file and the file it was read from + /// ([`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files + /// they link to from them ([`Host::linked`]). + run_docs: RefCell>, + /// The files of the documents open when the run began + /// ([`crate::file_access::ScriptGate::keeping_linked_read_only`]). + opened_before: Vec, + /// The real paths of the files the documents open when the run began link to + /// ([`crate::file_access::ScriptGate::linked`]). + linked: std::cell::OnceCell>, +} + +/// A document open when a run began, with its own file and the file it was read from. +type RunDoc = (Arc, Option, Option); + +impl Host { + /// The files the commands the run runs may read because the documents open when the run began + /// link to them, found once, from those documents as they were then: a link the run adds or + /// changes, and a document it opens, give it no file to read. + fn linked(&self) -> Arc<[std::path::PathBuf]> { + self.linked + .get_or_init(|| { + let docs = std::mem::take(&mut *self.run_docs.borrow_mut()); + let files = docs.iter().flat_map(|(d, path, from)| { + crate::cmd::links::files_linked(d, crate::cmd::links::LinkBase::of_files(path.as_deref(), from.as_deref())) + }); + crate::file_access::ScriptGate::real_files(files.collect::>()) + }) + .clone() + } } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -1238,8 +1268,11 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value let before: Vec<(u64, Arc, u64)> = if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() }; crate::file_access::start_recording_writes(); - // The command reads and writes only where the script's own files may, and the open documents' files. - let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect()); + // The command reads and writes only where the script's own files may, and the open documents' files; + // it also reads the files the documents open when the run began link to, and does not write a document + // the run opened from one of those. + let linked = host.linked(); + let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect(), linked).keeping_linked_read_only(&host.opened_before); let r = crate::file_access::with_script_gate(gate, || s.execute(id, params)); // A file a command wrote before it failed is on disk all the same. let mut written = host.written.borrow_mut(); @@ -2040,6 +2073,9 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), + run_docs: RefCell::new(self.docs.iter().map(|st| (st.doc.clone(), st.path.clone(), st.links_from.clone())).collect()), + opened_before: self.docs.iter().filter_map(|st| st.path.clone()).collect(), + linked: std::cell::OnceCell::new(), }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index bf8154f9a7..d0a9723f3e 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -417,6 +417,68 @@ fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() { let _ = std::fs::remove_dir_all(&dir); } +/// The color at the middle of the PNG at `path`. +fn middle_color(path: &std::path::Path) -> [u8; 3] { + let img = craft_image_codecs::decode(&std::fs::read(path).unwrap()).unwrap(); + let (w, h) = img.dimensions(); + let rgba = img.to_rgba8(); + let i = ((h / 2 * w + w / 2) * 4) as usize; + [rgba[i], rgba[i + 1], rgba[i + 2]] +} + +/// A script's export of a document open when the run began draws the file its image links to, +/// also outside the script's places. A file the script names itself, a link it points at such a +/// file, writing to the linked file and the links of a document the script opens are refused all +/// the same. +#[test] +fn a_scripts_export_reads_the_files_the_documents_open_before_it_link_to() { + use crate::tests_links::{BLUE, RED, near, open, place, png, save, session, write}; + let dir = fresh_folder("gate-links"); + let (inside, art) = (dir.join("in"), dir.join("art")); + std::fs::create_dir_all(&inside).unwrap(); + let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); + let (pic, secret, poster, other) = + (p(art.join("photo.png")), p(art.join("secret.png")), p(art.join("poster.vectorcraft")), p(inside.join("other.vectorcraft"))); + write(&pic, &png(600, 300, RED)); + write(&secret, &png(600, 300, RED)); + let mut s = session(); + place(&mut s, &pic); + save(&mut s, &poster); + s.execute("file.close", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + place(&mut s, &secret); + save(&mut s, &other); + s.execute("file.close", &json!({})).unwrap(); + // The files change after the saves: each document holds only the red preview of its image. + write(&pic, &png(600, 300, BLUE)); + write(&secret, &png(600, 300, BLUE)); + open(&mut s, &poster); + let (first, second) = (inside.join("first.png"), inside.join("second.png")); + let call = |id: &str, params: String| { + format!( + "try {{ var r = vc.run('{id}', {params}); vc.log(r.warnings ? r.warnings.length : 0); }} \ + catch (e) {{ vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }}\n" + ) + }; + let export = |to: &std::path::Path| format!("{{path: {:?}, format: 'png', background: 'white'}}", p(to.to_path_buf())); + let source = [ + call("document.export", export(&first)), + call("file.place", format!("{{path: {secret:?}, at: [200, 150]}}")), + "vc.run('select.all', {});\n".to_string(), + call("links.relink", format!("{{path: {secret:?}}}")), + call("document.export", format!("{{path: {pic:?}, format: 'png'}}")), + call("document.open", format!("{{path: {other:?}}}")), + call("document.export", export(&second)), + ] + .concat(); + let r = run_allowed(&mut s, &inside, &source).unwrap(); + assert_eq!(r["log"], json!([0, "denied", "denied", "denied", 0, 1]), "{r}"); + assert!(near(middle_color(&first), BLUE), "the linked file, not its preview: {:?}", middle_color(&first)); + assert!(near(middle_color(&second), RED), "a document the script opened gets no linked file: {:?}", middle_color(&second)); + assert_eq!(std::fs::read(&pic).unwrap(), png(600, 300, BLUE), "the linked file is not written"); + let _ = std::fs::remove_dir_all(&dir); +} + /// A command a script runs does not save into the app's own libraries; the same command run /// outside a script does. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..9a1f57c42f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3020,6 +3020,13 @@ VectorCraft writes files by these rules of its own: `Script file access denied` and the path, saving into a user library (swatches, brushes, symbols or graphic styles) included; reading the app's own libraries is allowed. A script given as `source` that a person allowed nothing writes only in its `Folder.temp` and `Folder.userData` and to the open documents' own files. + Such a command also reads, and does not write, the files that the documents open when the run began link to + (linked images, placed files, the plate files of a DCS image and the images their data sets name), so an export, + save, print or package of them includes the linked art. A document the script opens from such a file is not + saved over it. The files are taken as those links led at the run's + first `vc.run`, and a path that leads to another file since is refused. A link the script adds or points + elsewhere, and a document it opens, does not let it read any file it could not read before. The automation + read roots still apply. A pick inside the folder that holds the settings gives `null` and sets `error` to `Script file access to the app's own folders is not allowed`. - A run with nobody to ask, as over MCP or the command line, gives `null` from every file dialog and sets `error` to diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..37b87a97d9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1039,7 +1039,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a runtime error is shown at the line that was running ([the help page](https://extendscript.docsforadobe.dev/extendscript-toolkit/debugging-in-the-toolkit/)). VectorCraft's own rules: an error in code an earlier run of a named engine compiled, such as a function it defined, is reported at that code's file, line and column (the earlier run's script, a file it included or a file its `$.evalFile` ran), while the report and its console line keep the calling run's name; a script given as text is named by its run's name, and each engine keeps these places for 8 MiB of source maps, the oldest going first. An error in code whose place is gone, or in code that `eval` or `Function` compiled, is reported without a line and column, and the code still runs. `crates/engine/src/tests/script_engines.rs`. - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. + - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files, and read the files linked as the next line says; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. + - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run`; a path that leads to another file since, a link the script adds or points elsewhere and a document it opens give it no further file to read, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. From bab25d02487c087f44d143d0000ea33fb0de2660 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:32:08 -0800 Subject: [PATCH 2/6] Scripts: a document opened from a linked file stays read-only when its path changes The gate now records each path a script's command reads only because it led to a file the open documents link to. A document whose file is such a path is taken out of the open documents' files for the rest of the run, without looking at where the path leads now or what the script may read now. Before, the gate decided that again for each command from the path's current target, so a path pointed at another file by a link, or a read grant given later, let the run read and write through the document. --- crates/engine/src/file_access.rs | 139 ++++++++++++++++++++++++++---- crates/engine/src/script/files.rs | 5 +- crates/engine/src/script/mod.rs | 11 +-- docs/mcp.md | 4 +- 4 files changed, 135 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 525094a990..890be26fb9 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -286,19 +286,52 @@ pub(crate) struct ScriptGate { pub(crate) write: ScriptScope, /// The paths of the open documents' files, as the documents hold them. pub(crate) documents: Vec, - /// The real paths of the files the documents open when the run began link to, as they were - /// when the run's first command was run ([`ScriptGate::real_files`]): readable, not writable. - /// A path that leads to another file now is not one of them. - pub(crate) linked: Arc<[PathBuf]>, + /// The files the documents open when the run began link to: readable, not writable. + pub(crate) linked: LinkedFiles, /// Another gate a path must pass as well ([`ScopeHandle::within_current`]). pub(crate) also: Option>, } +/// The files the commands a script runs may only read because the documents open when the run +/// began link to them ([`ScriptGate::linked`]), and the paths a command read through them alone. +/// Clones share the record of those paths. +#[derive(Clone, Debug, Default)] +pub(crate) struct LinkedFiles { + /// The real paths of the files, as they were when the run's first command was run, sorted. A + /// path that leads to another file now is not one of them. + files: Arc<[PathBuf]>, + /// The paths, absolute as a document holds its file, that a command read only because they led + /// to one of `files` when it read them. A document opened from one of them stays read-only for + /// the rest of the run, wherever the path leads later. + read: Arc>>, +} + +impl LinkedFiles { + /// Is `real`, a real path, one of the files? + fn has(&self, real: &Path) -> bool { + self.files.binary_search_by(|f| f.as_path().cmp(real)).is_ok() + } + + /// The paths read through the files alone so far. + fn read_paths(&self) -> Vec { + self.read.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone() + } + + /// Notes that `path` was read through the files alone. + fn note_read(&self, path: &str) { + let path = crate::cmd::fileio::absolute_path(path); + let mut read = self.read.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if !read.contains(&path) { + read.push(path); + } + } +} + impl ScriptGate { /// The real paths of the files at `paths` that are files now, each once, for /// [`ScriptGate::linked`]. A path refused by its name alone, and one that cannot be resolved, /// is left out. - pub(crate) fn real_files(paths: impl IntoIterator) -> Arc<[PathBuf]> { + pub(crate) fn real_files(paths: impl IntoIterator) -> LinkedFiles { let mut real: Vec = paths .into_iter() .filter(|p| !ScriptScope::refused_by_name(Path::new(p))) @@ -307,18 +340,20 @@ impl ScriptGate { .collect(); real.sort(); real.dedup(); - real.into() + LinkedFiles { files: real.into(), read: Arc::default() } } /// This gate without the documents whose files only [`ScriptGate::linked`] lets it read, unless /// they are among `before`, the files of the documents open when the run began: a document the - /// run opened from such a file is read, never written. + /// run opened from such a file is read, never written. A document counts as one when a command + /// read its file through the linked files alone, whatever the path leads to or the script may + /// read now, and when its file is one of them now that nothing else lets the gate read. pub(crate) fn keeping_linked_read_only(mut self, before: &[String]) -> Self { - let plain = ScriptGate { documents: vec![], linked: Arc::new([]), also: None, ..self.clone() }; - let linked = self.linked.clone(); + let plain = ScriptGate { documents: vec![], linked: LinkedFiles::default(), also: None, ..self.clone() }; + let (linked, read) = (self.linked.clone(), self.linked.read_paths()); let only_linked = |d: &String| { let real = if ScriptScope::refused_by_name(Path::new(d)) { None } else { resolve(d).ok() }; - real.is_some_and(|real| linked.binary_search(&real).is_ok()) && plain.check(d, Access::Read).is_err() + read.contains(d) || (real.is_some_and(|real| linked.has(&real)) && plain.check(d, Access::Read).is_err()) }; self.documents.retain(|d| before.contains(d) || !only_linked(d)); self @@ -342,10 +377,17 @@ impl ScriptGate { let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() }; let allowed = real.is_some_and(|real| { let scoped = match access { - Access::Read => self.read.allows(&real) || self.write.allows(&real) || self.linked.binary_search(&real).is_ok(), + Access::Read => self.read.allows(&real) || self.write.allows(&real), Access::Write => self.write.allows(&real), }; - scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) + if scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) { + return true; + } + let linked = matches!(access, Access::Read) && self.linked.has(&real); + if linked { + self.linked.note_read(path); + } + linked }); if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } } @@ -957,7 +999,7 @@ mod tests { read: ScriptScope::of_folder(&base.join(dir)), write: ScriptScope::default(), documents: vec![], - linked: Arc::new([]), + linked: LinkedFiles::default(), also: None, }; let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); @@ -986,7 +1028,7 @@ mod tests { read: ScriptScope::of_folder(dir), write: ScriptScope::default(), documents: vec![], - linked: Arc::new([]), + linked: LinkedFiles::default(), also: None, }; let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); @@ -1013,7 +1055,7 @@ mod tests { std::fs::write(&other, "").unwrap(); let later = base.join("outside/later.svg"); let linked = ScriptGate::real_files([s(secret.clone()), s(later.clone()), s(base.join("outside"))]); - assert_eq!(linked.len(), 1, "a missing file and a folder are left out: {linked:?}"); + assert_eq!(linked.files.len(), 1, "a missing file and a folder are left out: {linked:?}"); let gate = ScriptGate { read: ScriptScope::of_folder(&base.join("in")), write: ScriptScope::default(), documents: vec![], linked, also: None }; std::fs::write(&later, "").unwrap(); @@ -1053,6 +1095,73 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// A document opened from a file a command read through the linked files alone stays + /// read-only after the script is allowed to read that file's folder, and after the file is + /// replaced by another one. + #[test] + fn a_document_read_through_a_linked_file_stays_read_only_after_a_read_grant() { + let (base, _) = folders("linked-granted"); + let secret = s(base.join("outside/secret.svg")); + let linked = ScriptGate::real_files([secret.clone()]); + let gate = |read: &str, documents: Vec| ScriptGate { + read: ScriptScope::of_folder(&base.join(read)), + write: ScriptScope::default(), + documents, + linked: linked.clone(), + also: None, + }; + assert!(gate("in", vec![]).check(&secret, Access::Read).is_ok(), "the command that opens it reads it through the linked file"); + let granted = gate("outside", vec![secret.clone()]).keeping_linked_read_only(&[]); + assert!(granted.check(&secret, Access::Read).is_ok()); + assert!(granted.check(&secret, Access::Write).is_err(), "a read grant made later does not make it writable"); + std::fs::remove_file(&secret).unwrap(); + std::fs::write(&secret, "").unwrap(); + let replaced = gate("in", vec![secret.clone()]).keeping_linked_read_only(&[]); + assert!(replaced.check(&secret, Access::Write).is_err(), "replaced by another file"); + let _ = std::fs::remove_dir_all(base); + } + + /// A document opened from a file a command read through the linked files alone gives no + /// access to the file its path leads to after the path is pointed elsewhere by a link. + #[test] + fn a_document_read_through_a_linked_file_gives_nothing_once_its_path_leads_elsewhere() { + let (base, _) = folders("linked-redirected"); + #[cfg(unix)] + let made = |target: &Path, link: &Path| std::os::unix::fs::symlink(target, link).is_ok(); + #[cfg(windows)] + let made = |target: &Path, link: &Path| std::os::windows::fs::symlink_dir(target, link).is_ok(); + #[cfg(not(any(unix, windows)))] + let made = |_: &Path, _: &Path| false; + let (first, second, via) = (base.join("outside/first"), base.join("outside/second"), base.join("outside/via")); + for dir in [&first, &second] { + std::fs::create_dir_all(dir).unwrap(); + std::fs::write(dir.join("a.svg"), "").unwrap(); + } + // Windows needs Developer Mode or elevation to make links: nothing to test without them. + if !made(&first, &via) { + eprintln!("skipped: symbolic links can't be made here"); + let _ = std::fs::remove_dir_all(base); + return; + } + let (doc, elsewhere) = (s(via.join("a.svg")), s(second.join("a.svg"))); + let linked = ScriptGate::real_files([doc.clone()]); + let gate = |documents: Vec| ScriptGate { + read: ScriptScope::default(), + write: ScriptScope::default(), + documents, + linked: linked.clone(), + also: None, + }; + assert!(gate(vec![]).check(&doc, Access::Read).is_ok(), "the command that opens it reads it through the linked file"); + std::fs::remove_dir(&via).or_else(|_| std::fs::remove_file(&via)).unwrap(); + assert!(made(&second, &via)); + let opened = gate(vec![doc.clone()]).keeping_linked_read_only(&[]); + for (path, access) in [(&doc, Access::Read), (&doc, Access::Write), (&elsewhere, Access::Read), (&elsewhere, Access::Write)] { + assert!(opened.check(path, access).is_err(), "{path} {access:?}"); + } + let _ = std::fs::remove_dir_all(base); + } + /// A link to a linked file read through the gate counts only while it leads to that file. #[cfg(unix)] #[test] diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 34179a55b5..2c63c9cd66 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -73,9 +73,8 @@ //! - In a wasm build every lookup fails with [`NO_WEB`]. use std::collections::HashMap; -use std::path::{Path, PathBuf}; +use std::path::Path; use std::rc::Rc; -use std::sync::Arc; use std::sync::atomic::{AtomicU32, Ordering}; use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError}; @@ -459,7 +458,7 @@ impl Disk { /// The gate for a command the script runs: the places it reads and writes now, the files of the /// open documents, `documents`, and the files it may only read because the documents open when /// the run began link to them, `linked`. - pub(crate) fn gate(&self, documents: Vec, linked: Arc<[PathBuf]>) -> crate::file_access::ScriptGate { + pub(crate) fn gate(&self, documents: Vec, linked: crate::file_access::LinkedFiles) -> crate::file_access::ScriptGate { crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, linked, also: None } } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 62dc11df23..9e3419d10d 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -806,9 +806,9 @@ struct Host { /// The files of the documents open when the run began /// ([`crate::file_access::ScriptGate::keeping_linked_read_only`]). opened_before: Vec, - /// The real paths of the files the documents open when the run began link to - /// ([`crate::file_access::ScriptGate::linked`]). - linked: std::cell::OnceCell>, + /// The files the documents open when the run began link to, and the paths the run's commands + /// read through them alone ([`crate::file_access::ScriptGate::linked`]). + linked: std::cell::OnceCell, } /// A document open when a run began, with its own file and the file it was read from. @@ -817,8 +817,9 @@ type RunDoc = (Arc, Option, Option); impl Host { /// The files the commands the run runs may read because the documents open when the run began /// link to them, found once, from those documents as they were then: a link the run adds or - /// changes, and a document it opens, give it no file to read. - fn linked(&self) -> Arc<[std::path::PathBuf]> { + /// changes, and a document it opens, give it no file to read. Every command's gate shares the + /// record of the paths read through them. + fn linked(&self) -> crate::file_access::LinkedFiles { self.linked .get_or_init(|| { let docs = std::mem::take(&mut *self.run_docs.borrow_mut()); diff --git a/docs/mcp.md b/docs/mcp.md index 9a1f57c42f..6c0de9e418 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3023,7 +3023,9 @@ VectorCraft writes files by these rules of its own: Such a command also reads, and does not write, the files that the documents open when the run began link to (linked images, placed files, the plate files of a DCS image and the images their data sets name), so an export, save, print or package of them includes the linked art. A document the script opens from such a file is not - saved over it. The files are taken as those links led at the run's + saved over it for the rest of the run, also after the script is allowed to read that file's folder, and when its + path leads to another file later, the document does not let the script read or write that file. The files are + taken as those links led at the run's first `vc.run`, and a path that leads to another file since is refused. A link the script adds or points elsewhere, and a document it opens, does not let it read any file it could not read before. The automation read roots still apply. From 29ddc57821b8d559b0de4f704e6e48b1df98980f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:45:27 -0800 Subject: [PATCH 3/6] Scripts: what a script's commands open or change gives later runs no file access The commands a script runs could read the files that the documents open at the run's start link to, and could read and write the files of every open document. Both lists were taken from the documents as they were, so a document a script opened, or a link or data set value a script added, widened what the next run could read, and a document opened from a linked file could be saved over that file in the next run. - DocState::by_script records what scripts' commands did to a document since the person last opened or saved it: opened it, or changed it or gave it another file, keeping the document, its file and the file it was read from as they were before. The script host notes it after every command, and a save the person makes from the document's current content clears it. Revert keeps it, and a recovery copy restores the document as one a script opened. - The gate's document files and the linked files are taken from each document as the person left it (DocState::as_person_left). A document a script opened gives neither, in that run or a later one. - This replaces the per-run record of paths read through the linked files and ScriptGate::keeping_linked_read_only. - docs/mcp.md and docs/target-app-parity.md describe the rule. --- crates/engine/src/cmd/fileio/save.rs | 6 +- crates/engine/src/cmd/links.rs | 3 +- crates/engine/src/cmd/recovery.rs | 9 ++ crates/engine/src/doc_state.rs | 44 ++++++++ crates/engine/src/file_access.rs | 135 +++++-------------------- crates/engine/src/script/files.rs | 9 +- crates/engine/src/script/mod.rs | 44 ++++---- crates/engine/src/session/documents.rs | 2 + crates/engine/src/tests/script_run.rs | 110 ++++++++++++++++++++ docs/mcp.md | 15 +-- docs/target-app-parity.md | 2 +- 11 files changed, 238 insertions(+), 141 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index f03dc6fe0d..7585861e9b 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1148,10 +1148,14 @@ impl SaveJob { /// Once written: Save and Save As (except to a template) make the file `st`'s own: path, /// title, format, options, and the snapshot as the saved state (edits made since the job was /// made keep the document modified; changes that are not edits to save don't, - /// [`DocState::same_content`]). + /// [`DocState::same_content`]). Saved outside a command a script runs, from the document's + /// content as it is now, the document is as the person left it ([`DocState::by_script`]). pub fn finish(self, st: &mut DocState) { let retargets = self.plan.retargets(); if let (true, Some(path)) = (retargets, self.plan.path) { + if !crate::file_access::in_script_command() && st.same_content(&self.source) { + st.by_script = None; + } st.path = Some(path); st.format = self.plan.format.id; st.save_options = self.plan.options; diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 9f1e7c3d79..3950d39f0b 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -410,7 +410,8 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option { /// finds each linked image's and placed document's file from `base` and from no document (as /// output reads them, [`full_linked_images`]), the plate files of their own of images placed from /// DCS files, and the image files its data sets name. The commands a script runs may read these -/// for the documents open when the run began ([`crate::file_access::ScriptGate::linked`]). +/// for the documents open when the run began, as the person left them +/// ([`crate::file_access::ScriptGate::linked`]). pub(crate) fn files_linked(d: &Document, base: LinkBase) -> Vec { let mut out = vec![]; for g in groups(d, None) { diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 193e86b600..de64441623 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -874,6 +874,11 @@ struct Meta { /// images were kept apart: the document entry holds them). #[serde(skip_serializing_if = "BTreeMap::is_empty")] images: BTreeMap, + /// A command a script ran opened or changed the document since the person last saved it + /// ([`crate::DocState::by_script`]): the commands scripts run treat the restored document as + /// one a script opened. + #[serde(skip_serializing_if = "std::ops::Not::not")] + by_script: bool, } /// One of a copy's images: its entry in the copy's area. @@ -1195,6 +1200,7 @@ pub fn jobs(s: &mut Session, store: &Arc) -> Result<(Vec, file: &str) -> R st.imported_from = meta.imported_from.clone(); st.import_losses = meta.import_losses.clone(); st.format = SAVE_FORMATS.iter().copied().find(|f| *f == meta.format).unwrap_or("vectorcraft"); + if meta.by_script { + st.by_script = Some(crate::doc_state::ByScript::Opened); + } if let Some(pdf) = meta.native_pdf_compatible { st.save_options.insert("pdfCompatible".into(), json!(pdf)); } diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index cabc774737..d57173ae76 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -128,6 +128,11 @@ pub struct DocState { /// paths the document links to are looked at within them later too, when the Links panel /// asks about a link outside any caller's scope. pub opened_by: Option>, + /// What the commands scripts ran did to the document since the person last opened or saved it: + /// `None` when they did nothing. The commands a script runs read and write the document's file, + /// and read the files it links to, only as the person left them ([`DocState::as_person_left`]). + /// Not saved. + pub(crate) by_script: Option, /// The live-effect plug-in stages deferred while the document is drawn on screen, and the time /// budget of its first view ([`vectorcraft_plugins::deferred`]). Not saved. pub plugin_effects: vectorcraft_plugins::deferred::Deferrals, @@ -146,6 +151,17 @@ pub struct DocState { pub(crate) inline_resolved: Option, } +/// What the commands scripts ran did to an open document since the person last opened or saved it +/// ([`DocState::by_script`]). +#[derive(Clone, Debug)] +pub(crate) enum ByScript { + /// A command a script ran opened it (or made it). + Opened, + /// A command a script ran changed it or gave it another file: the document, its file and the + /// file it was read from as they were before the first such command. + Changed { doc: Arc, path: Option, links_from: Option }, +} + /// Whether a document has an artboard for Delete Empty Artboards to delete, with the document that /// was measured. #[derive(Clone, Debug, Default)] @@ -360,6 +376,7 @@ impl DocState { links_from: None, last_perspective: None, opened_by: file_access::current(), + by_script: None, empty_artboards: Default::default(), plugin_effects: Default::default(), art_to_fit: Default::default(), @@ -367,6 +384,33 @@ impl DocState { inline_resolved: None, } } + + /// The document, its file and the file it was read from as the person last left them, for the + /// commands scripts run ([`DocState::by_script`]): `None` for a document a script's command + /// opened. + pub(crate) fn as_person_left(&self) -> Option<(&Arc, Option<&str>, Option<&str>)> { + match &self.by_script { + None => Some((&self.doc, self.path.as_deref(), self.links_from.as_deref())), + Some(ByScript::Opened) => None, + Some(ByScript::Changed { doc, path, links_from }) => Some((doc, path.as_deref(), links_from.as_deref())), + } + } + + /// Notes what a command a script ran did to the document, which was `was` (the document, its + /// file and the file it was read from) before the command ran, or not open when `was` is + /// `None`. The first change is kept until the person saves the document. + pub(crate) fn note_script_command(&mut self, was: Option<(&Arc, &Option, &Option)>) { + if self.by_script.is_some() { + return; + } + let Some((doc, path, links_from)) = was else { + self.by_script = Some(ByScript::Opened); + return; + }; + if !Arc::ptr_eq(doc, &self.doc) || *path != self.path || *links_from != self.links_from { + self.by_script = Some(ByScript::Changed { doc: doc.clone(), path: path.clone(), links_from: links_from.clone() }); + } + } /// `measure`'s answer for the document now. `measure` runs once for each version of the document, /// so a menu that asks on every frame measures it once, and a change of the selection or the view /// keeps the answer. diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 890be26fb9..c20e37b58e 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -28,7 +28,7 @@ //! are read from, and the places its `File` and `Folder` objects read and write, inside the roots. //! [`ScriptGate`] holds the same places for the commands the script runs with `vc.run`, with the //! files of the open documents, and for reading, the files the documents open when the run began -//! link to. +//! link to, each as the person last left the document. use std::cell::RefCell; use std::ffi::OsString; @@ -277,33 +277,31 @@ impl ScopeHandle { /// What a command a running script runs (`vc.run`) may read and write: the places the script's /// `File` and `Folder` objects may ([`ScriptScope`]), and the files the documents open in the app -/// were opened from or saved to. Reading, and only reading, the files the documents open when the -/// run began link to is allowed as well ([`ScriptGate::linked`]). The automation roots apply as -/// well. A path refused by its name alone ([`ScriptScope::refused_by_name`]) is refused here too. +/// were opened from or saved to by the person ([`crate::DocState::as_person_left`]). Reading, and +/// only reading, the files the documents link to as the person left them when the run began is +/// allowed as well ([`ScriptGate::linked`]). The automation roots apply as well. A path refused by +/// its name alone ([`ScriptScope::refused_by_name`]) is refused here too. #[derive(Clone, Debug)] pub(crate) struct ScriptGate { pub(crate) read: ScriptScope, pub(crate) write: ScriptScope, - /// The paths of the open documents' files, as the documents hold them. + /// The paths of the open documents' files, as the documents held them when the person last + /// opened or saved them. A document a script's command opened has none here. pub(crate) documents: Vec, - /// The files the documents open when the run began link to: readable, not writable. + /// The files the documents link to as the person left them when the run began: readable, not + /// writable. pub(crate) linked: LinkedFiles, /// Another gate a path must pass as well ([`ScopeHandle::within_current`]). pub(crate) also: Option>, } /// The files the commands a script runs may only read because the documents open when the run -/// began link to them ([`ScriptGate::linked`]), and the paths a command read through them alone. -/// Clones share the record of those paths. +/// began link to them as the person left them ([`ScriptGate::linked`]). #[derive(Clone, Debug, Default)] pub(crate) struct LinkedFiles { /// The real paths of the files, as they were when the run's first command was run, sorted. A /// path that leads to another file now is not one of them. files: Arc<[PathBuf]>, - /// The paths, absolute as a document holds its file, that a command read only because they led - /// to one of `files` when it read them. A document opened from one of them stays read-only for - /// the rest of the run, wherever the path leads later. - read: Arc>>, } impl LinkedFiles { @@ -311,20 +309,6 @@ impl LinkedFiles { fn has(&self, real: &Path) -> bool { self.files.binary_search_by(|f| f.as_path().cmp(real)).is_ok() } - - /// The paths read through the files alone so far. - fn read_paths(&self) -> Vec { - self.read.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone() - } - - /// Notes that `path` was read through the files alone. - fn note_read(&self, path: &str) { - let path = crate::cmd::fileio::absolute_path(path); - let mut read = self.read.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if !read.contains(&path) { - read.push(path); - } - } } impl ScriptGate { @@ -340,23 +324,7 @@ impl ScriptGate { .collect(); real.sort(); real.dedup(); - LinkedFiles { files: real.into(), read: Arc::default() } - } - - /// This gate without the documents whose files only [`ScriptGate::linked`] lets it read, unless - /// they are among `before`, the files of the documents open when the run began: a document the - /// run opened from such a file is read, never written. A document counts as one when a command - /// read its file through the linked files alone, whatever the path leads to or the script may - /// read now, and when its file is one of them now that nothing else lets the gate read. - pub(crate) fn keeping_linked_read_only(mut self, before: &[String]) -> Self { - let plain = ScriptGate { documents: vec![], linked: LinkedFiles::default(), also: None, ..self.clone() }; - let (linked, read) = (self.linked.clone(), self.linked.read_paths()); - let only_linked = |d: &String| { - let real = if ScriptScope::refused_by_name(Path::new(d)) { None } else { resolve(d).ok() }; - read.contains(d) || (real.is_some_and(|real| linked.has(&real)) && plain.check(d, Access::Read).is_err()) - }; - self.documents.retain(|d| before.contains(d) || !only_linked(d)); - self + LinkedFiles { files: real.into() } } /// This gate with `next` at the end of its chain of `also` gates, so a path must pass every @@ -380,14 +348,7 @@ impl ScriptGate { Access::Read => self.read.allows(&real) || self.write.allows(&real), Access::Write => self.write.allows(&real), }; - if scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) { - return true; - } - let linked = matches!(access, Access::Read) && self.linked.has(&real); - if linked { - self.linked.note_read(path); - } - linked + scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || (matches!(access, Access::Read) && self.linked.has(&real)) }); if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } } @@ -431,6 +392,11 @@ fn check_gate(path: &str, access: Access) -> Result<(), String> { GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check(path, access)) } +/// Whether this thread runs a command a script runs ([`with_script_gate`]). +pub(crate) fn in_script_command() -> bool { + GATE.with(|g| g.borrow().is_some()) +} + /// The roots in force on this thread, if any. pub fn current() -> Option> { match SCOPE.with(|s| s.borrow().clone()) { @@ -1072,59 +1038,10 @@ mod tests { let _ = std::fs::remove_dir_all(base); } - /// A document the run opened from a file only the linked files let it read is not written - /// through the document-file rule; one open when the run began, and one in the script's own - /// places, still is. + /// A path read through the linked files gives no access to the file it leads to after it is + /// pointed elsewhere by a link in one of its folders. #[test] - fn a_document_opened_from_a_linked_file_stays_read_only() { - let (base, _) = folders("linked-doc"); - let (secret, own) = (s(base.join("outside/secret.svg")), s(base.join("in/a.svg"))); - let gate = ScriptGate { - read: ScriptScope::of_folder(&base.join("in")), - write: ScriptScope::of_folder(&base.join("in")), - documents: vec![secret.clone(), own.clone()], - linked: ScriptGate::real_files([secret.clone(), own.clone()]), - also: None, - }; - let opened = gate.clone().keeping_linked_read_only(&[]); - assert!(opened.check(&secret, Access::Read).is_ok()); - assert!(opened.check(&secret, Access::Write).is_err(), "opened by the run from a linked file"); - assert!(opened.check(&own, Access::Write).is_ok(), "a file in the script's own places"); - let before = gate.keeping_linked_read_only(std::slice::from_ref(&secret)); - assert!(before.check(&secret, Access::Write).is_ok(), "open when the run began"); - let _ = std::fs::remove_dir_all(base); - } - - /// A document opened from a file a command read through the linked files alone stays - /// read-only after the script is allowed to read that file's folder, and after the file is - /// replaced by another one. - #[test] - fn a_document_read_through_a_linked_file_stays_read_only_after_a_read_grant() { - let (base, _) = folders("linked-granted"); - let secret = s(base.join("outside/secret.svg")); - let linked = ScriptGate::real_files([secret.clone()]); - let gate = |read: &str, documents: Vec| ScriptGate { - read: ScriptScope::of_folder(&base.join(read)), - write: ScriptScope::default(), - documents, - linked: linked.clone(), - also: None, - }; - assert!(gate("in", vec![]).check(&secret, Access::Read).is_ok(), "the command that opens it reads it through the linked file"); - let granted = gate("outside", vec![secret.clone()]).keeping_linked_read_only(&[]); - assert!(granted.check(&secret, Access::Read).is_ok()); - assert!(granted.check(&secret, Access::Write).is_err(), "a read grant made later does not make it writable"); - std::fs::remove_file(&secret).unwrap(); - std::fs::write(&secret, "").unwrap(); - let replaced = gate("in", vec![secret.clone()]).keeping_linked_read_only(&[]); - assert!(replaced.check(&secret, Access::Write).is_err(), "replaced by another file"); - let _ = std::fs::remove_dir_all(base); - } - - /// A document opened from a file a command read through the linked files alone gives no - /// access to the file its path leads to after the path is pointed elsewhere by a link. - #[test] - fn a_document_read_through_a_linked_file_gives_nothing_once_its_path_leads_elsewhere() { + fn a_path_read_through_a_linked_file_gives_nothing_once_it_leads_elsewhere() { let (base, _) = folders("linked-redirected"); #[cfg(unix)] let made = |target: &Path, link: &Path| std::os::unix::fs::symlink(target, link).is_ok(); @@ -1144,20 +1061,18 @@ mod tests { return; } let (doc, elsewhere) = (s(via.join("a.svg")), s(second.join("a.svg"))); - let linked = ScriptGate::real_files([doc.clone()]); - let gate = |documents: Vec| ScriptGate { + let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::default(), - documents, - linked: linked.clone(), + documents: vec![], + linked: ScriptGate::real_files([doc.clone()]), also: None, }; - assert!(gate(vec![]).check(&doc, Access::Read).is_ok(), "the command that opens it reads it through the linked file"); + assert!(gate.check(&doc, Access::Read).is_ok(), "read through the linked file"); std::fs::remove_dir(&via).or_else(|_| std::fs::remove_file(&via)).unwrap(); assert!(made(&second, &via)); - let opened = gate(vec![doc.clone()]).keeping_linked_read_only(&[]); for (path, access) in [(&doc, Access::Read), (&doc, Access::Write), (&elsewhere, Access::Read), (&elsewhere, Access::Write)] { - assert!(opened.check(path, access).is_err(), "{path} {access:?}"); + assert!(gate.check(path, access).is_err(), "{path} {access:?}"); } let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 2c63c9cd66..d0f54bfe32 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -54,8 +54,9 @@ //! for, loses the grant before that code runs. A run with nobody to ask gets `null` and //! [`NO_PICKER`]. //! - The commands a script runs with `vc.run` read and write only in the places above and in the -//! files of the open documents ([`crate::file_access::ScriptGate`]). They also read the files that -//! the documents open when the run began link to, as those links were then. +//! files the person gave the open documents ([`crate::file_access::ScriptGate`]). They also read +//! the files that the documents open when the run began link to, as the person last left those +//! documents and as those links led then. //! - `open('w')` empties the file at once; what a script writes is kept in memory, at most //! [`MAX_FILE_BYTES`] a file, and written when it closes the file or the run ends; a run writes at //! most [`MAX_RUN_BYTES`] in all and ends past that. `write` encodes in the file's encoding (an @@ -455,8 +456,8 @@ impl Disk { } } - /// The gate for a command the script runs: the places it reads and writes now, the files of the - /// open documents, `documents`, and the files it may only read because the documents open when + /// The gate for a command the script runs: the places it reads and writes now, the files the + /// person gave the open documents, `documents`, and the files it may only read because the documents open when /// the run began link to them, `linked`. pub(crate) fn gate(&self, documents: Vec, linked: crate::file_access::LinkedFiles) -> crate::file_access::ScriptGate { crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, linked, also: None } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 9e3419d10d..6d7181d283 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -799,15 +799,13 @@ struct Host { dollar: dollar::RunState, /// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it. args: RefCell<(Data, u64)>, - /// The documents open when the run began, each with its own file and the file it was read from - /// ([`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files + /// The documents open when the run began as the person last left them, each with its own file + /// and the file it was read from ([`crate::DocState::as_person_left`], + /// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files /// they link to from them ([`Host::linked`]). run_docs: RefCell>, - /// The files of the documents open when the run began - /// ([`crate::file_access::ScriptGate::keeping_linked_read_only`]). - opened_before: Vec, - /// The files the documents open when the run began link to, and the paths the run's commands - /// read through them alone ([`crate::file_access::ScriptGate::linked`]). + /// The files the documents open when the run began link to as the person left them + /// ([`crate::file_access::ScriptGate::linked`]). linked: std::cell::OnceCell, } @@ -816,9 +814,9 @@ type RunDoc = (Arc, Option, Option); impl Host { /// The files the commands the run runs may read because the documents open when the run began - /// link to them, found once, from those documents as they were then: a link the run adds or - /// changes, and a document it opens, give it no file to read. Every command's gate shares the - /// record of the paths read through them. + /// link to them, found once, from those documents as the person left them: a link a script's + /// command added or changed, in this run or an earlier one, and a document it opened, give it + /// no file to read. fn linked(&self) -> crate::file_access::LinkedFiles { self.linked .get_or_init(|| { @@ -1269,12 +1267,19 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value let before: Vec<(u64, Arc, u64)> = if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() }; crate::file_access::start_recording_writes(); - // The command reads and writes only where the script's own files may, and the open documents' files; - // it also reads the files the documents open when the run began link to, and does not write a document - // the run opened from one of those. - let linked = host.linked(); - let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect(), linked).keeping_linked_read_only(&host.opened_before); + // The command reads and writes only where the script's own files may, and the files the person gave + // the open documents; it also reads the files the documents open when the run began link to, as the + // person left them. A document a script's command opened gives it no file. + let documents = s.docs.iter().filter_map(|d| d.as_person_left().and_then(|(_, path, _)| path.map(str::to_string))).collect(); + let gate = host.disk.borrow().gate(documents, host.linked()); + let was: Vec<(u64, RunDoc)> = s.docs.iter().map(|d| (d.uid, (d.doc.clone(), d.path.clone(), d.links_from.clone()))).collect(); let r = crate::file_access::with_script_gate(gate, || s.execute(id, params)); + // What the command opened, changed or gave another file is not as the person left it. + for st in &mut s.docs { + let prior = was.iter().find(|(uid, _)| *uid == st.uid); + st.note_script_command(prior.map(|(_, (doc, path, from))| (doc, path, from))); + } + drop(was); // A file a command wrote before it failed is on disk all the same. let mut written = host.written.borrow_mut(); for path in crate::file_access::finish_recording_writes(r.is_ok()) { @@ -2074,8 +2079,13 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), - run_docs: RefCell::new(self.docs.iter().map(|st| (st.doc.clone(), st.path.clone(), st.links_from.clone())).collect()), - opened_before: self.docs.iter().filter_map(|st| st.path.clone()).collect(), + run_docs: RefCell::new( + self.docs + .iter() + .filter_map(DocState::as_person_left) + .map(|(doc, path, from)| (doc.clone(), path.map(str::to_string), from.map(str::to_string))) + .collect(), + ), linked: std::cell::OnceCell::new(), }); *link.borrow_mut() = Some(host.clone()); diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..d5d71c9704 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -402,6 +402,8 @@ impl Session { st.opened_as_tab = old.opened_as_tab; st.revision = old.revision + 1; st.format = old.format; + // What scripts' commands did to the document stays until the person saves it. + st.by_script = old.by_script.clone(); st.save_options = old.save_options.clone(); // The remembered artboard pick follows the artboards it named when the file read back has // the artboards the document had at the save, in the same order and with the same ids (a diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index d0a9723f3e..a57d3be23b 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -479,6 +479,116 @@ fn a_scripts_export_reads_the_files_the_documents_open_before_it_link_to() { let _ = std::fs::remove_dir_all(&dir); } +/// A script line that runs command `id` with `params` and logs `ok`, or `denied` when the gate +/// refuses a file. +fn tried(id: &str, params: &str) -> String { + format!( + "try {{ vc.run('{id}', {params}); vc.log('ok'); }} \ + catch (e) {{ vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }}\n" + ) +} + +/// A document a script opened from a file that only a link let it read is not written in that run +/// or a later one, and gives a later run no access to its file once no document the person left +/// links to it. +#[test] +fn a_document_a_script_opened_from_a_linked_file_stays_read_only_in_later_runs() { + use crate::tests_links::{RED, open, place, png, save, session, write}; + let art = fresh_folder("gate-linked-runs").join("art"); + std::fs::create_dir_all(&art).unwrap(); + let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); + let (pic, inner, poster) = (p(art.join("photo.png")), p(art.join("inner.vectorcraft")), p(art.join("poster.vectorcraft"))); + write(&pic, &png(60, 30, RED)); + let mut s = session(); + place(&mut s, &pic); + save(&mut s, &inner); + s.execute("file.close", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + place(&mut s, &inner); + save(&mut s, &poster); + s.execute("file.close", &json!({})).unwrap(); + open(&mut s, &poster); + let bytes = std::fs::read(&inner).unwrap(); + let opened = run(&mut s, &[tried("document.open", &format!("{{path: {inner:?}}}")), tried("document.save", "{}")].concat()).unwrap(); + assert_eq!(opened["log"], json!(["ok", "denied"]), "{opened}"); + assert_eq!(s.doc().unwrap().path.as_deref(), Some(inner.as_str())); + let mut log = vec![]; + let next = run(&mut s, &tried("document.save", "{}")).unwrap(); + log.push(next["log"][0].clone()); + // The person closes the document that links to it. + let at = s.documents().iter().position(|d| d.path.as_deref() == Some(poster.as_str())).unwrap(); + assert!(s.set_active(at)); + s.execute("file.close", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let later = run(&mut s, &tried("file.place", &format!("{{path: {inner:?}, at: [200, 150]}}"))).unwrap(); + log.push(later["log"][0].clone()); + assert_eq!(log, [json!("denied"), json!("denied")], "a save in the next run, then a read once nothing the person left links to it"); + assert_eq!(std::fs::read(&inner).unwrap(), bytes, "the linked file is as it was"); + let _ = std::fs::remove_dir_all(art.parent().unwrap()); +} + +/// A data set value a script gives a document, and a document a script opens, let no later run +/// read the files they name; once the person saves the document, the files its data sets name are +/// read again. +#[test] +fn what_a_script_adds_to_the_documents_lets_no_later_run_read_more() { + use crate::tests_links::{RED, place, png, session, write}; + let dir = fresh_folder("gate-linked-later"); + let (inside, art) = (dir.join("in"), dir.join("art")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&art).unwrap(); + let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); + let (secret, other, mine) = (p(art.join("secret.png")), p(inside.join("other.vectorcraft")), p(inside.join("mine.vectorcraft"))); + write(&secret, &png(60, 30, RED)); + let mut s = session(); + place(&mut s, &secret); + s.execute("document.save", &json!({"path": other})).unwrap(); + s.execute("file.close", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let read_secret = tried("file.place", &format!("{{path: {secret:?}, at: [200, 150]}}")); + let set = format!( + "vc.run('variable.define', {{name: 'Photo', kind: 'image'}});\nvc.run('dataset.new', {{name: 'X', values: {{Photo: {secret:?}}}}});\n" + ); + run(&mut s, &set).unwrap(); + let mut log = vec![]; + log.push(run(&mut s, &read_secret).unwrap()["log"][0].clone()); + let own = s.active_index().unwrap(); + let r = run_allowed(&mut s, &inside, &tried("document.open", &format!("{{path: {other:?}}}"))).unwrap(); + assert_eq!(r["log"], json!(["ok"]), "{r}"); + log.push(run(&mut s, &read_secret).unwrap()["log"][0].clone()); + assert_eq!(log, [json!("denied"), json!("denied")], "after a data set value, then after a document a script opened"); + assert!(s.set_active(own)); + s.execute("document.save", &json!({"path": mine})).unwrap(); + let saved = run(&mut s, &read_secret).unwrap(); + assert_eq!(saved["log"], json!(["ok"]), "saved by the person: {saved}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A save the person started before a script's command changed the document, and that finishes +/// after it, does not let a later run read the files that change names. +#[test] +fn a_save_started_before_a_scripts_change_lets_no_later_run_read_more() { + use crate::cmd::fileio::{SaveMode, save_job, save_plan}; + use crate::tests_links::{RED, png, session, write}; + let dir = fresh_folder("gate-linked-save"); + let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); + let (secret, mine) = (p(dir.join("secret.png")), p(dir.join("mine.vectorcraft"))); + write(&secret, &png(60, 30, RED)); + let mut s = session(); + let uid = s.doc().unwrap().uid; + let plan = save_plan(&s, SaveMode::SaveAs, &json!({"path": mine})).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + let set = format!( + "vc.run('variable.define', {{name: 'Photo', kind: 'image'}});\nvc.run('dataset.new', {{name: 'X', values: {{Photo: {secret:?}}}}});\n" + ); + run(&mut s, &set).unwrap(); + job.write(|_, _| Ok(())).unwrap(); + job.complete(&mut s, uid); + let r = run(&mut s, &tried("file.place", &format!("{{path: {secret:?}, at: [200, 150]}}"))).unwrap(); + assert_eq!(r["log"], json!(["denied"]), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// A command a script runs does not save into the app's own libraries; the same command run /// outside a script does. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 6c0de9e418..62978099cb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3022,13 +3022,14 @@ VectorCraft writes files by these rules of its own: its `Folder.temp` and `Folder.userData` and to the open documents' own files. Such a command also reads, and does not write, the files that the documents open when the run began link to (linked images, placed files, the plate files of a DCS image and the images their data sets name), so an export, - save, print or package of them includes the linked art. A document the script opens from such a file is not - saved over it for the rest of the run, also after the script is allowed to read that file's folder, and when its - path leads to another file later, the document does not let the script read or write that file. The files are - taken as those links led at the run's - first `vc.run`, and a path that leads to another file since is refused. A link the script adds or points - elsewhere, and a document it opens, does not let it read any file it could not read before. The automation - read roots still apply. + save, print or package of them includes the linked art. The files are taken as those links led at the run's + first `vc.run`, and a path that leads to another file since is refused. + Both rules count each document as the person last opened or saved it. A document that a script's command opened, + in this run or an earlier one, gives the commands no access to its file, and its links give them no file to read. + A document opened from a linked file is therefore not saved over that file unless the script may write there. A + link or data set value that a script's command adds or changes, and a file that a script's command saves a document + to, give later runs no access either. The person's next save of the document ends this. The automation read roots + still apply. A pick inside the folder that holds the settings gives `null` and sets `error` to `Script file access to the app's own folders is not allowed`. - A run with nobody to ask, as over MCP or the command line, gives `null` from every file dialog and sets `error` to diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 37b87a97d9..4c24e057f2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1040,7 +1040,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files, and read the files linked as the next line says; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run`; a path that leads to another file since, a link the script adds or points elsewhere and a document it opens give it no further file to read, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. + - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run` and as the person last opened or saved each document; a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. From a45e2dc710c28b9e81e54fe0adc904e2c8824876 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:57:54 -0800 Subject: [PATCH 4/6] Scripts: a linked file in the settings folder is not read through the linked list The read check for the files the documents link to now applies the script scope's fence of the folder that holds the settings, as the script's own reads do. A file in a place left open inside that folder is still read. --- crates/engine/src/file_access.rs | 35 ++++++++++++++++++++++++++++++-- docs/mcp.md | 3 ++- docs/target-app-parity.md | 2 +- 3 files changed, 36 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c20e37b58e..50b7f725fa 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -348,7 +348,8 @@ impl ScriptGate { Access::Read => self.read.allows(&real) || self.write.allows(&real), Access::Write => self.write.allows(&real), }; - scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || (matches!(access, Access::Read) && self.linked.has(&real)) + let linked = matches!(access, Access::Read) && self.linked.has(&real) && !self.read.keeps_out(&real); + scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked }); if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } } @@ -663,7 +664,13 @@ impl ScriptScope { pub(crate) fn allows(&self, real: &Path) -> bool { (self.files.iter().any(|f| inside(real, f) && real.components().count() == f.components().count()) || self.roots.iter().any(|r| inside(real, r))) - && !self.fenced.iter().any(|f| inside(real, f) && !self.open.iter().any(|o| inside(o, f) && inside(real, o))) + && !self.keeps_out(real) + } + + /// Is the real path `real` in a folder kept out ([`ScriptScope::fence`]), and not in a place + /// left open there? + fn keeps_out(&self, real: &Path) -> bool { + self.fenced.iter().any(|f| inside(real, f) && !self.open.iter().any(|o| inside(o, f) && inside(real, o))) } /// The scope of a script run from a file in the folder whose real path, with its links already @@ -1038,6 +1045,30 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// A linked file in a folder the script's scope keeps out, such as the settings folder, is not + /// read through the gate; one in a place left open there is. + #[test] + fn a_gate_reads_no_linked_file_in_a_folder_kept_out() { + let (base, _) = folders("linked-fenced"); + let (kept, open) = (base.join("outside/kept.svg"), base.join("outside/open/a.svg")); + std::fs::create_dir_all(base.join("outside/open")).unwrap(); + std::fs::write(&kept, "").unwrap(); + std::fs::write(&open, "").unwrap(); + let real = |p: &Path| resolve(&s(p.to_path_buf())).unwrap(); + let mut read = ScriptScope::of_folder(&base.join("in")); + read.fence(real(&base.join("outside")), &[real(&base.join("outside/open"))]); + let gate = ScriptGate { + read, + write: ScriptScope::default(), + documents: vec![], + linked: ScriptGate::real_files([s(kept.clone()), s(open.clone())]), + also: None, + }; + assert!(gate.check(&s(kept), Access::Read).is_err(), "in the folder kept out"); + assert!(gate.check(&s(open), Access::Read).is_ok(), "in a place left open"); + let _ = std::fs::remove_dir_all(base); + } + /// A path read through the linked files gives no access to the file it leads to after it is /// pointed elsewhere by a link in one of its folders. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 62978099cb..9967588b8f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3023,7 +3023,8 @@ VectorCraft writes files by these rules of its own: Such a command also reads, and does not write, the files that the documents open when the run began link to (linked images, placed files, the plate files of a DCS image and the images their data sets name), so an export, save, print or package of them includes the linked art. The files are taken as those links led at the run's - first `vc.run`, and a path that leads to another file since is refused. + first `vc.run`, and a path that leads to another file since is refused. A linked file in the folder that holds + the settings is not read this way. Both rules count each document as the person last opened or saved it. A document that a script's command opened, in this run or an earlier one, gives the commands no access to its file, and its links give them no file to read. A document opened from a linked file is therefore not saved over that file unless the script may write there. A diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4c24e057f2..8af5ee8f9e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1040,7 +1040,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files, and read the files linked as the next line says; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run` and as the person last opened or saved each document; a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. + - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run` and as the person last opened or saved each document; a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; a linked file in the folder that holds the settings is not read, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. From 2fcee167569dbbef78cee791ab510a11e7e97cb9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 04:08:23 -0800 Subject: [PATCH 5/6] Scripts: a recovery copy keeps a script's change through a crash A recovery copy's details now say that a script's command changed the document before the new document entry is written, and a restore writes a copy's details before its document entry in the new area. A crash between the two writes no longer restores a script-changed document without that record, so a later run cannot read the files its links name. The docs say that a linked file in one of the script's own places inside the settings folder is still read. --- crates/engine/src/cmd/recovery.rs | 13 ++++++--- crates/engine/src/tests/recovery.rs | 42 +++++++++++++++++++++++++++++ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 53 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index de64441623..fe6deb0b4b 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -1038,10 +1038,13 @@ impl RecoveryJob { let meta_name = format!("{}{META_EXT}", self.file); // The details name the images, so a crash between writing the document and its details // would pair the new document with the old copy's images: when the new document has - // images the old details don't name, they name both until the new document is in. - let old = read_meta(store, &self.file).images; - if meta.images.iter().any(|(k, r)| old.get(k).is_none_or(|o| o.blob != r.blob)) { + // images the old details don't name, they name both until the new document is in. Likewise + // when a script's command changed the document since the old details: they say so first. + let old_meta = read_meta(store, &self.file); + let old = old_meta.images; + if (meta.by_script && !old_meta.by_script) || meta.images.iter().any(|(k, r)| old.get(k).is_none_or(|o| o.blob != r.blob)) { let mut both = meta.clone(); + both.by_script |= old_meta.by_script; for (k, r) in old { both.images.entry(k).or_insert(r); } @@ -1503,8 +1506,10 @@ fn restore_one(s: &mut Session, store: &Arc, file: &str) -> R for (blob, data) in &blobs { store.write(&format!("{area}/{blob}"), data).map_err(EngineError::Other)?; } - store.write(&format!("{mine}{DOC_EXT}"), &bytes).map_err(EngineError::Other)?; + // The details go first: a crash in between leaves no copy without them (a copy is its + // document entry), and the copy in the old area stays whole. store.write(&format!("{mine}{META_EXT}"), &meta_bytes).map_err(EngineError::Other)?; + store.write(&format!("{mine}{DOC_EXT}"), &bytes).map_err(EngineError::Other)?; } // The copy's images in its old area go with the area, once no copy is left there. store.remove(&format!("{file}{DOC_EXT}")).map_err(EngineError::Other)?; diff --git a/crates/engine/src/tests/recovery.rs b/crates/engine/src/tests/recovery.rs index eed8801efc..613a453d47 100644 --- a/crates/engine/src/tests/recovery.rs +++ b/crates/engine/src/tests/recovery.rs @@ -1714,3 +1714,45 @@ fn a_crash_between_a_copys_document_and_its_details_keeps_every_image() { assert_eq!(images_of(&s), images, "first copy: {first}"); } } + +/// A crash between writing a copy's document and its details, after a script's command changed +/// the document since the last copy, restores the document as one a script opened. +#[test] +fn a_crash_between_a_copys_document_and_its_details_keeps_a_scripts_change() { + let store = Arc::new(MemoryStore::default()); + let mut s = session_in(&store); + s.execute("file.recovery.save", &json!({})).unwrap(); + let source = "vc.run('shape.ellipse', {x: 80, y: 20, width: 20, height: 20});"; + s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap(); + assert!(s.doc().unwrap().by_script.is_some(), "the script's command changed the document"); + let doc = vectorcraft_doc::Document::clone(&s.doc().unwrap().doc); + s.recovery.set_store(Arc::new(DiesAfterDocument { inner: store.clone(), dead: Default::default() })); + assert!(s.execute("file.recovery.save", &json!({})).is_err(), "the details weren't written"); + drop(s); + let mut s = relaunch(&store); + assert_eq!(restored(s.execute("file.recovery.restore", &json!({})).unwrap()), 1); + let count = |d: &vectorcraft_doc::Document| d.layers.iter().map(|l| l.count()).sum::(); + assert_eq!(count(&s.doc().unwrap().doc), count(&doc), "the new document is in"); + assert!(s.doc().unwrap().by_script.is_some(), "restored as a document a script opened"); +} + +/// A crash while a restore moves a copy into the app's own area leaves no copy that a later +/// restore opens without its details: a script's change is kept. +#[test] +fn a_crash_while_a_copy_is_restored_keeps_a_scripts_change() { + let store = Arc::new(MemoryStore::default()); + let mut s = session_in(&store); + let source = "vc.run('shape.ellipse', {x: 80, y: 20, width: 20, height: 20});"; + s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap(); + s.execute("file.recovery.save", &json!({})).unwrap(); + drop(s); + let mut s = Session::new(); + s.recovery.set_store(Arc::new(DiesAfterDocument { inner: store.clone(), dead: Default::default() })); + let _ = s.execute("file.recovery.restore", &json!({})); + drop(s); + let mut s = relaunch(&store); + assert!(restored(s.execute("file.recovery.restore", &json!({})).unwrap()) >= 1); + for st in s.documents().iter().filter(|st| st.recovered) { + assert!(st.by_script.is_some(), "every restored copy keeps the script's change: {}", st.title()); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 9967588b8f..fede932de6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3024,7 +3024,7 @@ VectorCraft writes files by these rules of its own: (linked images, placed files, the plate files of a DCS image and the images their data sets name), so an export, save, print or package of them includes the linked art. The files are taken as those links led at the run's first `vc.run`, and a path that leads to another file since is refused. A linked file in the folder that holds - the settings is not read this way. + the settings is not read this way unless it lies in one of the script's own places inside that folder. Both rules count each document as the person last opened or saved it. A document that a script's command opened, in this run or an earlier one, gives the commands no access to its file, and its links give them no file to read. A document opened from a linked file is therefore not saved over that file unless the script may write there. A diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8af5ee8f9e..b00ba51236 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1040,7 +1040,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files, and read the files linked as the next line says; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run` and as the person last opened or saved each document; a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; a linked file in the folder that holds the settings is not read, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. + - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run` and as the person last opened or saved each document; a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; a linked file in the folder that holds the settings is not read unless it lies in one of the script's own places inside that folder, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. From 162a3c10651c6b6ea7cbe79810fada2224ce9602 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 05:00:00 -0800 Subject: [PATCH 6/6] Scripts: a recovery copy with unreadable details restores as a script's document A recovery copy whose details entry is missing or can't be parsed now restores as a document a script opened, and the details written for the moved copy say so, so a later restore does the same. A valid details entry without the script's mark still restores as the person left it. The script docs now say that a link does not let a command write the file it names: a linked file is written only where the script's write places or an open document's own file allow it. --- crates/engine/src/cmd/recovery.rs | 14 ++++++++++++-- crates/engine/src/tests/recovery.rs | 25 +++++++++++++++++++++++++ docs/mcp.md | 7 ++++--- docs/target-app-parity.md | 2 +- 4 files changed, 42 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index fe6deb0b4b..b81e0b3885 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -1465,8 +1465,18 @@ fn targets(s: &mut Session, store: &dyn RecoveryStore, cmd: &str, p: &Value) -> /// (for Save As) and format. The copy moves into this session's area (another crash keeps it). fn restore_one(s: &mut Session, store: &Arc, file: &str) -> Result { let bytes = store.read(&format!("{file}{DOC_EXT}")).map_err(EngineError::Other)?; - let meta_bytes = store.read(&format!("{file}{META_EXT}")).unwrap_or_default(); - let meta: Meta = serde_json::from_slice(&meta_bytes).unwrap_or_default(); + // A details entry that is missing or can't be parsed does not say whether a script's command + // changed the document: the copy restores as one a script opened, and the details written for + // it say so. + let read = store.read(&format!("{file}{META_EXT}")).ok().and_then(|b| serde_json::from_slice::(&b).ok().map(|m| (m, b))); + let (meta, meta_bytes) = match read { + Some(both) => both, + None => { + let meta = Meta { by_script: true, ..Meta::default() }; + let bytes = serde_json::to_vec_pretty(&meta).map_err(|e| EngineError::Other(e.to_string()))?; + (meta, bytes) + } + }; let (mut doc, _, mut warnings) = fileio::native_file(&bytes).map_err(|e| EngineError::Other(format!("recovery copy `{file}`: {e}")))?; // A frame whose first paragraph continues from the frame before draws it without the // paragraph's first-line indent and list marker. diff --git a/crates/engine/src/tests/recovery.rs b/crates/engine/src/tests/recovery.rs index 613a453d47..08a691f222 100644 --- a/crates/engine/src/tests/recovery.rs +++ b/crates/engine/src/tests/recovery.rs @@ -1756,3 +1756,28 @@ fn a_crash_while_a_copy_is_restored_keeps_a_scripts_change() { assert!(st.by_script.is_some(), "every restored copy keeps the script's change: {}", st.title()); } } + +/// A copy whose details entry is missing or can't be parsed restores as a document a script +/// opened, and so does the copy that restore writes, after a later crash; a valid details entry +/// without the script's mark restores as the person left it. +#[test] +fn a_copy_without_readable_details_restores_as_a_scripts_document() { + let cases: [Option<&[u8]>; 3] = [Some(b"{ not json"), None, Some(b"{}")]; + for details in cases { + let store = Arc::new(MemoryStore::default()); + let mut s = session_in(&store); + let r = s.execute("file.recovery.save", &json!({})).unwrap(); + let entry = format!("{}.json", r["saved"][0]["file"].as_str().unwrap()); + drop(s); + match details { + Some(bytes) => store.write(&entry, bytes).unwrap(), + None => store.remove(&entry).unwrap(), + } + let by_script = details != Some(b"{}".as_slice()); + for round in 1..=2 { + let mut s = relaunch(&store); + assert_eq!(restored(s.execute("file.recovery.restore", &json!({})).unwrap()), 1, "{details:?}, restore {round}"); + assert_eq!(s.doc().unwrap().by_script.is_some(), by_script, "{details:?}, restore {round}"); + } + } +} diff --git a/docs/mcp.md b/docs/mcp.md index fede932de6..1bd3166ee0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3020,9 +3020,10 @@ VectorCraft writes files by these rules of its own: `Script file access denied` and the path, saving into a user library (swatches, brushes, symbols or graphic styles) included; reading the app's own libraries is allowed. A script given as `source` that a person allowed nothing writes only in its `Folder.temp` and `Folder.userData` and to the open documents' own files. - Such a command also reads, and does not write, the files that the documents open when the run began link to - (linked images, placed files, the plate files of a DCS image and the images their data sets name), so an export, - save, print or package of them includes the linked art. The files are taken as those links led at the run's + Such a command also reads the files that the documents open when the run began link to (linked images, placed + files, the plate files of a DCS image and the images their data sets name), so an export, save, print or package + of them includes the linked art. A link does not let the command write the file it names: it writes a linked file + only when the rule above lets it write there. The files are taken as those links led at the run's first `vc.run`, and a path that leads to another file since is refused. A linked file in the folder that holds the settings is not read this way unless it lies in one of the script's own places inside that folder. Both rules count each document as the person last opened or saved it. A document that a script's command opened, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b00ba51236..ce4d074eef 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1040,7 +1040,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files, and read the files linked as the next line says; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run` and as the person last opened or saved each document; a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; a linked file in the folder that holds the settings is not read unless it lies in one of the script's own places inside that folder, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. + - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files as the links led at the run's first `vc.run` and as the person last opened or saved each document; a link does not let them write the file it names, and they write a linked file only where the previous line lets them write (the script's own write places and the open documents' own files); a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; a linked file in the folder that holds the settings is not read unless it lies in one of the script's own places inside that folder, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`.