mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-24 18:32:23 +00:00
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.
This commit is contained in:
@@ -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;
|
||||
|
||||
@@ -410,7 +410,8 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option<Found> {
|
||||
/// 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<String> {
|
||||
let mut out = vec![];
|
||||
for g in groups(d, None) {
|
||||
|
||||
@@ -874,6 +874,11 @@ struct Meta {
|
||||
/// images were kept apart: the document entry holds them).
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
images: BTreeMap<String, ImageRef>,
|
||||
/// 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<dyn RecoveryStore>) -> Result<(Vec<Reco
|
||||
links_from: st.links_from.clone().filter(|_| st.path.is_none()),
|
||||
// Filled in as the copy is written.
|
||||
images: BTreeMap::new(),
|
||||
by_script: st.by_script.is_some(),
|
||||
};
|
||||
out.push(RecoveryJob { uid: st.uid, file, title, meta, save, store: store.clone() });
|
||||
}
|
||||
@@ -1517,6 +1523,9 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, 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));
|
||||
}
|
||||
|
||||
@@ -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<Arc<file_access::AutomationRoots>>,
|
||||
/// 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<ByScript>,
|
||||
/// 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<cmd::inline::Resolved>,
|
||||
}
|
||||
|
||||
/// 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<Document>, path: Option<String>, links_from: Option<String> },
|
||||
}
|
||||
|
||||
/// 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<Document>, 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<Document>, &Option<String>, &Option<String>)>) {
|
||||
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.
|
||||
|
||||
@@ -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<String>,
|
||||
/// 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<Arc<ScriptGate>>,
|
||||
}
|
||||
|
||||
/// 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<std::sync::Mutex<Vec<String>>>,
|
||||
}
|
||||
|
||||
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<String> {
|
||||
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<Arc<AutomationRoots>> {
|
||||
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<String>| 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, "<svg><rect/></svg>").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<String>| 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);
|
||||
}
|
||||
|
||||
@@ -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<String>, 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 }
|
||||
|
||||
@@ -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<Vec<RunDoc>>,
|
||||
/// The files of the documents open when the run began
|
||||
/// ([`crate::file_access::ScriptGate::keeping_linked_read_only`]).
|
||||
opened_before: Vec<String>,
|
||||
/// 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<crate::file_access::LinkedFiles>,
|
||||
}
|
||||
|
||||
@@ -816,9 +814,9 @@ type RunDoc = (Arc<crate::Document>, Option<String>, Option<String>);
|
||||
|
||||
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<crate::Document>, 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());
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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]
|
||||
|
||||
+8
-7
@@ -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
|
||||
|
||||
@@ -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`.
|
||||
|
||||
Reference in New Issue
Block a user