Cache plugin package hashes, add a content security policy, and limit browser windows
Plugin runtime cost: - Remove the timed plugin scan. Windows scan at start, on focus, on Refresh, and on plugins-changed. - Keep one package check for each plugin folder. Read and hash the files again only when the entry names, sizes, or modification times change. Enable and load always read all files. An asset read checks the SHA-256 hash of its file. - A changed package still stops and needs a new enable decision. Add tests for the cache, for changes that keep the metadata, and for the enable decision. - Replace the 50 ms wait loops of update and removal with a condition variable. The limit stays at 10 seconds. Command names, arguments, and results do not change. Content security policy: - Set app.security.csp in tauri.conf.json. Keep Tauri from adding nonces to style-src. - Add CSP mode to the smoke tests (pnpm smoke --csp). The dev server sends the same policy with each HTML page, and the harness fails a test on a policy violation. - Decode data URLs without fetch in the background frame test. Capabilities: - Give browser windows their own capability. They load no installed plugin. Add a unit test and a browser window smoke test for the command set. Document the scans, the hash cache, the policy, and the window capabilities.
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "browser",
|
||||
"description": "Browser windows. They run only the built-in browser and never load installed plugins.",
|
||||
"windows": [
|
||||
"browser-*"
|
||||
],
|
||||
"permissions": [
|
||||
"allow-browser-request",
|
||||
"allow-browser-connect",
|
||||
"allow-browser-stop",
|
||||
"allow-plugins-snapshot",
|
||||
"allow-settings-read",
|
||||
"allow-settings-write",
|
||||
"allow-settings-migrate",
|
||||
"allow-spelling-menu-install",
|
||||
"allow-spelling-menu-uninstall",
|
||||
"allow-spelling-menu-select",
|
||||
"allow-spelling-suggestions",
|
||||
"core:default",
|
||||
"core:window:allow-destroy",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-toggle-maximize",
|
||||
"core:window:allow-start-dragging"
|
||||
]
|
||||
}
|
||||
@@ -5,8 +5,7 @@
|
||||
"windows": [
|
||||
"main",
|
||||
"workspace-*",
|
||||
"terminal-*",
|
||||
"browser-*"
|
||||
"terminal-*"
|
||||
],
|
||||
"permissions": [
|
||||
"allow-spelling-menu-install",
|
||||
|
||||
+301
-109
@@ -5,7 +5,7 @@ use std::{
|
||||
fs,
|
||||
io::Read,
|
||||
path::{Path, PathBuf},
|
||||
sync::Mutex,
|
||||
sync::{Arc, Condvar, Mutex},
|
||||
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
@@ -19,6 +19,8 @@ use crate::fsutil;
|
||||
const MAX_FILES: usize = 5000;
|
||||
const MAX_FILE: u64 = 25 * 1024 * 1024;
|
||||
const MAX_TOTAL: usize = 100 * 1024 * 1024;
|
||||
/// The longest time that an update or a removal waits for other windows to stop a plugin.
|
||||
const LEASE_WAIT: Duration = Duration::from_secs(10);
|
||||
fn uid() -> String {
|
||||
Uuid::new_v4().to_string()
|
||||
}
|
||||
@@ -115,9 +117,29 @@ struct Package {
|
||||
files: BTreeMap<String, Vec<u8>>,
|
||||
hash: String,
|
||||
}
|
||||
/// The names, sizes, and modification times of the entries in a package folder. It contains no file data.
|
||||
#[derive(PartialEq, Eq)]
|
||||
struct Stamp(Vec<(String, u64, Option<SystemTime>)>);
|
||||
/// The result of a full package read: the manifest, the package hash, and the SHA-256 hash of each file.
|
||||
struct Checked {
|
||||
manifest: Manifest,
|
||||
hash: String,
|
||||
digests: BTreeMap<String, String>,
|
||||
}
|
||||
impl From<&Package> for Checked {
|
||||
fn from(package: &Package) -> Self {
|
||||
Self {
|
||||
manifest: package.manifest.clone(),
|
||||
hash: package.hash.clone(),
|
||||
digests: package.files.iter().map(|(name, bytes)| (name.clone(), digest(bytes))).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
struct Service {
|
||||
root: PathBuf,
|
||||
catalog: Catalog,
|
||||
/// Package checks by folder. An entry is valid while the folder has the same stamp.
|
||||
checked: BTreeMap<PathBuf, (Stamp, Arc<Checked>)>,
|
||||
candidates: BTreeMap<String, Candidate>,
|
||||
plans: BTreeMap<String, Plan>,
|
||||
leases: BTreeMap<String, BTreeSet<String>>,
|
||||
@@ -127,6 +149,8 @@ struct Service {
|
||||
#[derive(Default)]
|
||||
pub struct PluginState {
|
||||
inner: Mutex<Option<Service>>,
|
||||
/// Signals that a window released one or more plugin leases.
|
||||
released: Condvar,
|
||||
}
|
||||
|
||||
fn normal_component(name: &str) -> bool {
|
||||
@@ -233,6 +257,38 @@ fn directory_files(path: &Path) -> Result<BTreeMap<String, Vec<u8>>> {
|
||||
fn tree_hash(path: &Path) -> Result<String> {
|
||||
Ok(fingerprint(&directory_files(path)?))
|
||||
}
|
||||
fn digest(bytes: &[u8]) -> String {
|
||||
format!("{:x}", Sha256::digest(bytes))
|
||||
}
|
||||
/// Read the metadata of every entry in a package folder. Links and junctions are errors, as in `walk`.
|
||||
fn stamp(root: &Path) -> Result<Stamp> {
|
||||
fn visit(
|
||||
root: &Path,
|
||||
directory: &Path,
|
||||
entries: &mut Vec<(String, u64, Option<SystemTime>)>,
|
||||
) -> Result<()> {
|
||||
plain(directory)?;
|
||||
for entry in fs::read_dir(directory)? {
|
||||
let path = entry?.path();
|
||||
if entries.len() >= MAX_FILES {
|
||||
return Err("The package contains too many entries.".into());
|
||||
}
|
||||
let name = path.strip_prefix(root)?.to_string_lossy().replace('\\', "/");
|
||||
let meta = plain(&path)?;
|
||||
if meta.is_dir() {
|
||||
entries.push((name + "/", 0, None));
|
||||
visit(root, &path, entries)?;
|
||||
} else {
|
||||
entries.push((name, meta.len(), meta.modified().ok()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
let mut entries = Vec::new();
|
||||
visit(root, root, &mut entries)?;
|
||||
entries.sort();
|
||||
Ok(Stamp(entries))
|
||||
}
|
||||
fn valid_version(version: &str) -> bool {
|
||||
let parts: Vec<_> = version.split('.').collect();
|
||||
if parts.len() != 3 || parts[..2].iter().any(|part| {
|
||||
@@ -408,6 +464,7 @@ impl Service {
|
||||
let mut service = Self {
|
||||
root,
|
||||
catalog,
|
||||
checked: BTreeMap::new(),
|
||||
candidates: BTreeMap::new(),
|
||||
plans: BTreeMap::new(),
|
||||
leases: BTreeMap::new(),
|
||||
@@ -489,18 +546,58 @@ impl Service {
|
||||
let data = serde_json::to_vec_pretty(&self.catalog)?;
|
||||
Ok(fsutil::replace_file(&path, &temp, &data)?)
|
||||
}
|
||||
fn row(&self, id: &str) -> Result<PluginRow> {
|
||||
let record = self
|
||||
/// Return the package check from the cache while the folder metadata stays the same.
|
||||
/// Otherwise read and hash the package again. Enable and load use `verify`, which always reads the files.
|
||||
fn check(&mut self, path: &Path) -> Result<Arc<Checked>> {
|
||||
let Ok(stamp) = stamp(path) else {
|
||||
self.checked.remove(path);
|
||||
return package(path).map(|current| Arc::new(Checked::from(¤t)));
|
||||
};
|
||||
if let Some((cached, checked)) = self.checked.get(path) {
|
||||
if *cached == stamp {
|
||||
return Ok(checked.clone());
|
||||
}
|
||||
}
|
||||
self.remember(path, stamp, package(path)).map(|(_, checked)| checked)
|
||||
}
|
||||
/// Read and hash the package files, and replace the cached check.
|
||||
fn verify(&mut self, path: &Path) -> Result<Package> {
|
||||
let Ok(stamp) = stamp(path) else {
|
||||
self.checked.remove(path);
|
||||
return package(path);
|
||||
};
|
||||
self.remember(path, stamp, package(path)).map(|(current, _)| current)
|
||||
}
|
||||
/// Keep a successful check with the stamp from before the read. A file that changes during the read changes the next stamp.
|
||||
fn remember(&mut self, path: &Path, stamp: Stamp, current: Result<Package>) -> Result<(Package, Arc<Checked>)> {
|
||||
match current {
|
||||
Ok(current) => {
|
||||
let checked = Arc::new(Checked::from(¤t));
|
||||
self.checked.insert(path.to_owned(), (stamp, checked.clone()));
|
||||
Ok((current, checked))
|
||||
}
|
||||
Err(error) => {
|
||||
self.checked.remove(path);
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
fn row(&mut self, id: &str) -> Result<PluginRow> {
|
||||
let removal = self
|
||||
.catalog
|
||||
.plugins
|
||||
.get(id)
|
||||
.ok_or("The plugin is not installed.")?;
|
||||
let path = self.directory("plugins")?.join(id);
|
||||
let checked = if record.removal.is_some() {
|
||||
.ok_or("The plugin is not installed.")?
|
||||
.removal
|
||||
.is_some();
|
||||
let parent = self.directory("plugins")?;
|
||||
let path = parent.join(id);
|
||||
let checked = if removal {
|
||||
Err("Removal incomplete. Retry file cleanup.".into())
|
||||
} else {
|
||||
safe_child(&self.directory("plugins")?, &path).and_then(|_| package(&path))
|
||||
safe_child(&parent, &path).and_then(|_| self.check(&path))
|
||||
};
|
||||
let record = &self.catalog.plugins[id];
|
||||
let mut manifest = record.manifest.clone();
|
||||
if let Ok(current) = &checked {
|
||||
if current.manifest.id == id {
|
||||
@@ -509,14 +606,14 @@ impl Service {
|
||||
}
|
||||
let (hash, error) = match checked {
|
||||
Ok(current) if current.manifest.id != id => (
|
||||
current.hash,
|
||||
current.hash.clone(),
|
||||
Some("The installed plugin ID changed.".into()),
|
||||
),
|
||||
Ok(current) if current.hash != record.hash => (
|
||||
current.hash,
|
||||
current.hash.clone(),
|
||||
Some("Plugin files changed. Review them before enabling this plugin.".into()),
|
||||
),
|
||||
Ok(current) => (current.hash, self.cleanup_errors.get(id).cloned()),
|
||||
Ok(current) => (current.hash.clone(), self.cleanup_errors.get(id).cloned()),
|
||||
Err(error) => (record.hash.clone(), Some(error.to_string())),
|
||||
};
|
||||
Ok(PluginRow {
|
||||
@@ -542,13 +639,13 @@ impl Service {
|
||||
if !valid_id(&id) || self.catalog.plugins.contains_key(&id) {
|
||||
continue;
|
||||
}
|
||||
if let Ok(current) = safe_child(&directory, &path).and_then(|_| package(&path)) {
|
||||
if let Ok(current) = safe_child(&directory, &path).and_then(|_| self.check(&path)) {
|
||||
if current.manifest.id == id {
|
||||
self.catalog.plugins.insert(
|
||||
id,
|
||||
Installed {
|
||||
manifest: current.manifest,
|
||||
hash: current.hash,
|
||||
manifest: current.manifest.clone(),
|
||||
hash: current.hash.clone(),
|
||||
enabled: false,
|
||||
installed_at: None,
|
||||
removal: None,
|
||||
@@ -559,6 +656,8 @@ impl Service {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Forget the checks of folders that no longer exist.
|
||||
self.checked.retain(|path, _| path.exists());
|
||||
let mut plugins = Vec::new();
|
||||
for id in self.catalog.plugins.keys().cloned().collect::<Vec<_>>() {
|
||||
if !directory.join(&id).exists() && self.catalog.plugins[&id].removal.is_none() {
|
||||
@@ -713,6 +812,7 @@ impl Service {
|
||||
return Err(error);
|
||||
}
|
||||
let candidate = self.candidates.remove(token).unwrap();
|
||||
self.checked.remove(&target);
|
||||
if let Err(error) = fs::rename(&candidate.directory, &target) {
|
||||
self.catalog.plugins.remove(&id);
|
||||
let _ = self.persist();
|
||||
@@ -758,7 +858,7 @@ impl Service {
|
||||
if self.removing.get(&id) != Some(&previous.hash) {
|
||||
return Err("Start the plugin update again.".into());
|
||||
}
|
||||
if self.leases.get(&id).is_some_and(|windows| !windows.is_empty()) || self.cleanup_errors.contains_key(&id) {
|
||||
if self.leased(&id) || self.cleanup_errors.contains_key(&id) {
|
||||
return Err("Plugin cleanup did not finish. Close other RuneStone windows and retry the update.".into());
|
||||
}
|
||||
if candidate.source.as_ref().map(|source| package(source)).transpose()?.is_some_and(|source| source.hash != candidate.hash)
|
||||
@@ -779,6 +879,7 @@ impl Service {
|
||||
backup: backup.file_name().unwrap().to_string_lossy().into_owned(),
|
||||
staged: candidate.directory.file_name().unwrap().to_string_lossy().into_owned() };
|
||||
fs::write(&journal_path, serde_json::to_vec(&journal)?)?;
|
||||
self.checked.remove(&target);
|
||||
fs::rename(&target, &backup)?;
|
||||
if let Err(error) = fs::rename(&candidate.directory, &target) {
|
||||
fs::rename(&backup, &target)?;
|
||||
@@ -857,11 +958,7 @@ impl Service {
|
||||
Ok(plan.id)
|
||||
}
|
||||
fn finish_remove(&mut self, id: &str) -> Result<()> {
|
||||
if self
|
||||
.leases
|
||||
.get(id)
|
||||
.is_some_and(|windows| !windows.is_empty())
|
||||
{
|
||||
if self.leased(id) {
|
||||
return Err("Removal blocked. Close other RuneStone windows and try again.".into());
|
||||
}
|
||||
if let Some(error) = self.cleanup_errors.get(id) {
|
||||
@@ -887,9 +984,10 @@ impl Service {
|
||||
record.removal = Some(token.clone());
|
||||
record.removal_files = current_files
|
||||
.iter()
|
||||
.map(|(name, bytes)| (name.clone(), format!("{:x}", Sha256::digest(bytes))))
|
||||
.map(|(name, bytes)| (name.clone(), digest(bytes)))
|
||||
.collect();
|
||||
self.persist()?;
|
||||
self.checked.remove(&target);
|
||||
let destination = self.directory("plugin-removals")?.join(token);
|
||||
if let Err(error) = fs::rename(&target, &destination) {
|
||||
self.catalog.plugins.get_mut(id).unwrap().removal = None;
|
||||
@@ -920,7 +1018,7 @@ impl Service {
|
||||
safe_child(&parent, &target)?;
|
||||
let expected = &self.catalog.plugins[id].removal_files;
|
||||
for (name, bytes) in directory_files(&target)? {
|
||||
if expected.get(&name) != Some(&format!("{:x}", Sha256::digest(bytes))) {
|
||||
if expected.get(&name) != Some(&digest(&bytes)) {
|
||||
return Err(format!(
|
||||
"Removal files changed. Inspect {} before retrying.",
|
||||
target.display()
|
||||
@@ -938,6 +1036,73 @@ impl Service {
|
||||
}
|
||||
}
|
||||
impl Service {
|
||||
/// Return true when a window holds a lease for the plugin.
|
||||
fn leased(&self, id: &str) -> bool {
|
||||
self.leases.get(id).is_some_and(|windows| !windows.is_empty())
|
||||
}
|
||||
fn set_enabled(&mut self, id: &str, enabled: bool, hash: Option<&str>) -> Result<()> {
|
||||
if self.removing.contains_key(id) {
|
||||
return Err("Wait for plugin removal to finish.".into());
|
||||
}
|
||||
let row = self.row(id)?;
|
||||
if row.removal {
|
||||
return Err("Finish the confirmed removal first.".into());
|
||||
}
|
||||
let old = self.catalog.plugins[id].clone();
|
||||
if enabled {
|
||||
if self.cleanup_errors.contains_key(id) {
|
||||
return Err("Restart RuneStone after the cleanup failure.".into());
|
||||
}
|
||||
// Enable reads every file. The cache alone cannot approve code.
|
||||
let current = self.verify(&self.directory("plugins")?.join(id))?;
|
||||
if current.manifest.id != id || hash != Some(current.hash.as_str()) {
|
||||
return Err("Plugin files changed. Refresh and review them again.".into());
|
||||
}
|
||||
let record = self.catalog.plugins.get_mut(id).unwrap();
|
||||
record.hash = current.hash;
|
||||
record.manifest = current.manifest;
|
||||
}
|
||||
self.catalog.plugins.get_mut(id).unwrap().enabled = enabled;
|
||||
if let Err(error) = self.persist() {
|
||||
self.catalog.plugins.insert(id.into(), old);
|
||||
return Err(error);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Return the entry module and record a lease for the window `owner`. Load reads every file.
|
||||
fn load(&mut self, owner: &str, id: &str, hash: &str) -> Result<String> {
|
||||
let row = self.row(id)?;
|
||||
if !row.enabled || row.hash != hash {
|
||||
return Err("The plugin is disabled or changed.".into());
|
||||
}
|
||||
let mut current = self.verify(&self.directory("plugins")?.join(id))?;
|
||||
if current.hash != hash {
|
||||
return Err("The plugin changed during loading.".into());
|
||||
}
|
||||
self.leases.entry(id.into()).or_default().insert(owner.into());
|
||||
let entry = current.files.remove(¤t.manifest.entry).unwrap_or_default();
|
||||
String::from_utf8(entry).map_err(Error::from)
|
||||
}
|
||||
/// Read one file of an enabled plugin. The file must have the hash from the last full package read.
|
||||
fn asset(&mut self, id: &str, path: &str) -> Result<Vec<u8>> {
|
||||
if !self.row(id)?.enabled {
|
||||
return Err("The plugin is disabled.".into());
|
||||
}
|
||||
let name = relative(path)?;
|
||||
let folder = self.directory("plugins")?.join(id);
|
||||
let current = self.check(&folder)?;
|
||||
if current.hash != self.catalog.plugins[id].hash {
|
||||
return Err("Plugin assets changed. Review the package again.".into());
|
||||
}
|
||||
let expected = current.digests.get(path).ok_or("The plugin asset is missing.")?;
|
||||
let bytes = bounded(&folder.join(name), MAX_FILE)?;
|
||||
if digest(&bytes) != *expected {
|
||||
// The next check reads the package again and reports the change.
|
||||
self.checked.remove(&folder);
|
||||
return Err("Plugin assets changed. Review the package again.".into());
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
/// Accept only a plugin that is enabled and loaded in the window `owner`.
|
||||
fn require_lease(&self, owner: &str, id: &str) -> Result<()> {
|
||||
let record = self.catalog.plugins.get(id);
|
||||
@@ -1010,10 +1175,31 @@ impl PluginState {
|
||||
let app = app.clone();
|
||||
tauri::async_runtime::spawn_blocking(move || app.state::<PluginState>().with(&app, action)).await?
|
||||
}
|
||||
/// Wait until no window holds a lease for `id`, or until `limit` ends. Return true when no lease remains.
|
||||
/// The plugin lock is open while this function waits.
|
||||
fn wait_for_release(&self, id: &str, limit: Duration) -> Result<bool> {
|
||||
let deadline = Instant::now() + limit;
|
||||
let mut guard = self.inner.lock()?;
|
||||
loop {
|
||||
if !guard.as_ref().is_some_and(|service| service.leased(id)) {
|
||||
return Ok(true);
|
||||
}
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() {
|
||||
return Ok(false);
|
||||
}
|
||||
guard = self.released.wait_timeout(guard, left)?.0;
|
||||
}
|
||||
}
|
||||
/// Release the window without waiting. Return `None` when another command holds the plugin lock.
|
||||
pub fn try_release_window(&self, owner: &str) -> Option<StagingCleanup> {
|
||||
match self.inner.try_lock() {
|
||||
Ok(mut guard) => Some(StagingCleanup(guard.as_mut().map(|service| service.release_window(owner)))),
|
||||
Ok(mut guard) => {
|
||||
let cleanup = StagingCleanup(guard.as_mut().map(|service| service.release_window(owner)));
|
||||
drop(guard);
|
||||
self.released.notify_all();
|
||||
Some(cleanup)
|
||||
}
|
||||
Err(std::sync::TryLockError::WouldBlock) => None,
|
||||
Err(std::sync::TryLockError::Poisoned(_)) => Some(StagingCleanup(None)),
|
||||
}
|
||||
@@ -1024,6 +1210,7 @@ impl PluginState {
|
||||
Ok(mut guard) => StagingCleanup(guard.as_mut().map(|service| service.release_window(owner))),
|
||||
Err(_) => return,
|
||||
};
|
||||
self.released.notify_all();
|
||||
cleanup.erase();
|
||||
}
|
||||
}
|
||||
@@ -1143,14 +1330,11 @@ pub async fn plugins_install(
|
||||
Ok(id) => {
|
||||
if let Some(id) = &id {
|
||||
changed(&app);
|
||||
let start = Instant::now();
|
||||
while PluginState::run(&app, {
|
||||
let id = id.clone();
|
||||
move |service| Ok(service.leases.get(&id).is_some_and(|windows| !windows.is_empty()))
|
||||
}).await?
|
||||
&& start.elapsed() < Duration::from_secs(10) {
|
||||
tauri::async_runtime::spawn_blocking(|| std::thread::sleep(Duration::from_millis(50))).await?;
|
||||
}
|
||||
let (wait_app, wait_id) = (app.clone(), id.clone());
|
||||
// `install` checks the leases again and reports a window that did not stop the plugin.
|
||||
let _ = tauri::async_runtime::spawn_blocking(move || {
|
||||
wait_app.state::<PluginState>().wait_for_release(&wait_id, LEASE_WAIT)
|
||||
}).await;
|
||||
}
|
||||
let owner = owner.clone();
|
||||
let installed = PluginState::run(&app, move |service| {
|
||||
@@ -1182,34 +1366,7 @@ pub async fn plugins_set_enabled(
|
||||
hash: Option<String>,
|
||||
) -> Result<()> {
|
||||
let stop_browser = id == "runestone.browser" && !enabled;
|
||||
PluginState::run(&app, move |service| {
|
||||
if service.removing.contains_key(&id) {
|
||||
return Err("Wait for plugin removal to finish.".into());
|
||||
}
|
||||
let row = service.row(&id)?;
|
||||
if row.removal {
|
||||
return Err("Finish the confirmed removal first.".into());
|
||||
}
|
||||
let old = service.catalog.plugins[&id].clone();
|
||||
if enabled {
|
||||
if service.cleanup_errors.contains_key(&id) {
|
||||
return Err("Restart RuneStone after the cleanup failure.".into());
|
||||
}
|
||||
let current = package(&service.directory("plugins")?.join(&id))?;
|
||||
if current.manifest.id != id || hash.as_deref() != Some(¤t.hash) {
|
||||
return Err("Plugin files changed. Refresh and review them again.".into());
|
||||
}
|
||||
let record = service.catalog.plugins.get_mut(&id).unwrap();
|
||||
record.hash = current.hash;
|
||||
record.manifest = current.manifest;
|
||||
}
|
||||
service.catalog.plugins.get_mut(&id).unwrap().enabled = enabled;
|
||||
if let Err(error) = service.persist() {
|
||||
service.catalog.plugins.insert(id, old);
|
||||
return Err(error);
|
||||
}
|
||||
Ok(())
|
||||
}).await?;
|
||||
PluginState::run(&app, move |service| service.set_enabled(&id, enabled, hash.as_deref())).await?;
|
||||
if stop_browser {
|
||||
// Stopping the browser engine waits for its reply.
|
||||
let browser_app = app.clone();
|
||||
@@ -1226,23 +1383,7 @@ pub async fn plugins_load(
|
||||
hash: String,
|
||||
) -> Result<String> {
|
||||
let owner = window.label().to_owned();
|
||||
PluginState::run(&app, move |service| {
|
||||
let row = service.row(&id)?;
|
||||
if !row.enabled || row.hash != hash {
|
||||
return Err("The plugin is disabled or changed.".into());
|
||||
}
|
||||
let current = package(&service.directory("plugins")?.join(&id))?;
|
||||
if current.hash != hash {
|
||||
return Err("The plugin changed during loading.".into());
|
||||
}
|
||||
service
|
||||
.leases
|
||||
.entry(id)
|
||||
.or_default()
|
||||
.insert(owner);
|
||||
String::from_utf8(current.files[¤t.manifest.entry].clone()).map_err(Error::from)
|
||||
})
|
||||
.await
|
||||
PluginState::run(&app, move |service| service.load(&owner, &id, &hash)).await
|
||||
}
|
||||
#[tauri::command]
|
||||
pub async fn plugins_release(
|
||||
@@ -1252,7 +1393,7 @@ pub async fn plugins_release(
|
||||
error: Option<String>,
|
||||
) -> Result<()> {
|
||||
let owner = window.label().to_owned();
|
||||
PluginState::run(&app, move |service| {
|
||||
let result = PluginState::run(&app, move |service| {
|
||||
if let Some(error) = error {
|
||||
service.cleanup_errors.insert(id.clone(), error);
|
||||
}
|
||||
@@ -1261,7 +1402,9 @@ pub async fn plugins_release(
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.await;
|
||||
app.state::<PluginState>().released.notify_all();
|
||||
result
|
||||
}
|
||||
#[tauri::command]
|
||||
pub async fn plugins_prepare_remove(
|
||||
@@ -1279,23 +1422,10 @@ pub async fn plugins_remove(app: AppHandle, window: tauri::Window, token: String
|
||||
changed(&app);
|
||||
let worker_app = app.clone();
|
||||
let result = tauri::async_runtime::spawn_blocking(move || {
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
let leased = worker_app
|
||||
.state::<PluginState>()
|
||||
.with(&worker_app, |service| {
|
||||
Ok(service
|
||||
.leases
|
||||
.get(&id)
|
||||
.is_some_and(|windows| !windows.is_empty()))
|
||||
})?;
|
||||
if !leased || start.elapsed() > Duration::from_secs(10) {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
worker_app
|
||||
.state::<PluginState>()
|
||||
let state = worker_app.state::<PluginState>();
|
||||
// `finish_remove` checks the leases again and reports a window that did not stop the plugin.
|
||||
let _ = state.wait_for_release(&id, LEASE_WAIT);
|
||||
state
|
||||
.with(&worker_app, |service| {
|
||||
let result = service.finish_remove(&id);
|
||||
service.removing.remove(&id);
|
||||
@@ -1392,19 +1522,7 @@ pub async fn plugins_asset(
|
||||
) -> Result<String> {
|
||||
use base64::Engine;
|
||||
PluginState::run(&app, move |service| {
|
||||
if !service.row(&id)?.enabled {
|
||||
return Err("The plugin is disabled.".into());
|
||||
}
|
||||
relative(&path)?;
|
||||
let current = package(&service.directory("plugins")?.join(&id))?;
|
||||
if current.hash != service.catalog.plugins[&id].hash {
|
||||
return Err("Plugin assets changed. Review the package again.".into());
|
||||
}
|
||||
let bytes = current
|
||||
.files
|
||||
.get(&path)
|
||||
.ok_or("The plugin asset is missing.")?;
|
||||
Ok(base64::engine::general_purpose::STANDARD.encode(bytes))
|
||||
Ok(base64::engine::general_purpose::STANDARD.encode(service.asset(&id, &path)?))
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -1645,7 +1763,7 @@ mod tests {
|
||||
record.enabled = true;
|
||||
f.service.persist().unwrap();
|
||||
}
|
||||
let recovered = Service::open(f.root.join("app")).unwrap();
|
||||
let mut recovered = Service::open(f.root.join("app")).unwrap();
|
||||
let row = recovered.row(&id).unwrap();
|
||||
assert!(row.error.is_none());
|
||||
assert_eq!(row.manifest.version, if phase == 3 { "1.0.1" } else { "1.0.0" });
|
||||
@@ -1976,7 +2094,7 @@ mod tests {
|
||||
record.enabled = false;
|
||||
record.removal = Some(uid());
|
||||
f.service.persist().unwrap();
|
||||
let recovered = Service::open(f.service.root.clone()).unwrap();
|
||||
let mut recovered = Service::open(f.service.root.clone()).unwrap();
|
||||
assert!(recovered.catalog.plugins[&id].removal.is_none());
|
||||
assert!(!recovered.row(&id).unwrap().enabled);
|
||||
}
|
||||
@@ -2013,4 +2131,78 @@ mod tests {
|
||||
assert!(Service::open(f.service.root.clone()).is_err());
|
||||
assert!(safe_child(&f.service.directory("plugins").unwrap(), &f.source).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn package_checks_are_cached_until_file_metadata_changes() {
|
||||
let mut f = Fixture::new();
|
||||
let id = f.install(true);
|
||||
let folder = f.service.directory("plugins").unwrap().join(&id);
|
||||
let first = f.service.check(&folder).unwrap();
|
||||
f.service.snapshot().unwrap();
|
||||
assert!(Arc::ptr_eq(&first, &f.service.check(&folder).unwrap()), "A scan without file changes reuses the hash.");
|
||||
fs::create_dir(folder.join("empty")).unwrap();
|
||||
assert!(!Arc::ptr_eq(&first, &f.service.check(&folder).unwrap()), "A new entry starts a new read.");
|
||||
fs::write(folder.join("main.js"), "export function activate() { /* edited */ }").unwrap();
|
||||
let row = f.service.row(&id).unwrap();
|
||||
assert_eq!(row.error.as_deref(), Some("Plugin files changed. Review them before enabling this plugin."));
|
||||
assert!(!row.enabled);
|
||||
}
|
||||
#[test]
|
||||
fn changed_packages_stop_and_need_a_new_enable_decision() {
|
||||
let mut f = Fixture::new();
|
||||
let id = f.install(true);
|
||||
let reviewed = f.service.row(&id).unwrap().hash;
|
||||
let entry = f.service.directory("plugins").unwrap().join(&id).join("main.js");
|
||||
assert_eq!(f.service.load("main", &id, &reviewed).unwrap(), "export function activate() {}");
|
||||
assert_eq!(f.service.asset(&id, "main.js").unwrap(), b"export function activate() {}");
|
||||
assert!(f.service.asset(&id, "missing.js").unwrap_err().to_string().contains("missing"));
|
||||
f.service.leases.clear();
|
||||
// The same size and modification time hide the edit from the cache, but not from a file read.
|
||||
let modified = fs::metadata(&entry).unwrap().modified().unwrap();
|
||||
fs::write(&entry, "export function activatE() {}").unwrap();
|
||||
fs::File::options().write(true).open(&entry).unwrap().set_modified(modified).unwrap();
|
||||
assert!(f.service.row(&id).unwrap().enabled);
|
||||
assert!(f.service.asset(&id, "main.js").unwrap_err().to_string().contains("changed"));
|
||||
assert!(f.service.load("main", &id, &reviewed).is_err());
|
||||
assert!(!f.service.leased(&id));
|
||||
let row = f.service.row(&id).unwrap();
|
||||
assert!(row.error.is_some() && !row.enabled);
|
||||
// A scan stops the plugin in every window: the snapshot reports it as disabled and saves that state.
|
||||
let snapshot = f.service.snapshot().unwrap();
|
||||
assert!(!snapshot.plugins[0].enabled);
|
||||
assert!(!Service::open(f.root.join("app")).unwrap().catalog.plugins[&id].enabled);
|
||||
// Enable needs the hash that the user saw for the current files.
|
||||
assert!(f.service.set_enabled(&id, true, Some(&reviewed)).is_err());
|
||||
assert!(f.service.set_enabled(&id, true, None).is_err());
|
||||
f.service.set_enabled(&id, true, Some(&row.hash)).unwrap();
|
||||
assert!(f.service.row(&id).unwrap().enabled);
|
||||
assert_eq!(f.service.load("main", &id, &row.hash).unwrap(), "export function activatE() {}");
|
||||
}
|
||||
#[test]
|
||||
fn lease_wait_ends_when_the_last_window_releases_its_lease() {
|
||||
let mut f = Fixture::new();
|
||||
let id = f.install(true);
|
||||
f.service.leases.entry(id.clone()).or_default().extend(["main".to_owned(), "other".to_owned()]);
|
||||
let reopened = Service::open(f.root.join("app")).unwrap();
|
||||
let state = Arc::new(PluginState::default());
|
||||
*state.inner.lock().unwrap() = Some(std::mem::replace(&mut f.service, reopened));
|
||||
let start = Instant::now();
|
||||
assert!(!state.wait_for_release(&id, Duration::from_millis(100)).unwrap());
|
||||
assert!(start.elapsed() >= Duration::from_millis(100));
|
||||
let waiter = {
|
||||
let (state, id) = (state.clone(), id.clone());
|
||||
std::thread::spawn(move || {
|
||||
let start = Instant::now();
|
||||
(state.wait_for_release(&id, LEASE_WAIT).unwrap(), start.elapsed())
|
||||
})
|
||||
};
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
state.close_window("main");
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
assert!(!waiter.is_finished(), "One window still holds a lease.");
|
||||
state.close_window("other");
|
||||
let (released, elapsed) = waiter.join().unwrap();
|
||||
assert!(released);
|
||||
assert!(elapsed < Duration::from_secs(5), "The wait ends without the full time limit.");
|
||||
assert!(state.wait_for_release("org.test.missing", LEASE_WAIT).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,20 @@
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null
|
||||
"csp": {
|
||||
"default-src": "'self'",
|
||||
"script-src": "'self' blob: 'wasm-unsafe-eval'",
|
||||
"style-src": "'self' 'unsafe-inline'",
|
||||
"img-src": "'self' data: blob: https: http:",
|
||||
"font-src": "'self' data:",
|
||||
"connect-src": "'self' ipc: http://ipc.localhost blob:",
|
||||
"worker-src": "'self' blob:",
|
||||
"object-src": "'none'",
|
||||
"base-uri": "'self'",
|
||||
"form-action": "'none'",
|
||||
"frame-ancestors": "'none'"
|
||||
},
|
||||
"dangerousDisableAssetCspModification": ["style-src"]
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
|
||||
Reference in New Issue
Block a user