From 9965de4ec2b9f05e02cd67f45083a2d951d91c36 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:27:48 -0800 Subject: [PATCH 1/9] Preferences: list the script file access kept with Always, with Revoke Preferences > General gets a Script File Access section after Show External Script Warning. It reads script.grants and shows one row for each script and path, grouped by script, with the widest access any kept version has (read file, read and write file, or read and write folder). Revoke runs script.grants.revoke for that script and path, which removes every kept version of the pair, so the next run asks again. The list is read again after a revoke, the keyboard focus moves to the row now in that place, and the status bar says whether anything was removed or shows the command's error. Paths and script names show control and bidirectional formatting characters as escapes and are cut at 1,024 characters. A grants file that is not well formed or is larger than 4 MiB makes Revoke show the error and leaves the file as it was. Without a settings folder, and on the web, the section is not shown. The rows are drawn only where they are in view, so a long list stays fast. --- crates/ui-egui/src/i18n/bg.tsv | 8 + crates/ui-egui/src/i18n/bs.tsv | 8 + crates/ui-egui/src/i18n/ca.tsv | 8 + crates/ui-egui/src/i18n/cs.tsv | 8 + crates/ui-egui/src/i18n/da.tsv | 8 + crates/ui-egui/src/i18n/de.tsv | 8 + crates/ui-egui/src/i18n/el.tsv | 8 + crates/ui-egui/src/i18n/es.tsv | 8 + crates/ui-egui/src/i18n/fi.tsv | 8 + crates/ui-egui/src/i18n/fr.tsv | 8 + crates/ui-egui/src/i18n/gu.tsv | 9 + crates/ui-egui/src/i18n/hi.tsv | 8 + crates/ui-egui/src/i18n/hu.tsv | 8 + crates/ui-egui/src/i18n/id.tsv | 8 + crates/ui-egui/src/i18n/it.tsv | 8 + crates/ui-egui/src/i18n/ja.tsv | 8 + crates/ui-egui/src/i18n/ka.tsv | 8 + crates/ui-egui/src/i18n/ko.tsv | 8 + crates/ui-egui/src/i18n/nl.tsv | 8 + crates/ui-egui/src/i18n/pl.tsv | 8 + crates/ui-egui/src/i18n/pt-br.tsv | 8 + crates/ui-egui/src/i18n/ru.tsv | 8 + crates/ui-egui/src/i18n/sv.tsv | 8 + crates/ui-egui/src/i18n/tests.rs | 35 +++ crates/ui-egui/src/i18n/tr.tsv | 8 + crates/ui-egui/src/i18n/uk.tsv | 8 + crates/ui-egui/src/i18n/vi.tsv | 8 + crates/ui-egui/src/i18n/zh-hans.tsv | 8 + crates/ui-egui/src/i18n/zh-hant.tsv | 8 + crates/ui-egui/src/prefs_dialog.rs | 6 + .../ui-egui/src/prefs_dialog/script_access.rs | 202 ++++++++++++++++++ crates/ui-egui/src/prefs_dialog/tests.rs | 174 +++++++++++++++ docs/target-app-parity.md | 1 + 33 files changed, 643 insertions(+) create mode 100644 crates/ui-egui/src/prefs_dialog/script_access.rs diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..090d7a66d6 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4711,6 +4711,14 @@ axis Both И двете The script asks to read and write a folder you choose, with everything in it. Скриптът иска да чете и записва папка, която изберете, с цялото ѝ съдържание. Allow Once Разреши веднъж Always Allow This Script Винаги разрешавай този скрипт + No script has kept file access. Няма скрипт със запазен достъп до файлове. + Read file Четене на файл + Read and write file Четене и запис на файл + Read and write folder Четене и запис на папка + Revoke Отнемане + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Отнемането премахва достъпа, запазен за всяка версия на скрипта. Достъпът до папка обхваща всичко в нея. +@msg Script file access revoked Достъпът на скрипта до файлове е отнет +@msg The script file access was already revoked Достъпът на скрипта до файлове вече е отнет Deny Откажи A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скриптът може да променя отворените документи и да записва файлове чрез командите, които изпълнява. Изпълнявайте само скриптове, на които имате доверие. Do not show this warning again Не показвай повече това предупреждение diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..2c4659b00c 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5115,6 +5115,14 @@ imageTrace Outline Obris The script asks to read and write a folder you choose, with everything in it. Skripta traži da čita i piše folder koji odaberete, sa svim što je u njemu. Allow Once Dozvoli jednom Always Allow This Script Uvijek dozvoli ovu skriptu + No script has kept file access. Nijedna skripta nema sačuvan pristup datotekama. + Read file Čitanje datoteke + Read and write file Čitanje i pisanje datoteke + Read and write folder Čitanje i pisanje foldera + Revoke Opozovi + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Opozovi uklanja pristup sačuvan za svaku verziju skripte. Pristup folderu obuhvata sve u njemu. +@msg Script file access revoked Pristup skripte datotekama je opozvan +@msg The script file access was already revoked Pristup skripte datotekama je već opozvan Deny Odbij A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skripta može mijenjati otvorene dokumente i pisati datoteke putem naredbi koje pokreće. Pokrećite samo skripte kojima vjerujete. Do not show this warning again Ne prikazuj više ovo upozorenje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..dc052e1209 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6422,6 +6422,14 @@ digits Malayalam Malaiàlam The script asks to read and write a folder you choose, with everything in it. L’script demana llegir i escriure una carpeta que trieu, amb tot el que conté. Allow Once Permet un cop Always Allow This Script Permet sempre aquest script + No script has kept file access. Cap script no ha conservat accés als fitxers. + Read file Lectura del fitxer + Read and write file Lectura i escriptura del fitxer + Read and write folder Lectura i escriptura de la carpeta + Revoke Revoca + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Revoca elimina l’accés conservat per a cada versió de l’script. L’accés a una carpeta inclou tot el que conté. +@msg Script file access revoked S’ha revocat l’accés de l’script als fitxers +@msg The script file access was already revoked L’accés de l’script als fitxers ja s’havia revocat Deny Denega A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script pot canviar els documents oberts i escriure fitxers mitjançant les ordres que executa. Executeu només scripts de confiança. Do not show this warning again No tornis a mostrar aquest avís diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..baa6fdb5a0 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5230,6 +5230,14 @@ imageTrace Outline Obrys The script asks to read and write a folder you choose, with everything in it. Skript žádá o čtení a zápis složky, kterou vyberete, se vším, co obsahuje. Allow Once Povolit jednou Always Allow This Script Vždy povolit tento skript + No script has kept file access. Žádný skript nemá uložený přístup k souborům. + Read file Čtení souboru + Read and write file Čtení a zápis souboru + Read and write folder Čtení a zápis složky + Revoke Odvolat + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Odvolat odebere přístup uložený pro každou verzi skriptu. Přístup ke složce zahrnuje vše, co obsahuje. +@msg Script file access revoked Přístup skriptu k souborům byl odvolán +@msg The script file access was already revoked Přístup skriptu k souborům už byl odvolán Deny Zamítnout A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skript může měnit otevřené dokumenty a prostřednictvím příkazů, které spouští, zapisovat soubory. Spouštějte jen skripty, kterým důvěřujete. Do not show this warning again Toto upozornění již nezobrazovat diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..47c721d229 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7660,6 +7660,14 @@ imageTrace Outline Kontur The script asks to read and write a folder you choose, with everything in it. Scriptet beder om at læse og skrive en mappe, du vælger, med alt indhold. Allow Once Tillad én gang Always Allow This Script Tillad altid dette script + No script has kept file access. Intet script har gemt adgang til filer. + Read file Læs fil + Read and write file Læs og skriv fil + Read and write folder Læs og skriv mappe + Revoke Tilbagekald + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Tilbagekald fjerner den adgang, der er gemt for hver version af scriptet. Adgang til en mappe omfatter alt i den. +@msg Script file access revoked Scriptets adgang til filer er tilbagekaldt +@msg The script file access was already revoked Scriptets adgang til filer var allerede tilbagekaldt Deny Afvis A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Et script kan ændre de åbne dokumenter og skrive filer gennem de kommandoer, det kører. Kør kun scripts, du stoler på. Do not show this warning again Vis ikke denne advarsel igen diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..a625e018ef 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4815,6 +4815,14 @@ theme Appearance Erscheinungsbild The script asks to read and write a folder you choose, with everything in it. Das Skript möchte einen Ordner, den Sie auswählen, mit seinem gesamten Inhalt lesen und schreiben. Allow Once Einmal erlauben Always Allow This Script Dieses Skript immer erlauben + No script has kept file access. Kein Skript hat einen gespeicherten Dateizugriff. + Read file Datei lesen + Read and write file Datei lesen und schreiben + Read and write folder Ordner lesen und schreiben + Revoke Widerrufen + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. „Widerrufen“ entfernt den Zugriff, der für jede Version des Skripts gespeichert ist. Der Zugriff auf einen Ordner umfasst seinen gesamten Inhalt. +@msg Script file access revoked Dateizugriff des Skripts widerrufen +@msg The script file access was already revoked Der Dateizugriff des Skripts wurde bereits widerrufen Deny Ablehnen A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ein Skript kann die geöffneten Dokumente ändern und über die ausgeführten Befehle Dateien schreiben. Führen Sie nur Skripte aus, denen Sie vertrauen. Do not show this warning again Diese Warnung nicht mehr anzeigen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..e428decf7c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2619,6 +2619,14 @@ axis Both Και τα δύο The script asks to read and write a folder you choose, with everything in it. Το σενάριο ζητά να διαβάσει και να γράψει έναν φάκελο που θα επιλέξετε, με όλο το περιεχόμενό του. Allow Once Να επιτραπεί μία φορά Always Allow This Script Να επιτρέπεται πάντα αυτό το σενάριο + No script has kept file access. Κανένα σενάριο δεν έχει αποθηκευμένη πρόσβαση σε αρχεία. + Read file Ανάγνωση αρχείου + Read and write file Ανάγνωση και εγγραφή αρχείου + Read and write folder Ανάγνωση και εγγραφή φακέλου + Revoke Ανάκληση + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Η ανάκληση αφαιρεί την πρόσβαση που έχει αποθηκευτεί για κάθε έκδοση του σεναρίου. Η πρόσβαση σε φάκελο καλύπτει όλο το περιεχόμενό του. +@msg Script file access revoked Η πρόσβαση του σεναρίου σε αρχεία ανακλήθηκε +@msg The script file access was already revoked Η πρόσβαση του σεναρίου σε αρχεία είχε ήδη ανακληθεί Deny Άρνηση A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ένα σενάριο μπορεί να αλλάξει τα ανοιχτά έγγραφα και να γράψει αρχεία μέσω των εντολών που εκτελεί. Εκτελείτε μόνο σενάρια που εμπιστεύεστε. Do not show this warning again Να μην εμφανιστεί ξανά αυτή η προειδοποίηση diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..6c9867b07c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4894,6 +4894,14 @@ axis Both Ambos The script asks to read and write a folder you choose, with everything in it. El script pide leer y escribir una carpeta que usted elija, con todo su contenido. Allow Once Permitir una vez Always Allow This Script Permitir siempre este script + No script has kept file access. Ningún script tiene acceso a archivos guardado. + Read file Leer archivo + Read and write file Leer y escribir archivo + Read and write folder Leer y escribir carpeta + Revoke Revocar + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Revocar quita el acceso guardado para cada versión del script. El acceso a una carpeta abarca todo su contenido. +@msg Script file access revoked Acceso del script a archivos revocado +@msg The script file access was already revoked El acceso del script a archivos ya estaba revocado Deny Denegar A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script puede cambiar los documentos abiertos y escribir archivos mediante los comandos que ejecuta. Ejecute solo scripts de confianza. Do not show this warning again No volver a mostrar esta advertencia diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..bba3adf2e7 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5135,6 +5135,14 @@ imageTrace Outline Ääriviiva The script asks to read and write a folder you choose, with everything in it. Komentosarja pyytää lupaa lukea ja kirjoittaa valitsemasi kansion ja kaiken sen sisällön. Allow Once Salli kerran Always Allow This Script Salli tämä komentosarja aina + No script has kept file access. Millään komentosarjalla ei ole tallennettua tiedostojen käyttöoikeutta. + Read file Tiedoston luku + Read and write file Tiedoston luku ja kirjoitus + Read and write folder Kansion luku ja kirjoitus + Revoke Peruuta oikeus + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Peruuta oikeus poistaa käyttöoikeuden, joka on tallennettu komentosarjan jokaiselle versiolle. Kansion käyttöoikeus kattaa kaiken sen sisällön. +@msg Script file access revoked Komentosarjan tiedostojen käyttöoikeus peruttu +@msg The script file access was already revoked Komentosarjan tiedostojen käyttöoikeus oli jo peruttu Deny Estä A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Komentosarja voi muuttaa avoimia asiakirjoja ja kirjoittaa tiedostoja suorittamillaan komennoilla. Suorita vain komentosarjoja, joihin luotat. Do not show this warning again Älä näytä tätä varoitusta uudelleen diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..f31aad04d4 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4876,6 +4876,14 @@ axis Both Les deux The script asks to read and write a folder you choose, with everything in it. Le script demande à lire et écrire un dossier que vous choisissez, avec tout son contenu. Allow Once Autoriser une fois Always Allow This Script Toujours autoriser ce script + No script has kept file access. Aucun script n’a conservé d’accès aux fichiers. + Read file Lire le fichier + Read and write file Lire et écrire le fichier + Read and write folder Lire et écrire le dossier + Revoke Révoquer + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Révoquer supprime l’accès conservé pour chaque version du script. L’accès à un dossier couvre tout son contenu. +@msg Script file access revoked Accès du script aux fichiers révoqué +@msg The script file access was already revoked L’accès du script aux fichiers était déjà révoqué Deny Refuser A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script peut modifier les documents ouverts et écrire des fichiers au moyen des commandes qu’il exécute. N’exécutez que des scripts de confiance. Do not show this warning again Ne plus afficher cet avertissement diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..ea24ffdd4f 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3979,6 +3979,15 @@ arrowhead Feather પીંછું Show East Asian Options પૂર્વ એશિયન વિકલ્પો બતાવો Show Edges કિનારીઓ બતાવો Show External Script Warning બાહ્ય સ્ક્રિપ્ટ ચેતવણી બતાવો + Script File Access સ્ક્રિપ્ટની ફાઇલ ઍક્સેસ + No script has kept file access. કોઈ સ્ક્રિપ્ટ પાસે સાચવેલ ફાઇલ ઍક્સેસ નથી. + Read file ફાઇલ વાંચો + Read and write file ફાઇલ વાંચો અને લખો + Read and write folder ફોલ્ડર વાંચો અને લખો + Revoke પરવાનગી પાછી ખેંચો + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. પરવાનગી પાછી ખેંચવાથી સ્ક્રિપ્ટના દરેક સંસ્કરણ માટે સાચવેલ ઍક્સેસ દૂર થાય છે. ફોલ્ડરની ઍક્સેસમાં તેની અંદરનું બધું આવે છે. +@msg Script file access revoked સ્ક્રિપ્ટની ફાઇલ ઍક્સેસ પાછી ખેંચી +@msg The script file access was already revoked સ્ક્રિપ્ટની ફાઇલ ઍક્સેસ પહેલેથી પાછી ખેંચાઈ હતી Show Find Field શોધ ફીલ્ડ બતાવો Show Font Height Options ફોન્ટ ઊંચાઈ વિકલ્પો બતાવો Show Font Names in English ફોન્ટ નામો અંગ્રેજીમાં બતાવો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..9e8f4858ca 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7568,6 +7568,14 @@ arrowhead Feather पंख The script asks to read and write a folder you choose, with everything in it. स्क्रिप्ट आपका चुना हुआ फ़ोल्डर और उसकी सारी सामग्री पढ़ने और लिखने की अनुमति माँगती है। Allow Once एक बार अनुमति दें Always Allow This Script इस स्क्रिप्ट को हमेशा अनुमति दें + No script has kept file access. किसी भी स्क्रिप्ट के पास रखी गई फ़ाइल पहुँच नहीं है। + Read file फ़ाइल पढ़ें + Read and write file फ़ाइल पढ़ें और लिखें + Read and write folder फ़ोल्डर पढ़ें और लिखें + Revoke वापस लें + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. वापस लें स्क्रिप्ट के हर संस्करण के लिए रखी गई पहुँच हटा देता है। किसी फ़ोल्डर की पहुँच में उसके भीतर का सब कुछ शामिल है। +@msg Script file access revoked स्क्रिप्ट की फ़ाइल पहुँच वापस ली गई +@msg The script file access was already revoked स्क्रिप्ट की फ़ाइल पहुँच पहले ही वापस ली जा चुकी थी Deny अस्वीकार करें A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. स्क्रिप्ट खुले दस्तावेज़ बदल सकती है और अपने चलाए कमांड से फ़ाइलें लिख सकती है। केवल भरोसेमंद स्क्रिप्ट चलाएँ। Do not show this warning again यह चेतावनी फिर न दिखाएँ diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..3a99075b4c 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5747,6 +5747,14 @@ imageTrace Outline Körvonal The script asks to read and write a folder you choose, with everything in it. A parancsfájl egy Ön által választott mappa és teljes tartalma olvasását és írását kéri. Allow Once Engedélyezés egyszer Always Allow This Script A parancsfájl engedélyezése mindig + No script has kept file access. Egy parancsfájlnak sincs megőrzött fájlhozzáférése. + Read file Fájl olvasása + Read and write file Fájl olvasása és írása + Read and write folder Mappa olvasása és írása + Revoke Engedély visszavonása + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Az Engedély visszavonása a parancsfájl minden verziójához megőrzött hozzáférést eltávolítja. Egy mappához való hozzáférés a teljes tartalmára kiterjed. +@msg Script file access revoked A parancsfájl fájlhozzáférése visszavonva +@msg The script file access was already revoked A parancsfájl fájlhozzáférése már vissza volt vonva Deny Elutasítás A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. A parancsfájl módosíthatja a megnyitott dokumentumokat, és a futtatott parancsokkal fájlokat írhat. Csak megbízható parancsfájlokat futtasson. Do not show this warning again Ne jelenjen meg többé ez a figyelmeztetés diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..853ee465b7 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5526,6 +5526,14 @@ imageTrace Outline Kontur The script asks to read and write a folder you choose, with everything in it. Skrip meminta izin untuk membaca dan menulis folder yang Anda pilih, beserta seluruh isinya. Allow Once Izinkan Sekali Always Allow This Script Selalu Izinkan Skrip Ini + No script has kept file access. Tidak ada skrip yang memiliki akses berkas tersimpan. + Read file Baca Berkas + Read and write file Baca dan Tulis Berkas + Read and write folder Baca dan Tulis Folder + Revoke Cabut + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Cabut menghapus akses yang disimpan untuk setiap versi skrip. Akses ke folder mencakup semua isinya. +@msg Script file access revoked Akses berkas skrip dicabut +@msg The script file access was already revoked Akses berkas skrip sudah dicabut Deny Tolak A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrip dapat mengubah dokumen yang terbuka dan menulis file melalui perintah yang dijalankannya. Jalankan hanya skrip yang Anda percayai. Do not show this warning again Jangan tampilkan peringatan ini lagi diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..5a290e168a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4953,6 +4953,14 @@ axis Both Entrambi The script asks to read and write a folder you choose, with everything in it. Lo script chiede di leggere e scrivere una cartella che scegli, con tutto il suo contenuto. Allow Once Consenti una volta Always Allow This Script Consenti sempre questo script + No script has kept file access. Nessuno script ha conservato un accesso ai file. + Read file Lettura file + Read and write file Lettura e scrittura file + Read and write folder Lettura e scrittura cartella + Revoke Revoca + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Revoca rimuove l'accesso conservato per ogni versione dello script. L'accesso a una cartella comprende tutto il suo contenuto. +@msg Script file access revoked Accesso dello script ai file revocato +@msg The script file access was already revoked L'accesso dello script ai file era già stato revocato Deny Nega A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Uno script può modificare i documenti aperti e scrivere file tramite i comandi che esegue. Esegui solo script di cui ti fidi. Do not show this warning again Non mostrare più questo avviso diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..6dc915f9aa 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5779,6 +5779,14 @@ variable-list-end {0}, {1} {0}、{1} The script asks to read and write a folder you choose, with everything in it. スクリプトが、選択したフォルダーとその中身すべての読み書きを求めています。 Allow Once 今回のみ許可 Always Allow This Script このスクリプトを常に許可 + No script has kept file access. ファイルアクセスを保持しているスクリプトはありません。 + Read file ファイルの読み取り + Read and write file ファイルの読み取りと書き込み + Read and write folder フォルダーの読み取りと書き込み + Revoke 許可を取り消す + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. 「許可を取り消す」は、スクリプトのすべてのバージョンに保持されたアクセスを削除します。フォルダーへのアクセスには、その中のすべてが含まれます。 +@msg Script file access revoked スクリプトのファイルアクセスを取り消しました +@msg The script file access was already revoked スクリプトのファイルアクセスはすでに取り消されています Deny 拒否 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. スクリプトは開いているドキュメントを変更でき、実行するコマンドを通じてファイルを書き込むこともできます。信頼できるスクリプトだけを実行してください。 Do not show this warning again 今後この警告を表示しない diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..6932462a4e 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8448,6 +8448,14 @@ imageTrace Outline კონტური The script asks to read and write a folder you choose, with everything in it. სკრიპტი ითხოვს თქვენ მიერ არჩეული საქაღალდისა და მთელი მისი შიგთავსის წაკითხვასა და ჩაწერას. Allow Once ერთხელ დაშვება Always Allow This Script ამ სკრიპტის ყოველთვის დაშვება + No script has kept file access. არცერთ სკრიპტს არ აქვს შენახული წვდომა ფაილებზე. + Read file ფაილის წაკითხვა + Read and write file ფაილის წაკითხვა და ჩაწერა + Read and write folder საქაღალდის წაკითხვა და ჩაწერა + Revoke ნებართვის გაუქმება + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. ნებართვის გაუქმება შლის სკრიპტის ყველა ვერსიისთვის შენახულ წვდომას. საქაღალდეზე წვდომა მოიცავს მასში არსებულ ყველაფერს. +@msg Script file access revoked სკრიპტის წვდომა ფაილებზე გაუქმდა +@msg The script file access was already revoked სკრიპტის წვდომა ფაილებზე უკვე გაუქმებული იყო Deny უარყოფა A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. სკრიპტს შეუძლია ღია დოკუმენტების შეცვლა და მის მიერ გაშვებული ბრძანებებით ფაილების ჩაწერა. გაუშვით მხოლოდ სანდო სკრიპტები. Do not show this warning again აღარ აჩვენო ეს გაფრთხილება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..bddb440aee 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5708,6 +5708,14 @@ variable-list-end {0}, {1} {0} 및 {1} The script asks to read and write a folder you choose, with everything in it. 스크립트가 선택한 폴더와 그 안의 모든 항목을 읽고 쓰도록 요청합니다. Allow Once 한 번 허용 Always Allow This Script 이 스크립트 항상 허용 + No script has kept file access. 파일 접근을 유지한 스크립트가 없습니다. + Read file 파일 읽기 + Read and write file 파일 읽기 및 쓰기 + Read and write folder 폴더 읽기 및 쓰기 + Revoke 권한 취소 + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. 권한 취소는 스크립트의 모든 버전에 유지된 접근을 제거합니다. 폴더 접근에는 폴더 안의 모든 항목이 포함됩니다. +@msg Script file access revoked 스크립트 파일 접근 권한을 취소했습니다 +@msg The script file access was already revoked 스크립트 파일 접근 권한이 이미 취소되었습니다 Deny 거부 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 스크립트는 열려 있는 문서를 변경하고 실행하는 명령을 통해 파일을 쓸 수 있습니다. 신뢰할 수 있는 스크립트만 실행하세요. Do not show this warning again 이 경고를 다시 표시하지 않음 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..d00f9960df 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5526,6 +5526,14 @@ imageTrace Outline Contour The script asks to read and write a folder you choose, with everything in it. Het script vraagt een map die u kiest te lezen en te schrijven, met alles wat erin staat. Allow Once Eenmaal toestaan Always Allow This Script Dit script altijd toestaan + No script has kept file access. Geen enkel script heeft bewaarde bestandstoegang. + Read file Bestand lezen + Read and write file Bestand lezen en schrijven + Read and write folder Map lezen en schrijven + Revoke Intrekken + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Intrekken verwijdert de toegang die voor elke versie van het script is bewaard. Toegang tot een map omvat alles erin. +@msg Script file access revoked Bestandstoegang van script ingetrokken +@msg The script file access was already revoked De bestandstoegang van het script was al ingetrokken Deny Weigeren A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Een script kan de geopende documenten wijzigen en via de uitgevoerde opdrachten bestanden schrijven. Voer alleen scripts uit die u vertrouwt. Do not show this warning again Deze waarschuwing niet meer tonen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..6b41f2febc 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5058,6 +5058,14 @@ imageTrace Outline Kontur The script asks to read and write a folder you choose, with everything in it. Skrypt prosi o odczyt i zapis wybranego przez Ciebie folderu wraz z całą jego zawartością. Allow Once Zezwól raz Always Allow This Script Zawsze zezwalaj temu skryptowi + No script has kept file access. Żaden skrypt nie ma zachowanego dostępu do plików. + Read file Odczyt pliku + Read and write file Odczyt i zapis pliku + Read and write folder Odczyt i zapis folderu + Revoke Odwołaj + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Odwołaj usuwa dostęp zachowany dla każdej wersji skryptu. Dostęp do folderu obejmuje całą jego zawartość. +@msg Script file access revoked Odwołano dostęp skryptu do plików +@msg The script file access was already revoked Dostęp skryptu do plików został już odwołany Deny Odmów A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrypt może zmieniać otwarte dokumenty i zapisywać pliki za pomocą wykonywanych poleceń. Uruchamiaj tylko skrypty, którym ufasz. Do not show this warning again Nie pokazuj więcej tego ostrzeżenia diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..6cc30c65b5 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6097,6 +6097,14 @@ variable-list-end {0}, {1} {0} e {1} The script asks to read and write a folder you choose, with everything in it. O script pede para ler e gravar uma pasta que você escolher, com todo o seu conteúdo. Allow Once Permitir uma vez Always Allow This Script Sempre permitir este script + No script has kept file access. Nenhum script manteve acesso a arquivos. + Read file Ler arquivo + Read and write file Ler e gravar arquivo + Read and write folder Ler e gravar pasta + Revoke Revogar + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Revogar remove o acesso mantido para cada versão do script. O acesso a uma pasta abrange tudo o que ela contém. +@msg Script file access revoked Acesso do script a arquivos revogado +@msg The script file access was already revoked O acesso do script a arquivos já estava revogado Deny Negar A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Um script pode alterar os documentos abertos e gravar arquivos pelos comandos que executa. Execute apenas scripts em que você confia. Do not show this warning again Não mostrar este aviso novamente diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..59bc9f7d62 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4929,6 +4929,14 @@ axis Both Оба The script asks to read and write a folder you choose, with everything in it. Скрипт запрашивает чтение и запись выбранной вами папки со всем её содержимым. Allow Once Разрешить один раз Always Allow This Script Всегда разрешать этот скрипт + No script has kept file access. Ни у одного скрипта нет сохранённого доступа к файлам. + Read file Чтение файла + Read and write file Чтение и запись файла + Read and write folder Чтение и запись папки + Revoke Отозвать + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. «Отозвать» удаляет доступ, сохранённый для каждой версии скрипта. Доступ к папке распространяется на всё её содержимое. +@msg Script file access revoked Доступ скрипта к файлам отозван +@msg The script file access was already revoked Доступ скрипта к файлам уже был отозван Deny Запретить A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт может изменять открытые документы и записывать файлы с помощью выполняемых команд. Запускайте только те скрипты, которым доверяете. Do not show this warning again Больше не показывать это предупреждение diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..d8355b2c4a 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4791,6 +4791,14 @@ axis Both Båda The script asks to read and write a folder you choose, with everything in it. Skriptet ber om att läsa och skriva en mapp som du väljer, med allt innehåll. Allow Once Tillåt en gång Always Allow This Script Tillåt alltid det här skriptet + No script has kept file access. Inget skript har sparad filåtkomst. + Read file Läs fil + Read and write file Läs och skriv fil + Read and write folder Läs och skriv mapp + Revoke Återkalla + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Återkalla tar bort åtkomsten som sparats för varje version av skriptet. Åtkomst till en mapp omfattar allt i den. +@msg Script file access revoked Skriptets filåtkomst har återkallats +@msg The script file access was already revoked Skriptets filåtkomst var redan återkallad Deny Neka A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ett skript kan ändra de öppna dokumenten och skriva filer genom de kommandon det kör. Kör bara skript du litar på. Do not show this warning again Visa inte den här varningen igen diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..a95d4cbf1b 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -3024,6 +3024,41 @@ fn script_file_messages_translate_in_every_complete_message_language() { assert_eq!(message(de, "Script file access denied: C:/x/a.txt"), "Dateizugriff des Skripts verweigert: C:/x/a.txt"); } +/// Preferences › General › Script File Access: its labels have a row in every catalog with menus, +/// and the status messages of its Revoke button a translated row in every complete-message +/// language. +#[test] +fn script_file_access_list_strings_are_in_complete_catalogs() { + let labels = [ + "Script File Access", + "No script has kept file access.", + "Read file", + "Read and write file", + "Read and write folder", + "Revoke", + "Revoke removes the access kept for every version of the script. A folder's access covers everything in it.", + ]; + let literals = tl_literals(); + let mut missing = vec![]; + for label in labels { + assert!(literals.contains(label), "{label:?} is no longer a tl! literal"); + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + if lang.catalog().plain(label).is_none_or(|row| row == label) { + missing.push(format!("{} {label}", lang.code)); + } + } + } + assert!(missing.is_empty(), "{missing:?}"); + let messages = message_literals(); + for m in ["Script file access revoked", "The script file access was already revoked"] { + assert!(messages.contains(m), "{m:?} is no longer a message"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert_ne!(message(lang, m), m, "{code}: {m}"); + } + } +} + /// The error that `text.setFormat` and the paragraph style commands give when a justification /// setting's Minimum, Desired and Maximum are out of order is translated in every /// complete-message language, with the setting's name kept. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..cd74ca9166 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4643,6 +4643,14 @@ axis Both Her İkisi The script asks to read and write a folder you choose, with everything in it. Betik, seçtiğiniz bir klasörü içindeki her şeyle birlikte okumak ve yazmak için izin istiyor. Allow Once Bir Kez İzin Ver Always Allow This Script Bu Betiğe Her Zaman İzin Ver + No script has kept file access. Hiçbir betiğin kayıtlı dosya erişimi yok. + Read file Dosya Okuma + Read and write file Dosya Okuma ve Yazma + Read and write folder Klasör Okuma ve Yazma + Revoke İzni Kaldır + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. İzni Kaldır, betiğin her sürümü için kayıtlı erişimi kaldırır. Bir klasöre erişim, içindeki her şeyi kapsar. +@msg Script file access revoked Betiğin dosya erişimi kaldırıldı +@msg The script file access was already revoked Betiğin dosya erişimi zaten kaldırılmıştı Deny Reddet A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Bir betik açık belgeleri değiştirebilir ve çalıştırdığı komutlarla dosya yazabilir. Yalnızca güvendiğiniz betikleri çalıştırın. Do not show this warning again Bu uyarıyı bir daha gösterme diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..eedb12c21a 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4937,6 +4937,14 @@ axis Both Обидві The script asks to read and write a folder you choose, with everything in it. Скрипт просить дозволу читати й записувати вибрану вами папку з усім її вмістом. Allow Once Дозволити один раз Always Allow This Script Завжди дозволяти цей скрипт + No script has kept file access. Жоден скрипт не має збереженого доступу до файлів. + Read file Читання файлу + Read and write file Читання й запис файлу + Read and write folder Читання й запис папки + Revoke Відкликати + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. «Відкликати» прибирає доступ, збережений для кожної версії скрипту. Доступ до папки охоплює весь її вміст. +@msg Script file access revoked Доступ скрипту до файлів відкликано +@msg The script file access was already revoked Доступ скрипту до файлів уже було відкликано Deny Заборонити A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт може змінювати відкриті документи й записувати файли за допомогою команд, які виконує. Запускайте лише ті скрипти, яким довіряєте. Do not show this warning again Більше не показувати це попередження diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..da6d0ae64d 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5415,6 +5415,14 @@ theme Appearance Giao diện The script asks to read and write a folder you choose, with everything in it. Tập lệnh yêu cầu đọc và ghi một thư mục bạn chọn, cùng mọi thứ bên trong. Allow Once Cho phép một lần Always Allow This Script Luôn cho phép tập lệnh này + No script has kept file access. Không có tập lệnh nào được giữ quyền truy cập tệp. + Read file Đọc tệp + Read and write file Đọc và ghi tệp + Read and write folder Đọc và ghi thư mục + Revoke Thu hồi + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. Thu hồi gỡ quyền truy cập đã giữ cho mọi phiên bản của tập lệnh. Quyền truy cập một thư mục bao gồm mọi thứ bên trong. +@msg Script file access revoked Đã thu hồi quyền truy cập tệp của tập lệnh +@msg The script file access was already revoked Quyền truy cập tệp của tập lệnh đã được thu hồi trước đó Deny Từ chối A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Tập lệnh có thể thay đổi các tài liệu đang mở và ghi tệp thông qua các lệnh mà nó chạy. Chỉ chạy những tập lệnh bạn tin cậy. Do not show this warning again Không hiện lại cảnh báo này diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..5f66731afe 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5444,6 +5444,14 @@ imageTrace Outline 轮廓 The script asks to read and write a folder you choose, with everything in it. 脚本请求读写您选择的文件夹及其中的所有内容。 Allow Once 允许一次 Always Allow This Script 始终允许此脚本 + No script has kept file access. 没有脚本保留了文件访问权限。 + Read file 读取文件 + Read and write file 读取和写入文件 + Read and write folder 读取和写入文件夹 + Revoke 收回权限 + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. “收回权限”会移除为脚本每个版本保留的访问权限。文件夹的访问权限包括其中的所有内容。 +@msg Script file access revoked 已收回脚本的文件访问权限 +@msg The script file access was already revoked 脚本的文件访问权限已被收回 Deny 拒绝 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 脚本可以更改打开的文档,并可通过其运行的命令写入文件。请只运行您信任的脚本。 Do not show this warning again 不再显示此警告 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..d430105f73 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2790,6 +2790,14 @@ file-filter Templates 範本 The script asks to read and write a folder you choose, with everything in it. 指令碼要求讀寫您選擇的資料夾及其中的所有內容。 Allow Once 允許一次 Always Allow This Script 一律允許此指令碼 + No script has kept file access. 沒有指令碼保留檔案存取權。 + Read file 讀取檔案 + Read and write file 讀取和寫入檔案 + Read and write folder 讀取和寫入資料夾 + Revoke 收回權限 + Revoke removes the access kept for every version of the script. A folder's access covers everything in it. 「收回權限」會移除為指令碼每個版本保留的存取權。資料夾的存取權包含其中的所有內容。 +@msg Script file access revoked 已收回指令碼的檔案存取權 +@msg The script file access was already revoked 指令碼的檔案存取權已被收回 Deny 拒絕 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 指令碼可以變更開啟的文件,並可透過其執行的命令寫入檔案。請只執行您信任的指令碼。 Do not show this warning again 不再顯示此警告 diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index f6bd364449..19aa7d9e66 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -13,6 +13,7 @@ use crate::theme::{self, Accent, Brightness, Scheme, Tokens}; use crate::{VectorcraftApp, widgets}; mod descriptions; +mod script_access; /// UI-only fields shown in the dialog (backed by `UiState`, not engine prefs). pub const UI_FIELDS: &[(&str, &str, &str)] = &[ @@ -55,6 +56,8 @@ pub fn open(app: &mut VectorcraftApp, category: Option<&str>) { fields.insert("__desktopKeepsFrame".into(), json!(app.desktop_keeps_frame)); fields.insert("__search".into(), json!("")); fields.insert("__focusSearch".into(), json!(true)); + // Read-only: the script file access kept with Always (General › Script File Access). + script_access::load(app, &mut fields); app.ui.dialog = Some(Dialog { kind: "preferences".into(), fields }); } @@ -780,6 +783,9 @@ fn category_fields(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog, } found_paint(ui, d, mark); described.row(ui, sp.key, top); + if sp.key == "showExternalScriptWarning" { + script_access::show(ui, app, d); + } } described } diff --git a/crates/ui-egui/src/prefs_dialog/script_access.rs b/crates/ui-egui/src/prefs_dialog/script_access.rs new file mode 100644 index 0000000000..abbe87386d --- /dev/null +++ b/crates/ui-egui/src/prefs_dialog/script_access.rs @@ -0,0 +1,202 @@ +//! Preferences › General › Script File Access: the file access people allowed scripts with Always +//! Allow This Script in a script's file dialog (`script.grants`), one row for each script and path, +//! each with a Revoke button (`script.grants.revoke`). + +use std::collections::BTreeMap; + +use serde_json::{Map, Value, json}; +use vectorcraft_plugins::permissions; + +use crate::state::Dialog; +use crate::theme::{self, Tokens}; +use crate::{VectorcraftApp, widgets}; + +/// The dialog field that holds the rows, `[{script, path, access, versions}]`. It is absent where +/// the session keeps no grants (no settings folder, and the web), and the section is not shown. +pub(super) const ROWS: &str = "__scriptAccess"; + +/// The dialog field that holds the row whose Revoke button takes the keyboard focus next. +const FOCUS: &str = "__scriptAccessFocus"; + +/// The most characters of a path a row shows. +const MAX_SHOWN_PATH: usize = 1024; + +/// A row's height in the list. +const ROW_HEIGHT: f32 = 30.0; + +/// The list's height before it scrolls. +const LIST_HEIGHT: f32 = 180.0; + +/// The kept grants (`script.grants`) as the rows of the field [`ROWS`] in the Preferences dialog's +/// `fields`. Where the session keeps no grants, the field is removed. +pub(super) fn load(app: &mut VectorcraftApp, fields: &mut Map) { + match app.session.execute("script.grants", &json!({})) { + Ok(v) if !v["file"].is_null() => { + fields.insert(ROWS.into(), Value::Array(rows(&v["grants"]))); + } + _ => { + fields.remove(ROWS); + } + } +} + +/// The rows for the grants `grants` lists: one for each script and path, sorted by script and then +/// by path, with the widest access any kept version of the pair has (`folder`, then `write`, then +/// `read`) and how many versions are kept. A grant without a script or a path is left out. +pub(super) fn rows(grants: &Value) -> Vec { + let rank = |access: &str| match access { + "folder" => 2, + "write" => 1, + _ => 0, + }; + let mut pairs: BTreeMap<(&str, &str), (&str, usize)> = BTreeMap::new(); + for g in grants.as_array().into_iter().flatten() { + let (Some(script), Some(path)) = (g["script"].as_str(), g["path"].as_str()) else { continue }; + let access = if g["folder"] == true { + "folder" + } else if g["write"] == true { + "write" + } else { + "read" + }; + let pair = pairs.entry((script, path)).or_insert((access, 0)); + if rank(access) > rank(pair.0) { + pair.0 = access; + } + pair.1 += 1; + } + pairs + .into_iter() + .map(|((script, path), (access, versions))| json!({"script": script, "path": path, "access": access, "versions": versions})) + .collect() +} + +/// `path` as a row shows it: control and bidirectional formatting characters written as escapes, +/// and at most [`MAX_SHOWN_PATH`] characters. +pub(super) fn shown(path: &str) -> String { + permissions::display_text(path, MAX_SHOWN_PATH) +} + +/// The label of a row's access. +fn access_label(access: &str) -> &'static str { + match access { + "folder" => tl!("Read and write folder"), + "write" => tl!("Read and write file"), + _ => tl!("Read file"), + } +} + +/// A line of the list: the script that the rows below it belong to, or a row, by its index. +enum Line { + Script(usize), + Row(usize), +} + +/// The section, after General › Show External Script Warning, when the dialog `d` has rows: each +/// script, its paths with their access and a Revoke button, or a line saying there are none. +pub(super) fn show(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog) { + let Some(rows) = d.fields.get(ROWS).and_then(Value::as_array).cloned() else { return }; + let t = Tokens::get(ui.ctx()); + ui.add_space(8.0); + ui.label(egui::RichText::new(tl!("Script File Access")).font(theme::semibold(12.5)).color(t.text_strong)); + ui.add_space(2.0); + if rows.is_empty() { + ui.label(egui::RichText::new(tl!("No script has kept file access.")).color(t.text_dim).size(11.5)); + return; + } + let mut lines = Vec::with_capacity(rows.len() * 2); + for (i, row) in rows.iter().enumerate() { + if i == 0 || rows[i - 1]["script"] != row["script"] { + lines.push(Line::Script(i)); + } + lines.push(Line::Row(i)); + } + let focus = d.fields.get(FOCUS).and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); + let mut revoke_at = None; + // The widths of the access column and of the Revoke button, so the path takes the rest. + let text_width = |text: &str, font: egui::FontId| ui.painter().layout_no_wrap(text.to_string(), font, t.text).size().x; + let access_width = + ["folder", "write", "read"].map(|a| text_width(access_label(a), egui::FontId::proportional(11.5))).into_iter().fold(0.0, f32::max); + let revoke_width = (text_width(tl!("Revoke"), theme::semibold(12.5)) + 32.0).max(72.0); + // The list is as tall as its lines, up to LIST_HEIGHT, also at the bottom of the scrolled field + // list, where a scroll area would otherwise take only the height left in view. + let spacing = ui.spacing().item_spacing; + let height = ((ROW_HEIGHT + spacing.y) * lines.len() as f32 - spacing.y).min(LIST_HEIGHT); + let scroll = + egui::ScrollArea::vertical().id_salt("prefs-script-access").max_height(LIST_HEIGHT).min_scrolled_height(height).auto_shrink([false, true]); + scroll.show_rows(ui, ROW_HEIGHT, lines.len(), |ui, range| { + for line in &lines[range] { + let size = egui::vec2(ui.available_width(), ROW_HEIGHT); + match *line { + Line::Script(i) => { + let script = shown(rows[i]["script"].as_str().unwrap_or_default()); + ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| { + let text = egui::RichText::new(&script).color(t.text_strong).size(12.0); + ui.add(egui::Label::new(text).truncate()).on_hover_text(&script); + }); + } + Line::Row(i) => { + let row = &rows[i]; + let (script, path) = (shown(row["script"].as_str().unwrap_or_default()), shown(row["path"].as_str().unwrap_or_default())); + ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.add_space(12.0); + // The path, then the access and the Revoke button at the right. + let gaps = 12.0 + 2.0 * ui.spacing().item_spacing.x; + let path_width = (ui.available_width() - access_width - revoke_width - gaps).max(40.0); + let cell = |width: f32| egui::vec2(width, ROW_HEIGHT); + ui.allocate_ui_with_layout(cell(path_width), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_width(path_width); + ui.add(egui::Label::new(egui::RichText::new(&path).color(t.text)).truncate()).on_hover_text(&path); + }); + ui.add_space(12.0); + ui.allocate_ui_with_layout(cell(access_width), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_width(access_width); + let access = egui::RichText::new(access_label(row["access"].as_str().unwrap_or_default())).color(t.text_dim).size(11.5); + ui.add(egui::Label::new(access).wrap_mode(egui::TextWrapMode::Extend)); + }); + let button = widgets::secondary_button(ui, tl!("Revoke")); + // A screen reader names the script and the path along with the button. + ui.ctx().accesskit_node_builder(button.id, |node| node.set_description(format!("{script}: {path}"))); + if focus == Some(i) { + button.request_focus(); + } + if button.on_hover_text(&path).clicked() { + revoke_at = Some(i); + } + }); + } + } + } + }); + if focus.is_some() { + d.fields.remove(FOCUS); + } + let note = tl!("Revoke removes the access kept for every version of the script. A folder's access covers everything in it."); + ui.label(egui::RichText::new(note).color(t.text_dim).size(11.0)); + if let Some(i) = revoke_at { + revoke(app, d, i); + } +} + +/// Revoke on the row `i` of the Preferences dialog `d`: every kept grant of its script and path is +/// removed (`script.grants.revoke`), the rows are read again and the row now at `i`, or the last +/// row, takes the keyboard focus. The status bar says what happened; on an error the rows stay as +/// they were. +pub(super) fn revoke(app: &mut VectorcraftApp, d: &mut Dialog, i: usize) { + let Some(row) = d.fields.get(ROWS).and_then(|rows| rows.get(i)).cloned() else { return }; + match app.run("script.grants.revoke", json!({"script": row["script"], "path": row["path"]})) { + Ok(v) => { + load(app, &mut d.fields); + let left = d.fields.get(ROWS).and_then(Value::as_array).map_or(0, Vec::len); + if left > 0 { + d.fields.insert(FOCUS.into(), json!(i.min(left - 1))); + } + if v["removed"].as_u64().unwrap_or(0) > 0 { + app.status("Script file access revoked"); + } else { + app.status("The script file access was already revoked"); + } + } + Err(e) => app.status(e), + } +} diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index c79ca22470..f201c553dc 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -3001,3 +3001,177 @@ fn every_description_names_a_setting_and_fits_in_every_language() { out.textures_delta.clear(); assert!(bad.is_empty(), "{}", bad.join("\n")); } + +/// A kept script file grant, as the grants file holds it. +fn grant(script: &std::path::Path, path: &std::path::Path, sha256: &str, write: bool, folder: bool) -> Value { + json!({"script": script.to_string_lossy(), "sha256": sha256, "code": [], "path": path.to_string_lossy(), "write": write, "folder": folder}) +} + +/// An app whose session keeps its script data in a new folder for test `name`, with a grants file +/// beside it that holds `grants`. → The app and the grants file. +fn app_with_grants(name: &str, grants: Value) -> (VectorcraftApp, std::path::PathBuf) { + let base = temp_folder(name); + let store = base.join(vectorcraft_engine::script::files::GRANTS_FILE); + std::fs::write(&store, serde_json::to_vec_pretty(&json!({"version": 1, "grants": grants})).unwrap()).unwrap(); + let mut a = app(); + a.session.attach_script_data(base.join("Script Data")); + (a, store) +} + +/// The rows General › Script File Access shows, as (script, path, access, versions). +fn access_rows(a: &VectorcraftApp) -> Vec<(String, String, String, u64)> { + let d = a.ui.dialog.as_ref().unwrap(); + let rows = d.fields.get(script_access::ROWS).and_then(Value::as_array).cloned().unwrap_or_default(); + rows.iter() + .map(|r| { + let s = |k: &str| r[k].as_str().unwrap_or_default().to_string(); + (s("script"), s("path"), s("access"), r["versions"].as_u64().unwrap_or(0)) + }) + .collect() +} + +/// The open Preferences dialog drawn in `ctx` with the field list scrolled by the wheel, over the +/// Keyboard Increment row, until the last text `label` lies wholly inside it → the texts of the +/// last frame that lie in their clip rectangle. +fn script_access_in_view(a: &mut VectorcraftApp, ctx: &egui::Context, label: &str) -> Vec<(String, egui::Rect)> { + description_frame(a, ctx, vec![]); + let texts = whole_texts_frame(a, ctx, vec![]); + let at = texts.iter().find(|(t, _)| t == "Keyboard Increment:").map(|(_, r)| r.center()).expect("General shows Keyboard Increment"); + let texts = description_frame(a, ctx, vec![egui::Event::PointerMoved(at)]).0; + scroll_into_view(a, ctx, texts, label) +} + +/// Click the first text `label` of `texts`, which the last frame in `ctx` drew, with the pointer. +fn click_shown(a: &mut VectorcraftApp, ctx: &egui::Context, texts: &[(String, egui::Rect)], label: &str) { + let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + description_frame(a, ctx, vec![egui::Event::PointerMoved(at)]); + description_frame(a, ctx, vec![press(true)]); + description_frame(a, ctx, vec![press(false)]); +} + +/// A new context with the app's fonts. +fn fonts_context() -> egui::Context { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx +} + +/// General › Script File Access lists each script and path once, with the widest access any kept +/// version of the pair has, and Revoke removes every kept version of that pair through +/// `script.grants.revoke`, so the next run asks again; the other pairs stay. +#[test] +fn script_file_access_lists_each_script_and_path_once_and_revoke_removes_them() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let (a_js, b_js) = (dir.join("a.jsx"), dir.join("b.jsx")); + let (out, folder) = (dir.join("out.txt"), dir.join("work")); + let grants = json!([ + grant(&a_js, &out, "1", false, false), + grant(&a_js, &out, "2", true, false), + grant(&a_js, &folder, "1", true, true), + grant(&b_js, &out, "3", false, false), + ]); + let (mut a, store) = app_with_grants("grants-list", grants); + open(&mut a, Some("General")); + let (a_s, b_s, out_s, folder_s) = (a_js.to_string_lossy(), b_js.to_string_lossy(), out.to_string_lossy(), folder.to_string_lossy()); + let row = |s: &str, p: &str, access: &str, n: u64| (s.to_string(), p.to_string(), access.to_string(), n); + assert_eq!( + access_rows(&a), + [row(&a_s, &out_s, "write", 2), row(&a_s, &folder_s, "folder", 1), row(&b_s, &out_s, "read", 1)], + "one row for each script and path, sorted by script and then path" + ); + let ctx = fonts_context(); + let note = "Revoke removes the access kept for every version of the script. A folder's access covers everything in it."; + let texts = script_access_in_view(&mut a, &ctx, note); + let painted = |label: &str| texts.iter().filter(|(t, _)| t == label).count(); + for label in ["Script File Access", "Read and write file", "Read and write folder", "Read file"] { + assert_eq!(painted(label), 1, "{label:?} in {texts:?}"); + } + assert_eq!(painted("Revoke"), 3, "a Revoke for each row: {texts:?}"); + assert_eq!(painted(&a_s), 1, "the script shows once over its rows: {texts:?}"); + assert_eq!(painted(&out_s), 2, "{texts:?}"); + let rect = |label: &str| texts.iter().find(|(t, _)| t == label).map(|(_, r)| *r).unwrap_or_else(|| panic!("no `{label}`")); + let (path, access, revoke) = (rect(&out_s), rect("Read and write file"), rect("Revoke")); + assert!(path.max.x < access.min.x && access.max.x < revoke.min.x, "a row's path, access and Revoke do not overlap: {texts:?}"); + // The first Revoke is the first row's: a.jsx and out.txt, kept for two versions. + click_shown(&mut a, &ctx, &texts, "Revoke"); + assert_eq!(a.ui.status, "Script file access revoked"); + assert_eq!(access_rows(&a), [row(&a_s, &folder_s, "folder", 1), row(&b_s, &out_s, "read", 1)]); + let kept = a.session.execute("script.grants", &json!({})).unwrap(); + assert_eq!(kept["grants"].as_array().unwrap().len(), 2, "{kept}"); + let stored: Value = serde_json::from_slice(&std::fs::read(&store).unwrap()).unwrap(); + assert!(stored["grants"].as_array().unwrap().iter().all(|g| !(g["script"] == *a_s && g["path"] == *out_s)), "{stored}"); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); +} + +/// Revoke on a row whose grants were removed elsewhere removes nothing and says so; with no kept +/// grants the section says there are none, and a session without a settings folder (the web among +/// them) shows no section. +#[test] +fn script_file_access_shows_none_and_a_revoke_of_a_removed_row() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let (mut a, store) = app_with_grants("grants-gone", json!([grant(&dir.join("a.jsx"), &dir.join("out.txt"), "1", false, false)])); + open(&mut a, Some("General")); + assert_eq!(access_rows(&a).len(), 1); + a.session.execute("script.grants.revoke", &json!({"all": true})).unwrap(); + let mut d = a.ui.dialog.clone().unwrap(); + script_access::revoke(&mut a, &mut d, 0); + a.ui.dialog = Some(d); + assert_eq!(a.ui.status, "The script file access was already revoked"); + assert!(access_rows(&a).is_empty()); + let texts = script_access_in_view(&mut a, &fonts_context(), "No script has kept file access."); + assert!(texts.iter().any(|(t, _)| t == "Script File Access"), "{texts:?}"); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); + let mut web = app(); + open(&mut web, Some("General")); + assert!(web.ui.dialog.as_ref().unwrap().fields.get(script_access::ROWS).is_none()); + let text = crate::tests_labels::painted_text(&mut web, |a, ui| show(a, ui.ctx())); + assert!(!text.contains("No script has kept file access."), "{text}"); +} + +/// A grants file that is not well formed or is larger than may be read is refused: Revoke shows +/// the error, grants nothing and leaves the file and the rows as they were. +#[test] +fn script_file_access_revoke_refuses_a_malformed_or_oversized_grants_file() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let mut oversized = br#"{"version": 1, "grants": []}"#.to_vec(); + oversized.resize((4 << 20) + 1, b' '); + for (name, held) in + [("malformed", br#"{"version": 1, "grants": [{"script": "x"}]}"#.to_vec()), ("broken", b"{ not json".to_vec()), ("oversized", oversized)] + { + let (mut a, store) = app_with_grants(&format!("grants-{name}"), json!([grant(&dir.join("a.jsx"), &dir.join("out.txt"), "1", false, false)])); + open(&mut a, Some("General")); + let before = access_rows(&a); + assert_eq!(before.len(), 1, "{name}"); + std::fs::write(&store, &held).unwrap(); + let mut d = a.ui.dialog.clone().unwrap(); + script_access::revoke(&mut a, &mut d, 0); + a.ui.dialog = Some(d); + assert!(a.ui.status.contains("could not be saved"), "{name}: {}", a.ui.status); + assert_eq!(std::fs::read(&store).unwrap(), held, "{name}: the grants file is left as it was"); + assert_eq!(access_rows(&a), before, "{name}: the rows stay"); + let listed = a.session.execute("script.grants", &json!({})); + assert!( + listed.as_ref().is_ok_and(|v| v["grants"].as_array().is_some_and(Vec::is_empty)) || listed.is_err(), + "{name}: nothing is granted: {listed:?}" + ); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); + } +} + +/// A script or path with control or bidirectional formatting characters shows them as escapes, so +/// it cannot break its row or draw as another name. +#[test] +fn script_file_access_shows_paths_as_plain_text() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let (script, path) = (dir.join("a\u{202E}txt.jsx"), dir.join("two\nlines.txt")); + let (mut a, store) = app_with_grants("grants-plain", json!([grant(&script, &path, "1", false, false)])); + open(&mut a, Some("General")); + let (script_s, path_s) = (script_access::shown(&script.to_string_lossy()), script_access::shown(&path.to_string_lossy())); + assert!(script_s.ends_with("a\\u{202E}txt.jsx") && path_s.ends_with("two\\u{000A}lines.txt"), "{script_s} {path_s}"); + let texts = script_access_in_view(&mut a, &fonts_context(), &path_s); + assert!(texts.iter().any(|(t, _)| *t == script_s), "{texts:?}"); + let text: String = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(!text.contains('\u{202E}') && !text.contains("two\nlines"), "{text}"); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5e8483f80a..8f60699871 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1040,6 +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; 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: Preferences › General › Script File Access lists the file access kept with Always Allow This Script (`script.grants`), one row for each script and path with its widest access (read file, read and write file, or read and write folder), and its Revoke button removes every kept version of that script and path (`script.grants.revoke`), so the next run asks again. Paths show control and bidirectional characters as escapes; a grants file that is not well formed or is over 4 MiB makes Revoke show its error and leaves the file as it was. VectorCraft's own addition. `crates/ui-egui/src/prefs_dialog/tests.rs` (`script_file_access_*`). - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. From b9070d0013529471e8e08865b495afcd4905e293 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:25:20 -0800 Subject: [PATCH 2/9] Preferences: Revoke removes a script grant outside the automation read roots With automation read roots in force, script.grants names a script or a path outside them by its file name alone, and script.grants.revoke matches that name against the stored full path, so Revoke on such a row removed nothing and said the access was already revoked. Script File Access now reads the grants file, which is the app's own, with no roots in force. Each row keeps its script and path whole for script.grants.revoke and shows them as script.grants names them to the request that opened Preferences. ui.inspect, the reply of ui.dialog.set and the Reset Preferences question over the dialog name them the same way and leave out the whole values; ui.dialog.set's reply also leaves out the folder preferences outside the read roots, as ui.inspect does. --- crates/ui-egui/src/control.rs | 31 ++++++++--- crates/ui-egui/src/prefs_dialog.rs | 2 +- .../ui-egui/src/prefs_dialog/script_access.rs | 52 ++++++++++++++++--- crates/ui-egui/src/prefs_dialog/tests.rs | 52 +++++++++++++++++++ docs/target-app-parity.md | 2 +- 5 files changed, 123 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 218312750d..5035a00d04 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1152,7 +1152,8 @@ fn leave_out_unreadable_values(v: &mut Value, place: ParamsPlace) { /// Takes out of `ui.inspect`'s copy of the UI state the paths the request may not read: recent files, /// a library panel's file, folder preferences (saved, and in an open Preferences dialog) and the paths /// in recorded actions' steps and in the item an open Insert Menu Item dialog picked, outside the -/// read root. The file selected in an open JavaScript Files dialog is named as `svgInteractivity.info` +/// read root. An open Preferences dialog's kept script file access names its scripts and paths as +/// `script.grants` does. The file selected in an open JavaScript Files dialog is named as `svgInteractivity.info` /// names the active document's linked files. The UI state itself is not changed. fn leave_out_unreadable_paths(app: &VectorcraftApp, ui: &mut serde_json::Map) { if let Some(Value::Array(files)) = ui.get_mut("recent_files") { @@ -1171,11 +1172,8 @@ fn leave_out_unreadable_paths(app: &VectorcraftApp, ui: &mut serde_json::Map) { + let preferences = dialog.get("kind").and_then(Value::as_str) == Some("preferences"); + let Some(Value::Object(fields)) = dialog.get_mut("fields") else { return }; + if preferences { + leave_out_unreadable_folders(fields); + crate::prefs_dialog::script_access::list_as_listed(fields); + } + if let Some(Value::Object(parent)) = fields.get_mut(crate::dialogs::PARENT) { + leave_out_unreadable_preferences(parent); + } +} + /// Takes out of `prefs` the folder preferences /// ([`vectorcraft_engine::cmd::prefscmds::FOLDER_PREFS`]) the request may not read ([`shows_folder`]). fn leave_out_unreadable_folders(prefs: &mut serde_json::Map) { @@ -1639,7 +1653,10 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRequest) return err(e); } } - let dialog = app.ui.dialog.as_ref().and_then(|d| serde_json::to_value(d).ok()).unwrap_or_default(); + let mut dialog = app.ui.dialog.as_ref().and_then(|d| serde_json::to_value(d).ok()).unwrap_or_default(); + if let Value::Object(shown) = &mut dialog { + leave_out_unreadable_preferences(shown); + } // `action` answers the dialog the fields were just set in, within this request. match action { None => ok(dialog), diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index 19aa7d9e66..a23ef884a5 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -13,7 +13,7 @@ use crate::theme::{self, Accent, Brightness, Scheme, Tokens}; use crate::{VectorcraftApp, widgets}; mod descriptions; -mod script_access; +pub(crate) mod script_access; /// UI-only fields shown in the dialog (backed by `UiState`, not engine prefs). pub const UI_FIELDS: &[(&str, &str, &str)] = &[ diff --git a/crates/ui-egui/src/prefs_dialog/script_access.rs b/crates/ui-egui/src/prefs_dialog/script_access.rs index abbe87386d..219145e60f 100644 --- a/crates/ui-egui/src/prefs_dialog/script_access.rs +++ b/crates/ui-egui/src/prefs_dialog/script_access.rs @@ -27,12 +27,27 @@ const ROW_HEIGHT: f32 = 30.0; /// The list's height before it scrolls. const LIST_HEIGHT: f32 = 180.0; +/// The keys of a row that hold its script and path as it shows them, each with the key that holds +/// it whole. +const WHOLE: [(&str, &str); 2] = [("script", "wholeScript"), ("path", "wholePath")]; + /// The kept grants (`script.grants`) as the rows of the field [`ROWS`] in the Preferences dialog's -/// `fields`. Where the session keeps no grants, the field is removed. +/// `fields`. Where the session keeps no grants, the field is removed. The grants file is the app's +/// own, so it is read with no automation roots in force: each row keeps its script and path whole +/// (`wholeScript` and `wholePath`) for `script.grants.revoke`, and shows them (`script` and `path`) +/// as `script.grants` names them to the request that opened the dialog ([`as_listed`]). pub(super) fn load(app: &mut VectorcraftApp, fields: &mut Map) { - match app.session.execute("script.grants", &json!({})) { + match vectorcraft_engine::file_access::unconfined(|| app.session.execute("script.grants", &json!({}))) { Ok(v) if !v["file"].is_null() => { - fields.insert(ROWS.into(), Value::Array(rows(&v["grants"]))); + let mut rows = rows(&v["grants"]); + for row in rows.iter_mut().filter_map(Value::as_object_mut) { + for (shown, whole) in WHOLE { + let Some(path) = row.get(shown).and_then(Value::as_str).map(str::to_string) else { continue }; + row.insert(shown.into(), json!(as_listed(&path))); + row.insert(whole.into(), json!(path)); + } + } + fields.insert(ROWS.into(), Value::Array(rows)); } _ => { fields.remove(ROWS); @@ -77,6 +92,29 @@ pub(super) fn shown(path: &str) -> String { permissions::display_text(path, MAX_SHOWN_PATH) } +/// A kept script or path as `script.grants` names it to the request being served: whole where that +/// request may read it, else its file name alone (empty for a path that ends in no name). +pub(crate) fn as_listed(path: &str) -> &str { + if vectorcraft_engine::file_access::check_read(path).is_ok() { + return path; + } + let name = path.rsplit(vectorcraft_doc::links::path_separators(path)).next().unwrap_or_default(); + if matches!(name, "." | "..") { "" } else { name } +} + +/// The rows of `ROWS` in a copy of the Preferences dialog's `fields` (`ui.inspect` and +/// `ui.dialog.set`'s reply) with each script and path as [`as_listed`] gives it to the request being +/// served, and without the whole ones. +pub(crate) fn list_as_listed(fields: &mut Map) { + for row in fields.get_mut(ROWS).and_then(Value::as_array_mut).into_iter().flatten().filter_map(Value::as_object_mut) { + for (shown, whole) in WHOLE { + if let Some(path) = row.remove(whole).as_ref().and_then(Value::as_str) { + row.insert(shown.into(), json!(as_listed(path))); + } + } + } +} + /// The label of a row's access. fn access_label(access: &str) -> &'static str { match access { @@ -106,7 +144,7 @@ pub(super) fn show(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog) } let mut lines = Vec::with_capacity(rows.len() * 2); for (i, row) in rows.iter().enumerate() { - if i == 0 || rows[i - 1]["script"] != row["script"] { + if i == 0 || rows[i - 1]["wholeScript"] != row["wholeScript"] { lines.push(Line::Script(i)); } lines.push(Line::Row(i)); @@ -178,13 +216,13 @@ pub(super) fn show(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog) } } -/// Revoke on the row `i` of the Preferences dialog `d`: every kept grant of its script and path is -/// removed (`script.grants.revoke`), the rows are read again and the row now at `i`, or the last +/// Revoke on the row `i` of the Preferences dialog `d`: every kept grant of its script and path, +/// whole, is removed (`script.grants.revoke`), the rows are read again and the row now at `i`, or the last /// row, takes the keyboard focus. The status bar says what happened; on an error the rows stay as /// they were. pub(super) fn revoke(app: &mut VectorcraftApp, d: &mut Dialog, i: usize) { let Some(row) = d.fields.get(ROWS).and_then(|rows| rows.get(i)).cloned() else { return }; - match app.run("script.grants.revoke", json!({"script": row["script"], "path": row["path"]})) { + match app.run("script.grants.revoke", json!({"script": row["wholeScript"], "path": row["wholePath"]})) { Ok(v) => { load(app, &mut d.fields); let left = d.fields.get(ROWS).and_then(Value::as_array).map_or(0, Vec::len); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index f201c553dc..94d710dead 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -3129,6 +3129,58 @@ fn script_file_access_shows_none_and_a_revoke_of_a_removed_row() { assert!(!text.contains("No script has kept file access."), "{text}"); } +/// Preferences opened with a read root in force shows a script and a path outside it by their file +/// names alone, as `script.grants` lists them, and `ui.inspect`, `ui.dialog.set`'s reply and the +/// Reset Preferences question over the dialog name them the same way; Revoke still removes that +/// pair's kept grants, both with the root in force and without it. +#[test] +fn script_file_access_revokes_a_pair_outside_the_read_roots() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let (script, path) = (dir.join("a.jsx"), dir.join("out.txt")); + let root = temp_folder("grants-root-in"); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[root.as_path()], &[]).unwrap(); + for confined in [true, false] { + let (mut a, store) = app_with_grants("grants-outside-roots", json!([grant(&script, &path, "1", false, false)])); + let (shown, inspected, set, under) = vectorcraft_engine::file_access::confine(roots.as_ref(), || { + open(&mut a, Some("General")); + let shown = access_rows(&a); + let ctx = egui::Context::default(); + let inspected = crate::control::inspect(&a, &ctx); + let (req, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({"field": "unitsGeneral", "value": "points"})); + let crate::control::Outcome::Done(set) = crate::control::handle(&mut a, &ctx, &req) else { panic!("expected an immediate reply") }; + let kept = a.ui.dialog.clone(); + crate::dialogs::confirm::ask_reset_prefs(&mut a); + let under = crate::control::inspect(&a, &ctx); + a.ui.dialog = kept; + (shown, inspected, set, under) + }); + assert_eq!(shown, [("a.jsx".to_string(), "out.txt".to_string(), "read".to_string(), 1)]); + // The person's frame draws the rows as the request that opened the dialog was shown them. + let texts = script_access_in_view(&mut a, &fonts_context(), "out.txt"); + let whole = dir.to_string_lossy(); + assert!(texts.iter().any(|(t, _)| t == "a.jsx") && !texts.iter().any(|(t, _)| t.contains(&*whole)), "{texts:?}"); + let listed = json!({"script": "a.jsx", "path": "out.txt"}); + for (reply, row) in [ + (&inspected, &inspected["ui"]["dialog"]["fields"][script_access::ROWS][0]), + (&set, &set["result"]["fields"][script_access::ROWS][0]), + (&under, &under["ui"]["dialog"]["fields"][crate::dialogs::PARENT]["fields"][script_access::ROWS][0]), + ] { + assert_eq!(json!({"script": row["script"], "path": row["path"]}), listed, "{reply}"); + assert!(row["wholeScript"].is_null() && row["wholePath"].is_null(), "{reply}"); + } + let mut d = a.ui.dialog.clone().unwrap(); + let roots_now = if confined { roots.as_ref() } else { None }; + vectorcraft_engine::file_access::confine(roots_now, || script_access::revoke(&mut a, &mut d, 0)); + a.ui.dialog = Some(d); + assert_eq!(a.ui.status, "Script file access revoked", "confined: {confined}"); + assert!(access_rows(&a).is_empty(), "confined: {confined}"); + let stored: Value = serde_json::from_slice(&std::fs::read(&store).unwrap()).unwrap(); + assert!(stored["grants"].as_array().is_some_and(Vec::is_empty), "confined: {confined}: {stored}"); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); + } + let _ = std::fs::remove_dir_all(&root); +} + /// A grants file that is not well formed or is larger than may be read is refused: Revoke shows /// the error, grants nothing and leaves the file and the rows as they were. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8b38a9d408..9b0a072347 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1041,7 +1041,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; 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: Preferences › General › Script File Access lists the file access kept with Always Allow This Script (`script.grants`), one row for each script and path with its widest access (read file, read and write file, or read and write folder), and its Revoke button removes every kept version of that script and path (`script.grants.revoke`), so the next run asks again. Paths show control and bidirectional characters as escapes; a grants file that is not well formed or is over 4 MiB makes Revoke show its error and leaves the file as it was. VectorCraft's own addition. `crates/ui-egui/src/prefs_dialog/tests.rs` (`script_file_access_*`). + - Scripts: Preferences › General › Script File Access lists the file access kept with Always Allow This Script (`script.grants`), one row for each script and path with its widest access (read file, read and write file, or read and write folder), and its Revoke button removes every kept version of that script and path (`script.grants.revoke`), so the next run asks again. Paths show control and bidirectional characters as escapes, and a script or path outside the automation read roots in force when Preferences opens shows by its file name, as `script.grants` lists it, and Revoke still removes it; a grants file that is not well formed or is over 4 MiB makes Revoke show its error and leaves the file as it was. VectorCraft's own addition. `crates/ui-egui/src/prefs_dialog/tests.rs` (`script_file_access_*`). - 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`. From ce0f57826830c8926a96b61e7eed711f11e5c72b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 22:21:07 -0800 Subject: [PATCH 3/9] Preferences: Script File Access shows why the grants file cannot be read When the grants file was not well formed, was not JSON, was over 4 MiB or its lock could not be taken, script.grants listed no grants and Preferences said "No script has kept file access." while the file could still hold grants. script.grants now adds error, with the reason, when the file is there and cannot be read or changed, and still lists the well-formed grants it can read. Script File Access shows that error in place of the empty-list line, with any rows that could be read. The grants file is not written. The message has rows in the 25 complete-message catalogs, and the params text and docs/mcp.md describe the field. --- crates/engine/src/cmd/scripts.rs | 10 ++++--- crates/engine/src/script/files.rs | 17 +++++++++--- crates/engine/src/tests/script_io.rs | 8 +++--- crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + .../ui-egui/src/prefs_dialog/script_access.rs | 24 ++++++++++++++--- crates/ui-egui/src/prefs_dialog/tests.rs | 26 +++++++++++++++++++ docs/mcp.md | 8 +++--- docs/target-app-parity.md | 2 +- 33 files changed, 105 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index dc33c46ab1..44b8b7f432 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "List Script File Permissions", [], None, - "{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web)}", + "{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web), error?: why the grants file cannot be read or changed, when it is there and cannot be read, is over 4 MiB, is not a version 1 grants file, holds a grant that is not well formed or more than 4096 grants, or its lock cannot be taken (grants then lists the well-formed grants that can still be read, if any, and script.grants.revoke fails)}", always, grants ), @@ -369,7 +369,7 @@ fn grants(s: &mut Session, _: &Value) -> Result { let Some(dir) = s.script_data_dir() else { return Ok(json!({"grants": [], "file": null})) }; let file = dir.with_file_name(script::files::GRANTS_FILE); // A script or a granted path outside the automation read roots is named by its file name alone. - let mut grants = script::files::stored_grants(dir); + let (mut grants, unreadable) = script::files::stored_grants(dir); for g in &mut grants { for key in ["script", "path"] { if let Some(name) = g[key].as_str().and_then(hidden_name) { @@ -378,7 +378,11 @@ fn grants(s: &mut Session, _: &Value) -> Result { } } let file = file.to_string_lossy(); - Ok(json!({"grants": grants, "file": super::fileio::shown_path(&file)})) + let mut listed = json!({"grants": grants, "file": super::fileio::shown_path(&file)}); + if let Some(e) = unreadable { + listed["error"] = json!(EngineError::Other(format!("the script file permissions could not be read: {e}")).to_string()); + } + Ok(listed) } fn grants_revoke(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 94ef3bdf9e..191f1c52e0 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1062,9 +1062,20 @@ fn lock_store(_: &Path) -> std::io::Result { } /// The grants the grants file beside the data folder `data_dir` keeps: each script, the SHA-256 of -/// its text, the path and whether it may be written (`script.grants`). -pub(crate) fn stored_grants(data_dir: &Path) -> Vec { - read_store(&data_dir.with_file_name(GRANTS_FILE)) +/// its text, the path and whether it may be written (`script.grants`), as [`read_store`] reads +/// them, and the error when the file is there and [`try_read_store`] refuses it (it cannot be read, +/// is too large, is not a grants file of this version, or holds a grant that is not well formed or +/// more grants than may be kept) or its lock cannot be taken, which also refuses a change. +pub(crate) fn stored_grants(data_dir: &Path) -> (Vec, Option) { + let store = data_dir.with_file_name(GRANTS_FILE); + let _lock = match lock_store(&store) { + Ok(lock) => lock, + Err(e) => return (Vec::new(), Some(e)), + }; + match try_read_store(&store) { + Ok(grants) => (grants, None), + Err(e) => (load_store(&store, false).unwrap_or_default(), Some(e)), + } } /// Removes from the grants file beside `data_dir` the grants of the script `script` and of the path diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 25ccb3bcfb..6bcd6f7173 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -637,8 +637,8 @@ fn a_grants_change_without_its_lock_changes_nothing() { } /// Reading and changing the grants file wait for a lock another handle holds only for a bounded -/// number of tries: then a read gives no grants and a change fails with the file unchanged. A lock -/// released while it waits is taken. +/// number of tries: then a read gives no grants and the lock's error, and a change fails with the +/// file unchanged. A lock released while it waits is taken. #[test] fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() { use crate::script::files::{LOCK_TRIES, WHILE_GRANTS_LOCKED, revoke_grants, stored_grants}; @@ -652,7 +652,9 @@ fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() { let waits = std::rc::Rc::new(std::cell::Cell::new(0)); let counted = waits.clone(); WHILE_GRANTS_LOCKED.set(Some(Box::new(move || counted.set(counted.get() + 1)))); - assert_eq!(stored_grants(&data), Vec::::new(), "grants are not read without the lock"); + let (read, error) = stored_grants(&data); + assert_eq!(read, Vec::::new(), "grants are not read without the lock"); + assert_eq!(error.map(|e| e.kind()), Some(std::io::ErrorKind::TimedOut)); assert_eq!(waits.get(), LOCK_TRIES - 1); waits.set(0); let refused = revoke_grants(&data, None, None); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index dc052e1209..fa4647a450 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6627,6 +6627,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` per al diàleg de fitxers d’un script ha de ser un d’aquests: once, always, deny, stop @msg choose a file or folder first, or deny trieu primer un fitxer o una carpeta, o denegueu @msg the script file permissions could not be saved: {e} no s’han pogut desar els permisos de fitxers dels scripts: {e} +@msg the script file permissions could not be read: {e} no s’han pogut llegir els permisos de fitxers dels scripts: {e} @msg this script's file access can be allowed only once l’accés als fitxers d’aquest script només es pot permetre una vegada @msg Only the person at the keyboard can allow a script's file access Només la persona al teclat pot permetre l’accés als fitxers d’un script @msg A script is given at most 2,048 files: the files picked after them were left out Un script rep com a màxim 2.048 fitxers: els fitxers triats després d’aquests s’han deixat fora diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index baa6fdb5a0..791e28bee2 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5412,6 +5412,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` pro dialog souboru skriptu musí být jedna z hodnot: once, always, deny, stop @msg choose a file or folder first, or deny nejprve vyberte soubor nebo složku, nebo odmítněte @msg the script file permissions could not be saved: {e} oprávnění skriptů k souborům nelze uložit: {e} +@msg the script file permissions could not be read: {e} oprávnění skriptů k souborům nelze přečíst: {e} @msg this script's file access can be allowed only once přístup tohoto skriptu k souborům lze povolit jen jednou @msg Only the person at the keyboard can allow a script's file access Přístup skriptu k souborům může povolit jen člověk u klávesnice @msg A script is given at most 2,048 files: the files picked after them were left out Skript dostane nejvýše 2 048 souborů: soubory vybrané po nich byly vynechány diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 47c721d229..e805b3829c 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -99,6 +99,7 @@ @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` for et scripts fildialog skal være en af: once, always, deny, stop @msg choose a file or folder first, or deny vælg først en fil eller mappe, eller afvis @msg the script file permissions could not be saved: {e} scriptets filtilladelser kunne ikke gemmes: {e} +@msg the script file permissions could not be read: {e} scriptets filtilladelser kunne ikke læses: {e} @msg this script's file access can be allowed only once dette scripts filadgang kan kun tillades én gang @msg Only the person at the keyboard can allow a script's file access Kun personen ved tastaturet kan tillade et scripts filadgang @msg A script is given at most 2,048 files: the files picked after them were left out Et script får højst 2.048 filer: de filer, der blev valgt derefter, blev udeladt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index a625e018ef..7b8ff241eb 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4988,6 +4988,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` für den Dateidialog eines Skripts muss einer der folgenden Werte sein: once, always, deny, stop @msg choose a file or folder first, or deny wählen Sie zuerst eine Datei oder einen Ordner aus oder lehnen Sie ab @msg the script file permissions could not be saved: {e} die Dateiberechtigungen der Skripte konnten nicht gespeichert werden: {e} +@msg the script file permissions could not be read: {e} die Dateiberechtigungen der Skripte konnten nicht gelesen werden: {e} @msg this script's file access can be allowed only once der Dateizugriff dieses Skripts kann nur einmal erlaubt werden @msg Only the person at the keyboard can allow a script's file access Nur die Person an der Tastatur kann den Dateizugriff eines Skripts erlauben @msg A script is given at most 2,048 files: the files picked after them were left out Ein Skript erhält höchstens 2.048 Dateien: Die danach ausgewählten Dateien wurden weggelassen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e428decf7c..6f13330deb 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2825,6 +2825,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop το `answer` για το παράθυρο διαλόγου αρχείων ενός σεναρίου πρέπει να είναι ένα από: once, always, deny, stop @msg choose a file or folder first, or deny επιλέξτε πρώτα ένα αρχείο ή έναν φάκελο, ή απορρίψτε @msg the script file permissions could not be saved: {e} δεν ήταν δυνατή η αποθήκευση των αδειών αρχείων των σεναρίων: {e} +@msg the script file permissions could not be read: {e} δεν ήταν δυνατή η ανάγνωση των αδειών αρχείων των σεναρίων: {e} @msg this script's file access can be allowed only once η πρόσβαση αυτού του σεναρίου σε αρχεία μπορεί να επιτραπεί μόνο μία φορά @msg Only the person at the keyboard can allow a script's file access Μόνο το άτομο στο πληκτρολόγιο μπορεί να επιτρέψει την πρόσβαση ενός σεναρίου σε αρχεία @msg A script is given at most 2,048 files: the files picked after them were left out Ένα σενάριο λαμβάνει το πολύ 2.048 αρχεία: τα αρχεία που επιλέχθηκαν μετά από αυτά παραλείφθηκαν diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 6c9867b07c..be92272e97 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5099,6 +5099,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` para el cuadro de diálogo de archivo de un script debe ser uno de: once, always, deny, stop @msg choose a file or folder first, or deny elija primero un archivo o una carpeta, o deniegue @msg the script file permissions could not be saved: {e} no se pudieron guardar los permisos de archivos de los scripts: {e} +@msg the script file permissions could not be read: {e} no se pudieron leer los permisos de archivos de los scripts: {e} @msg this script's file access can be allowed only once el acceso a archivos de este script solo se puede permitir una vez @msg Only the person at the keyboard can allow a script's file access Solo la persona que está en el teclado puede permitir el acceso a archivos de un script @msg A script is given at most 2,048 files: the files picked after them were left out Un script recibe como máximo 2.048 archivos: los archivos elegidos después de ellos se omitieron diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bba3adf2e7..360e2ecedf 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5340,6 +5340,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop komentosarjan tiedostovalintaikkunan `answer`-arvon on oltava jokin seuraavista: once, always, deny, stop @msg choose a file or folder first, or deny valitse ensin tiedosto tai kansio tai estä @msg the script file permissions could not be saved: {e} komentosarjojen tiedostolupia ei voitu tallentaa: {e} +@msg the script file permissions could not be read: {e} komentosarjojen tiedostolupia ei voitu lukea: {e} @msg this script's file access can be allowed only once tämän komentosarjan tiedostojen käytön voi sallia vain kerran @msg Only the person at the keyboard can allow a script's file access Vain näppäimistön ääressä oleva ihminen voi sallia komentosarjan tiedostojen käytön @msg A script is given at most 2,048 files: the files picked after them were left out Komentosarja saa enintään 2 048 tiedostoa: niiden jälkeen valitut tiedostot jätettiin pois diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index f31aad04d4..347773645c 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5058,6 +5058,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` pour la boîte de dialogue de fichiers d’un script doit être l’une des valeurs : once, always, deny, stop @msg choose a file or folder first, or deny choisissez d’abord un fichier ou un dossier, ou refusez @msg the script file permissions could not be saved: {e} les autorisations d’accès aux fichiers des scripts n’ont pas pu être enregistrées : {e} +@msg the script file permissions could not be read: {e} les autorisations d’accès aux fichiers des scripts n’ont pas pu être lues : {e} @msg this script's file access can be allowed only once l’accès aux fichiers de ce script ne peut être autorisé qu’une fois @msg Only the person at the keyboard can allow a script's file access Seule la personne au clavier peut autoriser l’accès aux fichiers d’un script @msg A script is given at most 2,048 files: the files picked after them were left out Un script reçoit au plus 2 048 fichiers : les fichiers choisis après eux ont été laissés de côté diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 9e8f4858ca..a89667cbf4 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7774,6 +7774,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop स्क्रिप्ट के फ़ाइल डायलॉग के लिए `answer` इनमें से एक होना चाहिए: once, always, deny, stop @msg choose a file or folder first, or deny पहले कोई फ़ाइल या फ़ोल्डर चुनें, या अस्वीकार करें @msg the script file permissions could not be saved: {e} स्क्रिप्ट की फ़ाइल अनुमतियाँ सेव नहीं की जा सकीं: {e} +@msg the script file permissions could not be read: {e} स्क्रिप्ट की फ़ाइल अनुमतियाँ पढ़ी नहीं जा सकीं: {e} @msg this script's file access can be allowed only once इस स्क्रिप्ट की फ़ाइल पहुँच केवल एक बार दी जा सकती है @msg Only the person at the keyboard can allow a script's file access किसी स्क्रिप्ट को फ़ाइल पहुँच केवल कीबोर्ड पर मौजूद व्यक्ति दे सकता है @msg A script is given at most 2,048 files: the files picked after them were left out किसी स्क्रिप्ट को अधिकतम 2,048 फ़ाइलें दी जाती हैं: उनके बाद चुनी गई फ़ाइलें छोड़ दी गईं diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 3a99075b4c..c60f8f6b01 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5930,6 +5930,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop a parancsfájl fájlpárbeszédpaneléhez tartozó `answer` értéke a következők egyike kell legyen: once, always, deny, stop @msg choose a file or folder first, or deny először válasszon fájlt vagy mappát, vagy utasítsa el @msg the script file permissions could not be saved: {e} a parancsfájlok fájlengedélyeit nem sikerült menteni: {e} +@msg the script file permissions could not be read: {e} a parancsfájlok fájlengedélyeit nem sikerült beolvasni: {e} @msg this script's file access can be allowed only once ennek a parancsfájlnak a fájlhozzáférése csak egyszer engedélyezhető @msg Only the person at the keyboard can allow a script's file access Parancsfájl fájlhozzáférését csak a billentyűzetnél ülő személy engedélyezheti @msg A script is given at most 2,048 files: the files picked after them were left out Egy parancsfájl legfeljebb 2 048 fájlt kap: az ezek után kiválasztott fájlok kimaradtak diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 853ee465b7..1be6b1859f 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8768,6 +8768,7 @@ breakText Glyphs Glif @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` untuk dialog file skrip harus salah satu dari: once, always, deny, stop @msg choose a file or folder first, or deny pilih file atau folder terlebih dahulu, atau tolak @msg the script file permissions could not be saved: {e} izin file skrip tidak dapat disimpan: {e} +@msg the script file permissions could not be read: {e} izin file skrip tidak dapat dibaca: {e} @msg this script's file access can be allowed only once akses file skrip ini hanya dapat diizinkan sekali @msg Only the person at the keyboard can allow a script's file access Hanya orang yang berada di depan keyboard yang dapat mengizinkan akses file skrip @msg A script is given at most 2,048 files: the files picked after them were left out Skrip diberi paling banyak 2.048 file: file yang dipilih sesudahnya dihilangkan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5a290e168a..b1f81d4037 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5126,6 +5126,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` per la finestra di dialogo dei file di uno script deve essere uno tra: once, always, deny, stop @msg choose a file or folder first, or deny scegli prima un file o una cartella, oppure nega @msg the script file permissions could not be saved: {e} impossibile salvare i permessi sui file degli script: {e} +@msg the script file permissions could not be read: {e} impossibile leggere i permessi sui file degli script: {e} @msg this script's file access can be allowed only once l'accesso ai file di questo script può essere consentito solo una volta @msg Only the person at the keyboard can allow a script's file access Solo la persona alla tastiera può consentire l’accesso ai file di uno script @msg A script is given at most 2,048 files: the files picked after them were left out Uno script riceve al massimo 2.048 file: i file scelti dopo questi sono stati esclusi diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 6dc915f9aa..e5947dfed1 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5961,6 +5961,7 @@ liquify-list-end {0}, {1} {0}、{1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop スクリプトのファイルダイアログの `answer` は once、always、deny、stop のいずれかにしてください @msg choose a file or folder first, or deny 先にファイルまたはフォルダーを選択するか、拒否してください @msg the script file permissions could not be saved: {e} スクリプトのファイル許可を保存できませんでした: {e} +@msg the script file permissions could not be read: {e} スクリプトのファイル許可を読み込めませんでした: {e} @msg this script's file access can be allowed only once このスクリプトのファイルアクセスは 1 回だけ許可できます @msg Only the person at the keyboard can allow a script's file access スクリプトのファイルアクセスを許可できるのはキーボードの前にいる人だけです @msg A script is given at most 2,048 files: the files picked after them were left out スクリプトに渡せるファイルは 2,048 個までのため、それ以降に選んだファイルは除外されました diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 6932462a4e..0ff6c1e96e 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8622,6 +8622,7 @@ liquify-list-end {0}, {1} {0} და {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop სკრიპტის ფაილის დიალოგისთვის `answer` უნდა იყოს ერთ-ერთი: once, always, deny, stop @msg choose a file or folder first, or deny ჯერ აირჩიეთ ფაილი ან საქაღალდე, ან უარყავით @msg the script file permissions could not be saved: {e} სკრიპტების ფაილების ნებართვების შენახვა ვერ მოხერხდა: {e} +@msg the script file permissions could not be read: {e} სკრიპტების ფაილების ნებართვების წაკითხვა ვერ მოხერხდა: {e} @msg this script's file access can be allowed only once ამ სკრიპტის წვდომა ფაილებზე მხოლოდ ერთხელ შეიძლება დაიშვას @msg Only the person at the keyboard can allow a script's file access სკრიპტის წვდომას ფაილებზე მხოლოდ კლავიატურასთან მყოფი ადამიანი უშვებს @msg A script is given at most 2,048 files: the files picked after them were left out სკრიპტი იღებს მაქსიმუმ 2 048 ფაილს: მათ შემდეგ არჩეული ფაილები გამოტოვებულია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index bddb440aee..62aadc98e0 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5890,6 +5890,7 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop 스크립트 파일 대화 상자의 `answer`는 once, always, deny, stop 중 하나여야 합니다 @msg choose a file or folder first, or deny 먼저 파일이나 폴더를 선택하거나 거부하세요 @msg the script file permissions could not be saved: {e} 스크립트 파일 권한을 저장할 수 없습니다: {e} +@msg the script file permissions could not be read: {e} 스크립트 파일 권한을 읽을 수 없습니다: {e} @msg this script's file access can be allowed only once 이 스크립트의 파일 접근은 한 번만 허용할 수 있습니다 @msg Only the person at the keyboard can allow a script's file access 스크립트의 파일 접근은 키보드 앞에 있는 사람만 허용할 수 있습니다 @msg A script is given at most 2,048 files: the files picked after them were left out 스크립트에는 파일이 최대 2,048개까지 전달됩니다: 그 뒤에 고른 파일은 제외되었습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d00f9960df..11ee1ab242 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -101,6 +101,7 @@ @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` voor het bestandsdialoogvenster van een script moet een van deze waarden zijn: once, always, deny, stop @msg choose a file or folder first, or deny kies eerst een bestand of map, of weiger @msg the script file permissions could not be saved: {e} de toestemmingen voor scriptbestanden konden niet worden opgeslagen: {e} +@msg the script file permissions could not be read: {e} de toestemmingen voor scriptbestanden konden niet worden gelezen: {e} @msg this script's file access can be allowed only once de bestandstoegang van dit script kan maar één keer worden toegestaan @msg Only the person at the keyboard can allow a script's file access Alleen de persoon aan het toetsenbord kan de bestandstoegang van een script toestaan @msg A script is given at most 2,048 files: the files picked after them were left out Een script krijgt maximaal 2.048 bestanden: de bestanden die daarna zijn gekozen, zijn weggelaten diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 6b41f2febc..6e44727fb7 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5231,6 +5231,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` dla okna dialogowego plików skryptu musi być jedną z wartości: once, always, deny, stop @msg choose a file or folder first, or deny najpierw wybierz plik lub folder albo odmów @msg the script file permissions could not be saved: {e} nie można zapisać uprawnień skryptów do plików: {e} +@msg the script file permissions could not be read: {e} nie można odczytać uprawnień skryptów do plików: {e} @msg this script's file access can be allowed only once na dostęp tego skryptu do plików można zezwolić tylko raz @msg Only the person at the keyboard can allow a script's file access Na dostęp skryptu do plików może zezwolić tylko osoba przy klawiaturze @msg A script is given at most 2,048 files: the files picked after them were left out Skrypt otrzymuje najwyżej 2 048 plików: pliki wybrane po nich zostały pominięte diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 6cc30c65b5..835acc5f0c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6270,6 +6270,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` para a caixa de diálogo de arquivo de um script deve ser um destes: once, always, deny, stop @msg choose a file or folder first, or deny escolha primeiro um arquivo ou uma pasta, ou negue @msg the script file permissions could not be saved: {e} não foi possível salvar as permissões de arquivos dos scripts: {e} +@msg the script file permissions could not be read: {e} não foi possível ler as permissões de arquivos dos scripts: {e} @msg this script's file access can be allowed only once o acesso a arquivos deste script só pode ser permitido uma vez @msg Only the person at the keyboard can allow a script's file access Somente a pessoa ao teclado pode permitir o acesso a arquivos de um script @msg A script is given at most 2,048 files: the files picked after them were left out Um script recebe no máximo 2.048 arquivos: os arquivos escolhidos depois deles foram deixados de fora diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 59bc9f7d62..83e5e813fa 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5121,6 +5121,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` для файлового диалога скрипта должен быть одним из: once, always, deny, stop @msg choose a file or folder first, or deny сначала выберите файл или папку либо откажите @msg the script file permissions could not be saved: {e} не удалось сохранить разрешения скриптов на файлы: {e} +@msg the script file permissions could not be read: {e} не удалось прочитать разрешения скриптов на файлы: {e} @msg this script's file access can be allowed only once доступ этого скрипта к файлам можно разрешить только один раз @msg Only the person at the keyboard can allow a script's file access Разрешить скрипту доступ к файлам может только человек за клавиатурой @msg A script is given at most 2,048 files: the files picked after them were left out Скрипт получает не больше 2 048 файлов: файлы, выбранные после них, пропущены diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index d8355b2c4a..0a1f790715 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4997,6 +4997,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` för ett skripts fildialog måste vara ett av: once, always, deny, stop @msg choose a file or folder first, or deny välj först en fil eller mapp, eller neka @msg the script file permissions could not be saved: {e} skriptens filbehörigheter kunde inte sparas: {e} +@msg the script file permissions could not be read: {e} skriptens filbehörigheter kunde inte läsas: {e} @msg this script's file access can be allowed only once det här skriptets filåtkomst kan bara tillåtas en gång @msg Only the person at the keyboard can allow a script's file access Bara personen vid tangentbordet kan tillåta ett skripts filåtkomst @msg A script is given at most 2,048 files: the files picked after them were left out Ett skript får högst 2 048 filer: filerna som valdes efter dem utelämnades diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index a95d4cbf1b..b04336d7dc 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2998,6 +2998,7 @@ fn script_file_messages_translate_in_every_complete_message_language() { "`answer` for a script's file dialog must be one of: once, always, deny, stop", "choose a file or folder first, or deny", "the script file permissions could not be saved: {e}", + "the script file permissions could not be read: {e}", "this script's file access can be allowed only once", "Only the person at the keyboard can allow a script's file access", ]; diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index cd74ca9166..945c03002d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4833,6 +4833,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop bir betiğin dosya iletişim kutusu için `answer` şunlardan biri olmalıdır: once, always, deny, stop @msg choose a file or folder first, or deny önce bir dosya veya klasör seçin ya da reddedin @msg the script file permissions could not be saved: {e} betiklerin dosya izinleri kaydedilemedi: {e} +@msg the script file permissions could not be read: {e} betiklerin dosya izinleri okunamadı: {e} @msg this script's file access can be allowed only once bu betiğin dosya erişimine yalnızca bir kez izin verilebilir @msg Only the person at the keyboard can allow a script's file access Bir betiğin dosya erişimine yalnızca klavye başındaki kişi izin verebilir @msg A script is given at most 2,048 files: the files picked after them were left out Bir betiğe en fazla 2.048 dosya verilir: bunlardan sonra seçilen dosyalar dışarıda bırakıldı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index eedb12c21a..509d816012 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5110,6 +5110,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` для файлового діалогу скрипту має бути одним із: once, always, deny, stop @msg choose a file or folder first, or deny спершу виберіть файл або папку чи відмовте @msg the script file permissions could not be saved: {e} не вдалося зберегти дозволи скриптів на файли: {e} +@msg the script file permissions could not be read: {e} не вдалося прочитати дозволи скриптів на файли: {e} @msg this script's file access can be allowed only once доступ цього скрипту до файлів можна дозволити лише один раз @msg Only the person at the keyboard can allow a script's file access Дозволити скрипту доступ до файлів може лише людина за клавіатурою @msg A script is given at most 2,048 files: the files picked after them were left out Скрипт отримує щонайбільше 2 048 файлів: файли, вибрані після них, пропущено diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da6d0ae64d..d7bfad3331 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5620,6 +5620,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` cho hộp thoại tệp của tập lệnh phải là một trong: once, always, deny, stop @msg choose a file or folder first, or deny hãy chọn một tệp hoặc thư mục trước, hoặc từ chối @msg the script file permissions could not be saved: {e} không thể lưu quyền truy cập tệp của các tập lệnh: {e} +@msg the script file permissions could not be read: {e} không thể đọc quyền truy cập tệp của các tập lệnh: {e} @msg this script's file access can be allowed only once quyền truy cập tệp của tập lệnh này chỉ có thể được cho phép một lần @msg Only the person at the keyboard can allow a script's file access Chỉ người ngồi tại bàn phím mới có thể cho phép tập lệnh truy cập tệp @msg A script is given at most 2,048 files: the files picked after them were left out Một tập lệnh nhận tối đa 2.048 tệp: các tệp được chọn sau đó đã bị bỏ qua diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f66731afe..4b9233d962 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5617,6 +5617,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop 脚本文件对话框的 `answer` 必须是以下之一:once、always、deny、stop @msg choose a file or folder first, or deny 请先选择文件或文件夹,或拒绝 @msg the script file permissions could not be saved: {e} 无法保存脚本的文件权限:{e} +@msg the script file permissions could not be read: {e} 无法读取脚本的文件权限:{e} @msg this script's file access can be allowed only once 此脚本的文件访问只能允许一次 @msg Only the person at the keyboard can allow a script's file access 只有键盘前的人才能允许脚本访问文件 @msg A script is given at most 2,048 files: the files picked after them were left out 脚本最多获得 2,048 个文件:之后选择的文件已被略去 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d430105f73..5b13726f77 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2972,6 +2972,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop 指令碼檔案對話框的 `answer` 必須是下列之一:once、always、deny、stop @msg choose a file or folder first, or deny 請先選擇檔案或資料夾,或拒絕 @msg the script file permissions could not be saved: {e} 無法儲存指令碼的檔案權限:{e} +@msg the script file permissions could not be read: {e} 無法讀取指令碼的檔案權限:{e} @msg this script's file access can be allowed only once 此指令碼的檔案存取只能允許一次 @msg Only the person at the keyboard can allow a script's file access 只有鍵盤前的人才能允許指令碼存取檔案 @msg A script is given at most 2,048 files: the files picked after them were left out 指令碼最多取得 2,048 個檔案:之後選擇的檔案已略去 diff --git a/crates/ui-egui/src/prefs_dialog/script_access.rs b/crates/ui-egui/src/prefs_dialog/script_access.rs index 219145e60f..f1f8fa4416 100644 --- a/crates/ui-egui/src/prefs_dialog/script_access.rs +++ b/crates/ui-egui/src/prefs_dialog/script_access.rs @@ -18,6 +18,10 @@ pub(super) const ROWS: &str = "__scriptAccess"; /// The dialog field that holds the row whose Revoke button takes the keyboard focus next. const FOCUS: &str = "__scriptAccessFocus"; +/// The dialog field that holds, in English, why the grants file cannot be read or changed +/// (`script.grants`' `error`), absent when it can. +pub(super) const ERROR: &str = "__scriptAccessError"; + /// The most characters of a path a row shows. const MAX_SHOWN_PATH: usize = 1024; @@ -35,10 +39,16 @@ const WHOLE: [(&str, &str); 2] = [("script", "wholeScript"), ("path", "wholePath /// `fields`. Where the session keeps no grants, the field is removed. The grants file is the app's /// own, so it is read with no automation roots in force: each row keeps its script and path whole /// (`wholeScript` and `wholePath`) for `script.grants.revoke`, and shows them (`script` and `path`) -/// as `script.grants` names them to the request that opened the dialog ([`as_listed`]). +/// as `script.grants` names them to the request that opened the dialog ([`as_listed`]). When the +/// grants file cannot be read or changed, its error goes in the field [`ERROR`], with the rows of the +/// grants that could still be read. pub(super) fn load(app: &mut VectorcraftApp, fields: &mut Map) { + fields.remove(ERROR); match vectorcraft_engine::file_access::unconfined(|| app.session.execute("script.grants", &json!({}))) { Ok(v) if !v["file"].is_null() => { + if let Some(error) = v["error"].as_str() { + fields.insert(ERROR.into(), json!(error)); + } let mut rows = rows(&v["grants"]); for row in rows.iter_mut().filter_map(Value::as_object_mut) { for (shown, whole) in WHOLE { @@ -131,15 +141,23 @@ enum Line { } /// The section, after General › Show External Script Warning, when the dialog `d` has rows: each -/// script, its paths with their access and a Revoke button, or a line saying there are none. +/// script, its paths with their access and a Revoke button, or a line saying there are none. When +/// the grants file cannot be read or changed, its error shows first, and the line saying there are +/// none does not. pub(super) fn show(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog) { let Some(rows) = d.fields.get(ROWS).and_then(Value::as_array).cloned() else { return }; let t = Tokens::get(ui.ctx()); ui.add_space(8.0); ui.label(egui::RichText::new(tl!("Script File Access")).font(theme::semibold(12.5)).color(t.text_strong)); ui.add_space(2.0); + let error = d.fields.get(ERROR).and_then(Value::as_str); + if let Some(error) = error { + ui.label(egui::RichText::new(crate::i18n::msg(error)).color(t.error).size(11.5)); + } if rows.is_empty() { - ui.label(egui::RichText::new(tl!("No script has kept file access.")).color(t.text_dim).size(11.5)); + if error.is_none() { + ui.label(egui::RichText::new(tl!("No script has kept file access.")).color(t.text_dim).size(11.5)); + } return; } let mut lines = Vec::with_capacity(rows.len() * 2); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 94d710dead..10e4305b34 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -3211,6 +3211,32 @@ fn script_file_access_revoke_refuses_a_malformed_or_oversized_grants_file() { } } +/// Preferences opened over a grants file that cannot be read or changed (not well formed, not +/// JSON, or over 4 MiB) shows why under Script File Access instead of saying that no script has +/// kept file access, lists the grants that can still be read, and leaves the file as it was. +#[test] +fn script_file_access_shows_why_the_grants_file_cannot_be_read() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let kept = grant(&dir.join("a.jsx"), &dir.join("out.txt"), "1", false, false); + let malformed = serde_json::to_vec(&json!({"version": 1, "grants": [kept, {"script": "x"}]})).unwrap(); + let mut oversized = br#"{"version": 1, "grants": []}"#.to_vec(); + oversized.resize((4 << 20) + 1, b' '); + for (name, held, rows) in [("malformed", malformed, 1), ("broken", b"{ not json".to_vec(), 0), ("oversized", oversized, 0)] { + let (mut a, store) = app_with_grants(&format!("grants-unread-{name}"), json!([])); + std::fs::write(&store, &held).unwrap(); + open(&mut a, Some("General")); + assert_eq!(access_rows(&a).len(), rows, "{name}"); + let fields = &a.ui.dialog.as_ref().unwrap().fields; + let error = fields.get(script_access::ERROR).and_then(Value::as_str).unwrap_or_default().to_string(); + assert!(error.starts_with("the script file permissions could not be read: "), "{name}: {error:?}"); + script_access_in_view(&mut a, &fonts_context(), &error); + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(!text.contains("No script has kept file access."), "{name}: {text}"); + assert_eq!(std::fs::read(&store).unwrap(), held, "{name}: the grants file is left as it was"); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); + } +} + /// A script or path with control or bidirectional formatting characters shows them as escapes, so /// it cannot break its row or draw as another name. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 1253778638..f1106d23c6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3047,7 +3047,7 @@ VectorCraft writes files by these rules of its own: `Script file dialogs need a person to answer them`, and takes no kept grant. In the app, a file dialog inside a built-in's callback, a getter, a conversion or a file `$.evalFile` runs throws an error. -`script.grants {}` lists the kept grants: `{grants: [{script, sha256, code, path, write, folder}], file}`, with `code` +`script.grants {}` lists the kept grants: `{grants: [{script, sha256, code, path, write, folder}], file, error?}`, with `code` the SHA-256 of each evaluated source (of its UTF-16 code units in little-endian order), `folder` true for a folder's grant, which covers everything in the folder (a file's grant covers its own path only, also when a folder later takes its place), and `file` the grants @@ -3056,8 +3056,10 @@ is given as its file name alone. `script.grants.revoke {script?, path?, all?}` r a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. A path is matched after its links are followed; under automation read roots, a path outside them is matched as given. While a script runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but -cannot be read is left as it is: `script.grants.revoke` fails, and a grant picked with Always is not kept. A script -cannot run either command. +cannot be read is left as it is: `script.grants.revoke` fails, and a grant picked with Always is not kept. For such a +file, and one that is over 4 MiB, is not a version 1 grants file, holds a grant that is not well formed or more than +4096 grants, or whose lock cannot be taken, `script.grants` gives the reason in `error` and lists the well-formed grants +it can still read. Preferences › General › Script File Access shows that error. A script cannot run either command. ```json {"name":"run_command","arguments":{"command":"script.grants.revoke","params":{"all":true}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9b0a072347..119a93b3c6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1041,7 +1041,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; 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: Preferences › General › Script File Access lists the file access kept with Always Allow This Script (`script.grants`), one row for each script and path with its widest access (read file, read and write file, or read and write folder), and its Revoke button removes every kept version of that script and path (`script.grants.revoke`), so the next run asks again. Paths show control and bidirectional characters as escapes, and a script or path outside the automation read roots in force when Preferences opens shows by its file name, as `script.grants` lists it, and Revoke still removes it; a grants file that is not well formed or is over 4 MiB makes Revoke show its error and leaves the file as it was. VectorCraft's own addition. `crates/ui-egui/src/prefs_dialog/tests.rs` (`script_file_access_*`). + - Scripts: Preferences › General › Script File Access lists the file access kept with Always Allow This Script (`script.grants`), one row for each script and path with its widest access (read file, read and write file, or read and write folder), and its Revoke button removes every kept version of that script and path (`script.grants.revoke`), so the next run asks again. Paths show control and bidirectional characters as escapes, and a script or path outside the automation read roots in force when Preferences opens shows by its file name, as `script.grants` lists it, and Revoke still removes it; a grants file that is not well formed or is over 4 MiB shows its error in the section when Preferences opens, with the grants that can still be read, makes Revoke show its error, and is left as it was. VectorCraft's own addition. `crates/ui-egui/src/prefs_dialog/tests.rs` (`script_file_access_*`). - 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`. From 3886c934122f3c01d8839030d29e3d2500a32776 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 17:31:07 -0800 Subject: [PATCH 4/9] Scripts: say that script.grants lists no grants when the lock is busy When the grants file's lock cannot be taken, script.grants returns the error without reading the file, so the grants list is empty. docs/mcp.md, the command's params text and the doc comments of stored_grants and the Script File Access loader now say so, and keep "lists the well-formed grants it can still read" for a file that is unreadable, over 4 MiB, of another version, malformed or over 4096 grants. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/files.rs | 3 ++- crates/ui-egui/src/prefs_dialog/script_access.rs | 2 +- docs/mcp.md | 8 +++++--- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 44b8b7f432..30cd846e29 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "List Script File Permissions", [], None, - "{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web), error?: why the grants file cannot be read or changed, when it is there and cannot be read, is over 4 MiB, is not a version 1 grants file, holds a grant that is not well formed or more than 4096 grants, or its lock cannot be taken (grants then lists the well-formed grants that can still be read, if any, and script.grants.revoke fails)}", + "{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web), error?: why the grants file cannot be read or changed, when it is there and cannot be read, is over 4 MiB, is not a version 1 grants file, holds a grant that is not well formed or more than 4096 grants, or its lock cannot be taken (grants then lists the well-formed grants that can still be read, if any, or is empty when the lock cannot be taken, as the file is then not read; script.grants.revoke fails)}", always, grants ), diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 191f1c52e0..e023e83b45 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1065,7 +1065,8 @@ fn lock_store(_: &Path) -> std::io::Result { /// its text, the path and whether it may be written (`script.grants`), as [`read_store`] reads /// them, and the error when the file is there and [`try_read_store`] refuses it (it cannot be read, /// is too large, is not a grants file of this version, or holds a grant that is not well formed or -/// more grants than may be kept) or its lock cannot be taken, which also refuses a change. +/// more grants than may be kept) or its lock cannot be taken, which also refuses a change. When the +/// lock cannot be taken the file is not read, and the list is empty. pub(crate) fn stored_grants(data_dir: &Path) -> (Vec, Option) { let store = data_dir.with_file_name(GRANTS_FILE); let _lock = match lock_store(&store) { diff --git a/crates/ui-egui/src/prefs_dialog/script_access.rs b/crates/ui-egui/src/prefs_dialog/script_access.rs index f1f8fa4416..78a9969f9e 100644 --- a/crates/ui-egui/src/prefs_dialog/script_access.rs +++ b/crates/ui-egui/src/prefs_dialog/script_access.rs @@ -41,7 +41,7 @@ const WHOLE: [(&str, &str); 2] = [("script", "wholeScript"), ("path", "wholePath /// (`wholeScript` and `wholePath`) for `script.grants.revoke`, and shows them (`script` and `path`) /// as `script.grants` names them to the request that opened the dialog ([`as_listed`]). When the /// grants file cannot be read or changed, its error goes in the field [`ERROR`], with the rows of the -/// grants that could still be read. +/// grants that could still be read (none when its lock cannot be taken). pub(super) fn load(app: &mut VectorcraftApp, fields: &mut Map) { fields.remove(ERROR); match vectorcraft_engine::file_access::unconfined(|| app.session.execute("script.grants", &json!({}))) { diff --git a/docs/mcp.md b/docs/mcp.md index 45c66c077c..3cc36056ac 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3062,9 +3062,11 @@ a script file, of a path, of both together, or with `all: true` every grant, and matched after its links are followed; under automation read roots, a path outside them is matched as given. While a script runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but cannot be read is left as it is: `script.grants.revoke` fails, and a grant picked with Always is not kept. For such a -file, and one that is over 4 MiB, is not a version 1 grants file, holds a grant that is not well formed or more than -4096 grants, or whose lock cannot be taken, `script.grants` gives the reason in `error` and lists the well-formed grants -it can still read. Preferences › General › Script File Access shows that error. A script cannot run either command. +file, and one that is over 4 MiB, is not a version 1 grants file, or holds a grant that is not well formed or more than +4096 grants, `script.grants` gives the reason in `error` and lists the well-formed grants it can still read. When the +grants file's lock cannot be taken, `script.grants` gives the reason in `error` and does not read the file, so `grants` +is empty even when the file holds grants. Preferences › General › Script File Access shows that error. A script cannot +run either command. ```json {"name":"run_command","arguments":{"command":"script.grants.revoke","params":{"all":true}}} From c7108b22890f85849f0ef605c00e13678c4a639b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 17:57:57 -0800 Subject: [PATCH 5/9] Script File Access: name the whole path in Revoke's tooltip and description A row shows at most 1,024 characters of a script or path, so two grants whose paths differ only after that showed the same text in the row, its tooltip and the Revoke button's screen-reader description. The tooltips and the description now give the whole path, with control and bidirectional characters still written as escapes; the row label stays shortened. --- .../ui-egui/src/prefs_dialog/script_access.rs | 22 ++++++++++----- crates/ui-egui/src/prefs_dialog/tests.rs | 28 +++++++++++++++++++ 2 files changed, 43 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/prefs_dialog/script_access.rs b/crates/ui-egui/src/prefs_dialog/script_access.rs index 78a9969f9e..80deee700f 100644 --- a/crates/ui-egui/src/prefs_dialog/script_access.rs +++ b/crates/ui-egui/src/prefs_dialog/script_access.rs @@ -102,6 +102,13 @@ pub(super) fn shown(path: &str) -> String { permissions::display_text(path, MAX_SHOWN_PATH) } +/// `path` as a row's tooltip and its Revoke button's screen-reader description give it: control and +/// bidirectional formatting characters written as escapes, and whole, so two paths that a row shows +/// alike stay apart. +fn shown_whole(path: &str) -> String { + permissions::display_text(path, usize::MAX) +} + /// A kept script or path as `script.grants` names it to the request being served: whole where that /// request may read it, else its file name alone (empty for a path that ends in no name). pub(crate) fn as_listed(path: &str) -> &str { @@ -185,15 +192,16 @@ pub(super) fn show(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog) let size = egui::vec2(ui.available_width(), ROW_HEIGHT); match *line { Line::Script(i) => { - let script = shown(rows[i]["script"].as_str().unwrap_or_default()); + let script = rows[i]["script"].as_str().unwrap_or_default(); ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| { - let text = egui::RichText::new(&script).color(t.text_strong).size(12.0); - ui.add(egui::Label::new(text).truncate()).on_hover_text(&script); + let text = egui::RichText::new(shown(script)).color(t.text_strong).size(12.0); + ui.add(egui::Label::new(text).truncate()).on_hover_text(shown_whole(script)); }); } Line::Row(i) => { let row = &rows[i]; - let (script, path) = (shown(row["script"].as_str().unwrap_or_default()), shown(row["path"].as_str().unwrap_or_default())); + let (script, path) = (row["script"].as_str().unwrap_or_default(), row["path"].as_str().unwrap_or_default()); + let (script, path, path_whole) = (shown_whole(script), shown(path), shown_whole(path)); ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| { ui.add_space(12.0); // The path, then the access and the Revoke button at the right. @@ -202,7 +210,7 @@ pub(super) fn show(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog) let cell = |width: f32| egui::vec2(width, ROW_HEIGHT); ui.allocate_ui_with_layout(cell(path_width), egui::Layout::left_to_right(egui::Align::Center), |ui| { ui.set_width(path_width); - ui.add(egui::Label::new(egui::RichText::new(&path).color(t.text)).truncate()).on_hover_text(&path); + ui.add(egui::Label::new(egui::RichText::new(&path).color(t.text)).truncate()).on_hover_text(&path_whole); }); ui.add_space(12.0); ui.allocate_ui_with_layout(cell(access_width), egui::Layout::left_to_right(egui::Align::Center), |ui| { @@ -212,11 +220,11 @@ pub(super) fn show(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog) }); let button = widgets::secondary_button(ui, tl!("Revoke")); // A screen reader names the script and the path along with the button. - ui.ctx().accesskit_node_builder(button.id, |node| node.set_description(format!("{script}: {path}"))); + ui.ctx().accesskit_node_builder(button.id, |node| node.set_description(format!("{script}: {path_whole}"))); if focus == Some(i) { button.request_focus(); } - if button.on_hover_text(&path).clicked() { + if button.on_hover_text(&path_whole).clicked() { revoke_at = Some(i); } }); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 2ee1cf2663..990bf57b3d 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -3255,6 +3255,34 @@ fn script_file_access_shows_paths_as_plain_text() { let _ = std::fs::remove_dir_all(store.parent().unwrap()); } +/// Two paths that differ only after the characters a row shows keep their whole paths in the Revoke +/// buttons' screen-reader descriptions, so each button names the grant it removes. +#[test] +fn script_file_access_revoke_names_the_whole_path() { + let mut long = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + for _ in 0..11 { + long.push("d".repeat(100)); + } + let (script, one, two) = (long.with_file_name("a.jsx"), long.join("1.txt"), long.join("2.txt")); + let (mut a, store) = app_with_grants("grants-long", json!([grant(&script, &one, "1", false, false), grant(&script, &two, "1", false, false)])); + open(&mut a, Some("General")); + let ctx = fonts_context(); + ctx.enable_accesskit(); + script_access_in_view(&mut a, &ctx, "Revoke"); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))); + let raw = egui::RawInput { screen_rect, time: Some(ctx.input(|i| i.time) + 0.25), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(&mut a, ui.ctx())); + out.textures_delta.clear(); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let descriptions: Vec = + nodes.iter().filter(|(_, n)| n.label() == Some("Revoke")).filter_map(|(_, n)| n.description().map(str::to_string)).collect(); + for path in [&one, &two] { + let whole = path.to_string_lossy(); + assert!(descriptions.iter().any(|d| d.ends_with(&*whole)), "{whole} in {descriptions:?}"); + } + let _ = std::fs::remove_dir_all(store.parent().unwrap()); +} + fn description_fits(ui: &egui::Ui, text: &str) -> bool { let mut job = egui::text::LayoutJob::simple(text.to_string(), egui::FontId::proportional(11.5), egui::Color32::WHITE, 530.0); job.wrap.max_rows = 3; From b3430b7f825a832fe09c8b85459d8ea9440d7df5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 04:45:41 -0800 Subject: [PATCH 6/9] Script File Access: no row for a grant with an empty script or path script.grants lists a kept grant whose script or path is an empty string, but script.grants.revoke does not take an empty path, so its Revoke button could not remove it. Such a grant now has no row. --- .../ui-egui/src/prefs_dialog/script_access.rs | 6 +++++- crates/ui-egui/src/prefs_dialog/tests.rs | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/prefs_dialog/script_access.rs b/crates/ui-egui/src/prefs_dialog/script_access.rs index e8e70ec1eb..bdf4b128f5 100644 --- a/crates/ui-egui/src/prefs_dialog/script_access.rs +++ b/crates/ui-egui/src/prefs_dialog/script_access.rs @@ -77,7 +77,8 @@ pub(super) fn load(app: &mut VectorcraftApp) -> Option { /// The rows for the grants `grants` lists: one for each script and path, sorted by script and then by path, with the /// widest access any kept version of the pair has (`folder`, then `write`, then `read`) and how many versions are -/// kept. A grant without a script or a path is left out. +/// kept. A grant without a script or a path, or with an empty one, which `script.grants.revoke` does not take, is +/// left out. fn rows(grants: &Value) -> Vec { let rank = |access: &str| match access { "folder" => 2, @@ -87,6 +88,9 @@ fn rows(grants: &Value) -> Vec { let mut pairs: BTreeMap<(&str, &str), (&'static str, usize)> = BTreeMap::new(); for g in grants.as_array().into_iter().flatten() { let (Some(script), Some(path)) = (g["script"].as_str(), g["path"].as_str()) else { continue }; + if script.is_empty() || path.is_empty() { + continue; + } let access = if g["folder"] == true { "folder" } else if g["write"] == true { diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 02c9913b43..c148173378 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -833,6 +833,25 @@ fn script_file_access_shows_none_and_a_revoke_of_a_removed_row() { assert!(access_texts(&mut web).is_empty()); } +/// A kept grant with an empty script or path, which `script.grants` lists and `script.grants.revoke` does not take, +/// has no row. +#[test] +fn script_file_access_leaves_out_a_grant_with_an_empty_script_or_path() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let (script, path) = (dir.join("a.jsx"), dir.join("out.txt")); + let grants = json!([ + grant(&script, &path, "1", false, false), + grant(&script, "".as_ref(), "1", false, false), + grant("".as_ref(), &path, "1", false, false) + ]); + let (mut a, store) = app_with_grants("grants-empty", grants); + assert_eq!(a.session.execute("script.grants", &json!({})).unwrap()["grants"].as_array().map(Vec::len), Some(3)); + open(&mut a, Some("General")); + let row = (script.to_string_lossy().into_owned(), path.to_string_lossy().into_owned(), "read".to_string(), 1); + assert_eq!(access_rows(&a), [row]); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); +} + /// Preferences opened with a read root in force shows a script and a path outside it by their file /// names alone, as `script.grants` lists them, and `ui.inspect` names them the same way; Revoke /// still removes that pair's kept grants, both with the root in force and without it. From 73978a194fc3402afa123d28b68565a6eec746ad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 10:00:05 -0800 Subject: [PATCH 7/9] Scripts: script.grants.revoke matches a path as given as well as resolved A grant whose path a link has since replaced is listed by script.grants under the path it was kept for, but script.grants.revoke followed the link and compared the link's target, so Revoke in Script File Access removed nothing. A path is now matched as given and, inside the automation read roots, also with its links followed. --- crates/engine/src/cmd/scripts.rs | 17 ++++++++++------- crates/engine/src/script/files.rs | 10 +++++----- crates/engine/src/tests/script_io.rs | 22 ++++++++++++++++++++++ docs/mcp.md | 2 +- 4 files changed, 38 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 2640433606..14ad0685fd 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -104,7 +104,7 @@ pub fn specs() -> Vec { "Revoke Script File Permissions", [], None, - "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as script.grants lists it, after its links are followed (a path outside the automation read roots is matched as given); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", + "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as given and as script.grants lists it, after its links are followed (a path outside the automation read roots is matched as given only); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", always, grants_revoke ), @@ -384,16 +384,19 @@ fn grants(s: &mut Session, _: &Value) -> Result { fn grants_revoke(s: &mut Session, p: &Value) -> Result { const C: &str = "script.grants.revoke"; + // A path is matched as given, and also with its links followed, so a grant whose path a link + // has since taken the place of is still removed. A path the request may not read (outside the + // automation read roots, a network path among them) is compared as written, without looking it up. let path_of = |key: &str| match p.get(key) { None => Ok(None), - // A path the request may not read (outside the automation read roots, a network path among - // them) is compared as written, without looking it up. - Some(Value::String(t)) if !t.is_empty() => Ok(Some( - crate::file_access::check_read(t) + Some(Value::String(t)) if !t.is_empty() => { + let real = crate::file_access::check_read(t) .ok() .and_then(|()| std::fs::canonicalize(t).ok()) - .map_or_else(|| t.clone(), |real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()), - )), + .map(|real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()) + .filter(|real| real != t); + Ok(Some([Some(t.clone()), real].into_iter().flatten().collect::>())) + } Some(_) => Err(bad(C, format!("`{key}` must be a path"))), }; let (script_path, path) = (path_of("script")?, path_of("path")?); diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 476fbde5ad..a914f2d474 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1079,15 +1079,15 @@ pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result, path: Option<&str>) -> std::io::Result { +/// `path` (each matched by any of its spellings), of both when both are given and of every grant +/// when neither is (`script.grants.revoke`). → how many were removed. +pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&[String]>, path: Option<&[String]>) -> std::io::Result { let store = data_dir.with_file_name(GRANTS_FILE); let _lock = lock_store(&store)?; let grants = try_read_store(&store)?; let before = grants.len(); - let kept: Vec = - grants.into_iter().filter(|g| !(script.is_none_or(|s| g["script"] == *s) && path.is_none_or(|p| g["path"] == *p))).collect(); + let matches = |value: &serde_json::Value, names: Option<&[String]>| names.is_none_or(|names| names.iter().any(|n| value == n.as_str())); + let kept: Vec = grants.into_iter().filter(|g| !(matches(&g["script"], script) && matches(&g["path"], path))).collect(); let removed = before - kept.len(); if removed > 0 { write_store(&store, kept)?; diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index e5d854850d..d4eed1b4f4 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -652,6 +652,28 @@ fn a_grants_change_without_its_lock_changes_nothing() { let _ = std::fs::remove_dir_all(base); } +/// `script.grants.revoke` removes a grant by the path `script.grants` lists for it, also when a +/// link has since taken that path's place and leads elsewhere. +#[cfg(unix)] +#[test] +fn a_grant_whose_path_is_now_a_link_is_revoked_by_its_listed_path() { + let base = folder("grants-relinked"); + let real = std::fs::canonicalize(&base).unwrap(); + let (kept, other) = (real.join("kept.txt"), real.join("other.txt")); + write(&other, b"other"); + let kept_path = kept.to_string_lossy().into_owned(); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": kept_path, "write": false, "folder": false}); + write(&base.join("settings/Script Grants.json"), json!({"version": 1, "grants": [grant]}).to_string().as_bytes()); + std::os::unix::fs::symlink(&other, &kept).unwrap(); + let mut s = with_data(&base); + let listed = s.execute("script.grants", &json!({})).unwrap(); + assert_eq!(listed["grants"][0]["path"], json!(kept_path)); + let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap(); + assert_eq!(r["removed"], 1, "{r}"); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([])); + let _ = std::fs::remove_dir_all(base); +} + /// Reading and changing the grants file wait for a lock another handle holds only for a bounded /// number of tries: then a listing and a change fail, with the file unchanged. A lock /// released while it waits is taken. diff --git a/docs/mcp.md b/docs/mcp.md index 0b7369d02e..6518d6868e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3132,7 +3132,7 @@ takes its place), and `file` the grants file's path, or `null` without a settings folder. Under automation read roots, a `script`, `path` or `file` outside them is given as its file name alone. `script.grants.revoke {script?, path?, all?}` removes the grants of a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. A path is -matched after its links are followed; under automation read roots, a path outside them is matched as given. While a script +matched as given and after its links are followed; under automation read roots, a path outside them is matched as given only. While a script runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but cannot be read, a link to a missing file included, is left as it is: `script.grants` and `script.grants.revoke` fail, and a grant picked with Always is not kept. A missing grants file lists no grants, and `script.grants` leaves out a grant in the file that is not well From 6ad8c0476a1a7775df23ef61b07f13d1dea5fe9b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:13:55 -0800 Subject: [PATCH 8/9] Scripts: script.grants.revoke removes only the grant named as given script.grants.revoke matched a path both as given and with its links followed, so revoking a grant whose path is now a link to another granted path removed both grants. The spellings are now tried in order, the path as given first, and only the first script and path pair that some grant holds is removed. --- crates/engine/src/cmd/scripts.rs | 6 ++--- crates/engine/src/script/files.rs | 22 +++++++++++++---- crates/engine/src/tests/script_io.rs | 35 ++++++++++++++++++++++++++++ docs/mcp.md | 2 +- 4 files changed, 57 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 14ad0685fd..31a78f0ed3 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -104,7 +104,7 @@ pub fn specs() -> Vec { "Revoke Script File Permissions", [], None, - "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as given and as script.grants lists it, after its links are followed (a path outside the automation read roots is matched as given only); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", + "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as given, as script.grants lists it, or after its links are followed when no grant holds it as given (a path outside the automation read roots is matched as given only); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", always, grants_revoke ), @@ -384,8 +384,8 @@ fn grants(s: &mut Session, _: &Value) -> Result { fn grants_revoke(s: &mut Session, p: &Value) -> Result { const C: &str = "script.grants.revoke"; - // A path is matched as given, and also with its links followed, so a grant whose path a link - // has since taken the place of is still removed. A path the request may not read (outside the + // A path is matched as given, or with its links followed when no grant holds it as given, so a + // grant whose path a link has since taken the place of is still removed. A path the request may not read (outside the // automation read roots, a network path among them) is compared as written, without looking it up. let path_of = |key: &str| match p.get(key) { None => Ok(None), diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index a914f2d474..9d4c90aed4 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1079,15 +1079,29 @@ pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result, path: Option<&[String]>) -> std::io::Result { let store = data_dir.with_file_name(GRANTS_FILE); let _lock = lock_store(&store)?; let grants = try_read_store(&store)?; let before = grants.len(); - let matches = |value: &serde_json::Value, names: Option<&[String]>| names.is_none_or(|names| names.iter().any(|n| value == n.as_str())); - let kept: Vec = grants.into_iter().filter(|g| !(matches(&g["script"], script) && matches(&g["path"], path))).collect(); + // `None` matches any value; `Some(name)` only that name. + fn spellings(names: Option<&[String]>) -> Vec> { + match names { + None => vec![None], + Some(names) => names.iter().map(|n| Some(n.as_str())).collect(), + } + } + let matches = |g: &serde_json::Value, (script, path): (Option<&str>, Option<&str>)| { + script.is_none_or(|s| g["script"] == s) && path.is_none_or(|p| g["path"] == p) + }; + let pairs = spellings(script).into_iter().flat_map(|s| spellings(path).into_iter().map(move |p| (s, p))); + let pair = pairs.into_iter().find(|&pair| grants.iter().any(|g| matches(g, pair))); + let Some(pair) = pair else { return Ok(0) }; + let kept: Vec = grants.into_iter().filter(|g| !matches(g, pair)).collect(); let removed = before - kept.len(); if removed > 0 { write_store(&store, kept)?; diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index d4eed1b4f4..0f05c839c4 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -674,6 +674,41 @@ fn a_grant_whose_path_is_now_a_link_is_revoked_by_its_listed_path() { let _ = std::fs::remove_dir_all(base); } +/// A grant kept for a path that is now a link to another granted path is revoked alone: the grant of +/// the link's target stays. +#[cfg(unix)] +#[test] +fn revoking_a_grant_whose_path_now_links_to_another_grant_keeps_the_other() { + let base = folder("grants-relinked-both"); + let real = std::fs::canonicalize(&base).unwrap(); + let (kept, other) = (real.join("kept.txt"), real.join("other.txt")); + write(&other, b"other"); + let (kept_path, other_path) = (kept.to_string_lossy().into_owned(), other.to_string_lossy().into_owned()); + let grant = |path: &str| json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": path, "write": false, "folder": false}); + let stored = json!({"version": 1, "grants": [grant(&kept_path), grant(&other_path)]}); + write(&base.join("settings/Script Grants.json"), stored.to_string().as_bytes()); + std::os::unix::fs::symlink(&other, &kept).unwrap(); + let mut s = with_data(&base); + let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap(); + assert_eq!(r["removed"], 1, "{r}"); + let left = s.execute("script.grants", &json!({})).unwrap(); + let paths: Vec = left["grants"].as_array().into_iter().flatten().map(|g| g["path"].clone()).collect(); + assert_eq!(paths, [json!(other_path)], "{left}"); + // Another script's grant of the path as given does not keep this script's grant of the link's + // target from being removed. + let stored = json!({"version": 1, "grants": [ + {"script": "/t.jsx", "sha256": "0", "code": [], "path": kept_path, "write": false, "folder": false}, + grant(&other_path) + ]}); + write(&base.join("settings/Script Grants.json"), stored.to_string().as_bytes()); + let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap(); + assert_eq!(r["removed"], 1, "{r}"); + let left = s.execute("script.grants", &json!({})).unwrap(); + let scripts: Vec = left["grants"].as_array().into_iter().flatten().map(|g| g["script"].clone()).collect(); + assert_eq!(scripts, [json!("/t.jsx")], "{left}"); + let _ = std::fs::remove_dir_all(base); +} + /// Reading and changing the grants file wait for a lock another handle holds only for a bounded /// number of tries: then a listing and a change fail, with the file unchanged. A lock /// released while it waits is taken. diff --git a/docs/mcp.md b/docs/mcp.md index 2846f7d7c8..45555fd57f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3161,7 +3161,7 @@ takes its place), and `file` the grants file's path, or `null` without a settings folder. Under automation read roots, a `script`, `path` or `file` outside them is given as its file name alone. `script.grants.revoke {script?, path?, all?}` removes the grants of a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. A path is -matched as given and after its links are followed; under automation read roots, a path outside them is matched as given only. While a script +matched as given, or after its links are followed when no grant holds it as given; under automation read roots, a path outside them is matched as given only. While a script runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but cannot be read, a link to a missing file included, is left as it is: `script.grants` and `script.grants.revoke` fail, and a grant picked with Always is not kept. A missing grants file lists no grants, and `script.grants` leaves out a grant in the file that is not well From 0e2860ea8bdf603a3901d509acf51769ece422d8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:49:00 -0800 Subject: [PATCH 9/9] Preferences: Script File Access lists its rows in a craft scroll stack The list is a Stack with a vertical scroll, and each line is a Lazy child, so only the lines in view run. The row whose Revoke was clicked is returned from the list's body and revoked after the list is shown. --- .../ui-egui/src/prefs_dialog/script_access.rs | 42 ++++++++++--------- crates/ui-egui/src/prefs_dialog/tests.rs | 21 ++++++++++ 2 files changed, 43 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/prefs_dialog/script_access.rs b/crates/ui-egui/src/prefs_dialog/script_access.rs index bdf4b128f5..b0de2cd30d 100644 --- a/crates/ui-egui/src/prefs_dialog/script_access.rs +++ b/crates/ui-egui/src/prefs_dialog/script_access.rs @@ -7,9 +7,9 @@ use std::collections::BTreeMap; use craft::theme::TypeRole; use craft::theme::variant::Tone; use craft::ui::buttons::Button; -use craft::ui::contract::{Props as _, Show as _, ShowContainer as _, Sizing}; +use craft::ui::contract::{Lazy, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; use craft::ui::display::{Elide, Shade, Text}; -use craft::ui::layout_components::Row as Line; +use craft::ui::layout_components::{Row as Line, Stack}; use craft::ui::runtime::focus::FocusRequest; use serde_json::{Map, Value, json}; use vectorcraft_plugins::permissions; @@ -30,10 +30,10 @@ pub(super) const ERROR: &str = "__scriptAccessError"; /// The most characters of a path a row shows. const MAX_SHOWN_PATH: usize = 1024; -/// A line's height in the list. -const LINE_HEIGHT: f32 = 30.0; +/// How tall a line of the list is taken to be before it was first shown. +const LINE_ESTIMATE: f32 = 30.0; -/// The list's height before it scrolls. +/// The height the list offers its lines before it scrolls. const LIST_HEIGHT: f32 = 180.0; /// One script and path with kept access. @@ -193,26 +193,24 @@ pub(super) fn show(app: &mut VectorcraftApp, access: &mut Option, ui: &m lines.push(Entry::Grant(i)); } let focus = state.focus.take(); - let mut revoke_at = None; - // The list is as tall as its lines, up to LIST_HEIGHT, and draws only the lines in view. - let spacing = ui.spacing().item_spacing.y; - let height = ((LINE_HEIGHT + spacing) * lines.len() as f32 - spacing).min(LIST_HEIGHT); - let scroll = egui::ScrollArea::vertical().id_salt("prefs-script-access").max_height(LIST_HEIGHT).min_scrolled_height(height); - scroll.auto_shrink([false, true]).show_rows(ui, LINE_HEIGHT, lines.len(), |ui, range| { - for line in &lines[range] { - let size = egui::vec2(ui.available_width(), LINE_HEIGHT); + // The body returns the row whose Revoke was clicked; the revoke runs after the list is shown. + let list = Stack::new().id_salt("prefs-script-access").label(tl!("Script File Access")).fill_width(); + let shown_list = list.scroll(Scroll::vertical()).room_height(LIST_HEIGHT).show(ui, |ui, _| { + let mut clicked = None; + // Each line runs only while it is in view, so a long list costs no more per frame than a short one. + for line in &lines { match *line { Entry::Script(i) => { let script = &rows[i].shown_script; - ui.allocate_ui(size, |ui| { + Lazy::new(("prefs-script", i), LINE_ESTIMATE).show(ui, |ui| { Text::new(shown(script)).role(TypeRole::BodyStrong).elide(Elide::Path).tooltip(shown_whole(script)).show(ui); }); } Entry::Grant(i) => { let row = &rows[i]; - let (script, path) = (shown_whole(&row.shown_script), shown_whole(&row.shown_path)); - ui.allocate_ui(size, |ui| { - Line::new().show(ui, |ui, _| { + let shown_line = Lazy::new(("prefs-script-row", i), LINE_ESTIMATE).reveal(focus == Some(i)).show(ui, |ui| { + let (script, path) = (shown_whole(&row.shown_script), shown_whole(&row.shown_path)); + let line = Line::new().id_salt(("prefs-script-row", i)).show(ui, |ui, _| { Text::new(shown(&row.shown_path)).elide(Elide::Path).sizing(Sizing::FillWidth).tooltip(path.clone()).show(ui); Text::new(access_label(row.access)).shade(Shade::Muted).show(ui); // A screen reader names the script and the path along with the button. @@ -221,15 +219,19 @@ pub(super) fn show(app: &mut VectorcraftApp, access: &mut Option, ui: &m if focus == Some(i) { button = button.request_focus(FocusRequest::Take); } - if button.show(ui).clicked() { - revoke_at = Some(i); - } + button.show(ui).clicked() }); + line.inner }); + if shown_line.flatten() == Some(true) { + clicked = Some(i); + } } } } + clicked }); + let revoke_at = shown_list.inner.flatten(); Text::new(tl!("Revoke removes the access kept for every version of the script. A folder's access covers everything in it.")) .shade(Shade::Muted) .show(ui); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index c148173378..37772ba113 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -807,6 +807,27 @@ fn script_file_access_lists_each_script_and_path_once_and_revoke_removes_them() let _ = std::fs::remove_dir_all(store.parent().unwrap()); } +/// A long list scrolls and draws only the lines in view: of 200 rows, the first shows and the last +/// does not, and fewer than 200 Revoke buttons are drawn. +#[test] +fn script_file_access_draws_only_the_rows_in_view() { + let dir = std::env::temp_dir().join("vc-ui-prefs-grants-nowhere"); + let script = dir.join("a.jsx"); + let paths: Vec<_> = (0..200).map(|n| dir.join(format!("out{n:03}.txt"))).collect(); + let grants: Vec = paths.iter().map(|p| grant(&script, p, "1", false, false)).collect(); + let (mut a, store) = app_with_grants("grants-many", Value::Array(grants)); + open(&mut a, Some("General")); + assert_eq!(access_rows(&a).len(), 200); + let texts = access_texts(&mut a); + let painted = |label: &str| texts.iter().filter(|(t, _)| t == label).count(); + let (first, last) = (paths[0].to_string_lossy(), paths[199].to_string_lossy()); + assert_eq!(painted(&first), 1, "the first row shows: {texts:?}"); + assert_eq!(painted(&last), 0, "the last row is out of view: {texts:?}"); + let revokes = painted("Revoke"); + assert!(revokes > 0 && revokes < 200, "{revokes} Revoke buttons drawn"); + let _ = std::fs::remove_dir_all(store.parent().unwrap()); +} + /// Revoke on a row whose grants were removed elsewhere removes nothing and says so; with no kept /// grants the section says there are none, and a session without a settings folder (the web among /// them) shows no section.