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 fd76896ce3..1115c7e917 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,29 @@ 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, 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) { + 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/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 5a70d49ab7..54906b5a1d 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. @@ -1033,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); } @@ -1195,6 +1203,7 @@ pub fn jobs(s: &mut Session, store: &Arc) -> Result<(Vec /// (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::decode_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. @@ -1497,8 +1516,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)?; @@ -1519,6 +1540,9 @@ fn restore_one(s: &mut Session, store: &Arc, 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 39303760a3..2494020660 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -129,6 +129,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, @@ -147,6 +152,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)] @@ -385,6 +401,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(), @@ -392,6 +409,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 abc7fa0740..c96bf81084 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, each as the person last left the document. use std::cell::RefCell; use std::ffi::OsString; @@ -276,19 +277,56 @@ 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 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 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 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]>, +} + +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() + } +} + 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) -> LinkedFiles { + 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(); + LinkedFiles { files: real.into() } + } + /// 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 { @@ -310,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)) + 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}")) } } @@ -354,6 +393,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()) { @@ -620,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 @@ -920,8 +970,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: LinkedFiles::default(), + 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 { @@ -944,7 +999,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: LinkedFiles::default(), + 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())); @@ -959,6 +1020,114 @@ 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.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(); + 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 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] + 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(); + #[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 gate = ScriptGate { + read: ScriptScope::default(), + write: ScriptScope::default(), + documents: vec![], + linked: ScriptGate::real_files([doc.clone()]), + also: None, + }; + 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)); + for (path, access) in [(&doc, Access::Read), (&doc, Access::Write), (&elsewhere, Access::Read), (&elsewhere, Access::Write)] { + assert!(gate.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] + 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 94ef3bdf9e..9bd7815c8b 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -54,7 +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`]). +//! 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 @@ -462,10 +464,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 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 } } /// 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..6d7181d283 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -799,6 +799,35 @@ 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 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 the documents open when the run began link to as the person left them + /// ([`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 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(|| { + 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,9 +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. - 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 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()) { @@ -2040,6 +2079,14 @@ 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() + .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()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 93a4f70580..2ca404c9d7 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -417,6 +417,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/recovery.rs b/crates/engine/src/tests/recovery.rs index aa5a7e5ab5..80d993870c 100644 --- a/crates/engine/src/tests/recovery.rs +++ b/crates/engine/src/tests/recovery.rs @@ -1785,3 +1785,70 @@ 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()); + } +} + +/// 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/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index bf8154f9a7..a57d3be23b 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -417,6 +417,178 @@ 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 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 414272ffcb..f3bd0063c9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3054,6 +3054,18 @@ 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 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, + 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 902dbd890e..027c7707ee 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1045,7 +1045,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 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: the `hidden` setter and `createAlias(target)` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/)), with setting `hidden`, `rename` and `remove` acting on an alias itself ([Using File and Folder objects](https://extendscript.docsforadobe.dev/file-system-access/using-file-and-folder-objects/)). VectorCraft's own rules: on Unix a name that starts with a dot is hidden, so setting `hidden` renames the file with one dot added or its leading dots taken off, and both names must be places the script may write; `createAlias` makes a symbolic link to the real path of a file the script may read, in a place it may write where nothing is, a link that leads nowhere included; a link is checked again each time it is used; on Windows both set `error` and change nothing. `crates/engine/src/tests/script_io.rs`. - 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`.