Add a shared error type and shared file helpers to the Rust host

Replace the three error styles with one Error type and one Result alias in
error.rs. The error crosses IPC as the same plain string as before. The
message text does not change.

Move the shared file mechanics to fsutil.rs. These are the reserved-name
check, the link and junction check, the limited reads, and the atomic
writes. Each module keeps its own path rules, limits, and messages. The
plugin settings writer now flushes its file to disk before the rename.

Remove the current_root_path and list_entries wrappers and an unused mime
value. Use named windows-sys constants for the process, file, drive, and
error codes.

Add a test that compares the command lists in lib.rs, build.rs, and the
capability files. The settings capability must be a subset of the full list.

In Cargo.toml, set the author, keep only the rlib crate type, and remove
the unused thiserror dependency. Remove panic = "abort" from the release
profile. A panic on a worker thread then stops only that thread. It does
not stop the editor with unsaved buffers.
This commit is contained in:
Knotty Wyvern
2026-10-27 22:41:11 -07:00
parent 69f90df571
commit bd46f3a189
18 changed files with 1103 additions and 882 deletions
+87 -150
View File
@@ -13,13 +13,12 @@ use tauri_plugin_dialog::DialogExt;
use tauri_plugin_opener::OpenerExt;
use uuid::Uuid;
type Result<T> = std::result::Result<T, String>;
use crate::error::{Error, Result};
use crate::fsutil;
const MAX_FILES: usize = 5000;
const MAX_FILE: u64 = 25 * 1024 * 1024;
const MAX_TOTAL: usize = 100 * 1024 * 1024;
fn fail(error: impl std::fmt::Display) -> String {
error.to_string()
}
fn uid() -> String {
Uuid::new_v4().to_string()
}
@@ -131,41 +130,11 @@ pub struct PluginState {
}
fn normal_component(name: &str) -> bool {
if name.is_empty() || name == "." || name == ".." || name.ends_with('.') || name.len() > 120 {
return false;
}
if !name
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c))
{
return false;
}
let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase();
!matches!(
stem.as_str(),
"CON"
| "PRN"
| "AUX"
| "NUL"
| "COM1"
| "COM2"
| "COM3"
| "COM4"
| "COM5"
| "COM6"
| "COM7"
| "COM8"
| "COM9"
| "LPT1"
| "LPT2"
| "LPT3"
| "LPT4"
| "LPT5"
| "LPT6"
| "LPT7"
| "LPT8"
| "LPT9"
)
fsutil::is_plain_component(name)
&& name.len() <= 120
&& name
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c))
}
fn valid_id(id: &str) -> bool {
normal_component(id)
@@ -176,18 +145,14 @@ fn valid_id(id: &str) -> bool {
}
fn relative(name: &str) -> Result<PathBuf> {
if name.len() > 180 || !name.split('/').all(normal_component) {
return Err(format!("Invalid package path: {name}"));
return Err(format!("Invalid package path: {name}").into());
}
Ok(name.split('/').collect())
}
fn plain(path: &Path) -> Result<fs::Metadata> {
let meta = fs::symlink_metadata(path).map_err(fail)?;
#[cfg(windows)]
{
use std::os::windows::fs::MetadataExt;
if meta.file_attributes() & 0x400 != 0 {
return Err("Links and junctions are not allowed in plugin paths.".into());
}
let meta = fs::symlink_metadata(path)?;
if fsutil::is_reparse_point(&meta) {
return Err("Links and junctions are not allowed in plugin paths.".into());
}
if meta.file_type().is_symlink() {
return Err("Links are not allowed in plugin paths.".into());
@@ -199,16 +164,8 @@ fn bounded(path: &Path, limit: u64) -> Result<Vec<u8>> {
if !meta.is_file() || meta.len() > limit {
return Err("The package contains an invalid or oversized file.".into());
}
let mut data = Vec::new();
fs::File::open(path)
.map_err(fail)?
.take(limit + 1)
.read_to_end(&mut data)
.map_err(fail)?;
if data.len() as u64 > limit {
return Err("The file exceeds the size limit.".into());
}
Ok(data)
fsutil::read_to_limit(fs::File::open(path)?, limit)?
.ok_or_else(|| "The file exceeds the size limit.".into())
}
fn add_file(
files: &mut BTreeMap<String, Vec<u8>>,
@@ -237,15 +194,14 @@ fn walk(
count: &mut usize,
) -> Result<()> {
plain(directory)?;
for entry in fs::read_dir(directory).map_err(fail)? {
let path = entry.map_err(fail)?.path();
for entry in fs::read_dir(directory)? {
let path = entry?.path();
*count += 1;
if *count > MAX_FILES {
return Err("The package contains too many entries.".into());
}
let name = path
.strip_prefix(root)
.map_err(fail)?
.strip_prefix(root)?
.to_str()
.ok_or("The package path is not UTF-8.")?
.replace('\\', "/");
@@ -300,15 +256,14 @@ fn package(source: &Path) -> Result<Package> {
return Err("The archive exceeds 100 MiB.".into());
}
let mut archive =
zip::ZipArchive::new(fs::File::open(source).map_err(fail)?).map_err(fail)?;
zip::ZipArchive::new(fs::File::open(source)?)?;
if archive.len() > MAX_FILES {
return Err("The archive contains too many entries.".into());
}
let mut archive_names = BTreeSet::new();
for index in 0..archive.len() {
let mut file = archive.by_index(index).map_err(fail)?;
let name = std::str::from_utf8(file.name_raw())
.map_err(fail)?
let mut file = archive.by_index(index)?;
let name = std::str::from_utf8(file.name_raw())?
.trim_end_matches('/')
.to_string();
relative(&name)?;
@@ -326,11 +281,8 @@ fn package(source: &Path) -> Result<Package> {
if file.size() > MAX_FILE {
return Err("An archive file exceeds 25 MiB.".into());
}
let mut bytes = Vec::new();
file.by_ref()
.take(MAX_FILE + 1)
.read_to_end(&mut bytes)
.map_err(fail)?;
let bytes = fsutil::read_to_limit(file.by_ref(), MAX_FILE)?
.ok_or("The package exceeds the file count or size limit.")?;
add_file(&mut files, &mut names, &mut total, name, bytes)?;
}
}
@@ -340,7 +292,7 @@ fn package(source: &Path) -> Result<Package> {
if bytes.len() > 64 * 1024 {
return Err("The manifest exceeds 64 KiB.".into());
}
let manifest: Manifest = serde_json::from_slice(bytes).map_err(fail)?;
let manifest: Manifest = serde_json::from_slice(bytes)?;
if !valid_id(&manifest.id) {
return Err("The plugin ID is invalid.".into());
}
@@ -369,8 +321,7 @@ fn package(source: &Path) -> Result<Package> {
files
.get(&manifest.entry)
.ok_or("The entry module is missing.")?,
)
.map_err(fail)?;
)?;
let hash = fingerprint(&files);
Ok(Package {
manifest,
@@ -394,8 +345,8 @@ fn require_zip(source: &Path) -> Result<()> {
fn safe_child(parent: &Path, child: &Path) -> Result<()> {
plain(parent)?;
plain(child)?;
let parent = dunce::canonicalize(parent).map_err(fail)?;
let resolved = dunce::canonicalize(child).map_err(fail)?;
let parent = dunce::canonicalize(parent)?;
let resolved = dunce::canonicalize(child)?;
if resolved.parent() != Some(parent.as_path()) {
return Err("The plugin path is outside its managed directory.".into());
}
@@ -405,27 +356,26 @@ fn erase(parent: &Path, target: &Path) -> Result<()> {
safe_child(parent, target)?;
fn descend(path: &Path, boundary: &Path) -> Result<()> {
let meta = plain(path)?;
if !dunce::canonicalize(path)
.map_err(fail)?
if !dunce::canonicalize(path)?
.starts_with(boundary)
{
return Err("Removal escaped its managed directory.".into());
}
if meta.is_dir() {
for item in fs::read_dir(path).map_err(fail)? {
descend(&item.map_err(fail)?.path(), boundary)?;
for item in fs::read_dir(path)? {
descend(&item?.path(), boundary)?;
}
fs::remove_dir(path).map_err(fail)
fs::remove_dir(path).map_err(Error::from)
} else {
fs::remove_file(path).map_err(fail)
fs::remove_file(path).map_err(Error::from)
}
}
let boundary = dunce::canonicalize(target).map_err(fail)?;
let boundary = dunce::canonicalize(target)?;
descend(target, &boundary)
}
impl Service {
fn open(root: PathBuf) -> Result<Self> {
fs::create_dir_all(&root).map_err(fail)?;
fs::create_dir_all(&root)?;
plain(&root)?;
for name in [
"plugins",
@@ -437,13 +387,13 @@ impl Service {
if path.exists() {
plain(&path)?;
} else {
fs::create_dir(&path).map_err(fail)?;
fs::create_dir(&path)?;
}
safe_child(&root, &path)?;
}
let state = root.join("plugin-state.json");
let catalog: Catalog = if state.exists() {
serde_json::from_slice(&bounded(&state, 4 * 1024 * 1024)?).map_err(fail)?
serde_json::from_slice(&bounded(&state, 4 * 1024 * 1024)?)?
} else {
Catalog::default()
};
@@ -452,7 +402,7 @@ impl Service {
return Err("The plugin catalog contains an invalid ID.".into());
}
if let Some(token) = &record.removal {
Uuid::parse_str(token).map_err(fail)?;
Uuid::parse_str(token)?;
}
}
let mut service = Self {
@@ -485,15 +435,15 @@ impl Service {
}
fn recover_updates(&mut self) -> Result<()> {
let staging = self.directory("plugin-staging")?;
for entry in fs::read_dir(&staging).map_err(fail)? {
let entry = entry.map_err(fail)?;
for entry in fs::read_dir(&staging)? {
let entry = entry?;
let name = entry.file_name().to_string_lossy().into_owned();
if !name.starts_with("update-") || !name.ends_with(".json") { continue; }
let journal: UpdateJournal = serde_json::from_slice(&bounded(&entry.path(), 128 * 1024)?).map_err(fail)?;
let journal: UpdateJournal = serde_json::from_slice(&bounded(&entry.path(), 128 * 1024)?)?;
let id = journal.previous.manifest.id.clone();
if !valid_id(&id) { return Err("Invalid plugin update journal.".into()); }
Uuid::parse_str(&journal.backup).map_err(fail)?;
Uuid::parse_str(&journal.staged).map_err(fail)?;
Uuid::parse_str(&journal.backup)?;
Uuid::parse_str(&journal.staged)?;
let target = self.directory("plugins")?.join(&id);
let backup = staging.join(&journal.backup);
let staged = staging.join(&journal.staged);
@@ -509,9 +459,9 @@ impl Service {
if package(&target)?.hash != journal.next_hash || staged.exists() {
return Err("Plugin update recovery requires inspection of the staging directory.".into());
}
fs::rename(&target, &staged).map_err(fail)?;
fs::rename(&target, &staged)?;
}
fs::rename(&backup, &target).map_err(fail)?;
fs::rename(&backup, &target)?;
}
}
if !committed {
@@ -536,17 +486,8 @@ impl Service {
plain(&path)?;
}
let temp = self.root.join(format!("plugin-state-{}.tmp", uid()));
let data = serde_json::to_vec_pretty(&self.catalog).map_err(fail)?;
use std::io::Write;
let mut file = fs::OpenOptions::new()
.create_new(true)
.write(true)
.open(&temp)
.map_err(fail)?;
file.write_all(&data).map_err(fail)?;
file.sync_all().map_err(fail)?;
drop(file);
fs::rename(&temp, path).map_err(fail)
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
@@ -576,7 +517,7 @@ impl Service {
Some("Plugin files changed. Review them before enabling this plugin.".into()),
),
Ok(current) => (current.hash, self.cleanup_errors.get(id).cloned()),
Err(error) => (record.hash.clone(), Some(error)),
Err(error) => (record.hash.clone(), Some(error.to_string())),
};
Ok(PluginRow {
manifest,
@@ -591,8 +532,8 @@ impl Service {
fn snapshot(&mut self) -> Result<Snapshot> {
let mut changed = false;
let directory = self.directory("plugins")?;
for entry in fs::read_dir(&directory).map_err(fail)? {
let path = entry.map_err(fail)?.path();
for entry in fs::read_dir(&directory)? {
let path = entry?.path();
let id = path
.file_name()
.unwrap_or_default()
@@ -643,7 +584,7 @@ impl Service {
fn inspect(&mut self, owner: &str, source: PathBuf) -> CandidateRow {
let token = uid();
let display = source.to_string_lossy().into_owned();
let result = (|| {
let result = (|| -> Result<Manifest> {
let current = package(&source)?;
let previous = self.catalog.plugins.get(&current.manifest.id).cloned();
if let Some(record) = &previous {
@@ -655,7 +596,7 @@ impl Service {
return Err("Refresh the plugin list before installing this package.".into());
}
let staging = self.directory("plugin-staging")?.join(&token);
fs::create_dir(&staging).map_err(fail)?;
fs::create_dir(&staging)?;
for (name, bytes) in &current.files {
let target = staging.join(relative(name)?);
if self
@@ -669,8 +610,8 @@ impl Service {
{
return Err("The installed path would exceed 240 characters.".into());
}
fs::create_dir_all(target.parent().unwrap()).map_err(fail)?;
fs::write(target, bytes).map_err(fail)?;
fs::create_dir_all(target.parent().unwrap())?;
fs::write(target, bytes)?;
}
let manifest = current.manifest.clone();
self.candidates.insert(
@@ -705,7 +646,7 @@ impl Service {
token,
source: display,
manifest: None,
error: Some(error),
error: Some(error.to_string()),
}
}
}
@@ -713,7 +654,7 @@ impl Service {
fn inspect_download(&mut self, owner: &str, download: crate::plugin_sources::Download) -> Result<CandidateRow> {
let parent = self.directory("plugin-staging")?;
let archive = parent.join(format!("{}.zip", uid()));
fs::write(&archive, download.bytes).map_err(fail)?;
fs::write(&archive, download.bytes)?;
let mut row = self.inspect(owner, archive.clone());
if let Some(candidate) = self.candidates.get_mut(&row.token) {
// Review pins the downloaded bytes. Remote releases can change independently.
@@ -753,8 +694,7 @@ impl Service {
}
safe_child(&self.directory("plugin-staging")?, &candidate.directory)?;
let installed_at = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(fail)?
.duration_since(UNIX_EPOCH)?
.as_millis() as u64;
// Persist disabled first. A crash cannot enable unreviewed or partial code.
self.catalog.plugins.insert(
@@ -776,13 +716,13 @@ impl Service {
if let Err(error) = fs::rename(&candidate.directory, &target) {
self.catalog.plugins.remove(&id);
let _ = self.persist();
return Err(fail(error));
return Err(Error::from(error));
}
if enabled {
self.catalog.plugins.get_mut(&id).unwrap().enabled = true;
if let Err(error) = self.persist() {
self.catalog.plugins.get_mut(&id).unwrap().enabled = false;
return Err(format!("Installed but disabled: {error}"));
return Err(format!("Installed but disabled: {error}").into());
}
}
Ok(candidate.manifest.name)
@@ -838,21 +778,21 @@ impl Service {
let journal = UpdateJournal { previous: previous.clone(), next_hash: candidate.hash.clone(),
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).map_err(fail)?).map_err(fail)?;
fs::rename(&target, &backup).map_err(fail)?;
fs::write(&journal_path, serde_json::to_vec(&journal)?)?;
fs::rename(&target, &backup)?;
if let Err(error) = fs::rename(&candidate.directory, &target) {
fs::rename(&backup, &target).map_err(fail)?;
fs::rename(&backup, &target)?;
let _ = erase(&staging, &journal_path);
return Err(fail(error));
return Err(Error::from(error));
}
self.catalog.plugins.insert(id.clone(), Installed {
manifest: candidate.manifest.clone(), hash: candidate.hash.clone(), enabled: previous.enabled,
installed_at: Some(SystemTime::now().duration_since(UNIX_EPOCH).map_err(fail)?.as_millis() as u64),
installed_at: Some(SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() as u64),
removal: None, removal_files: BTreeMap::new(),
});
if let Err(error) = self.persist() {
fs::rename(&target, &candidate.directory).map_err(fail)?;
fs::rename(&backup, &target).map_err(fail)?;
fs::rename(&target, &candidate.directory)?;
fs::rename(&backup, &target)?;
self.catalog.plugins.insert(id, previous);
let _ = erase(&staging, &journal_path);
return Err(error);
@@ -927,7 +867,7 @@ impl Service {
if let Some(error) = self.cleanup_errors.get(id) {
return Err(format!(
"Cleanup failed. Restart RuneStone before removal. {error}"
));
).into());
}
let parent = self.directory("plugins")?;
let target = parent.join(id);
@@ -954,7 +894,7 @@ impl Service {
if let Err(error) = fs::rename(&target, &destination) {
self.catalog.plugins.get_mut(id).unwrap().removal = None;
let _ = self.persist();
return Err(fail(error));
return Err(Error::from(error));
}
if tree_hash(&destination)? != current_hash {
return Err("Plugin files changed during removal. Inspect the removal directory before retrying.".into());
@@ -968,7 +908,7 @@ impl Service {
.get(id)
.and_then(|record| record.removal.clone())
.ok_or("No confirmed removal exists.")?;
Uuid::parse_str(&token).map_err(fail)?;
Uuid::parse_str(&token)?;
let parent = self.directory("plugin-removals")?;
let target = parent.join(&token);
if self.directory("plugins")?.join(id).exists() {
@@ -984,7 +924,7 @@ impl Service {
return Err(format!(
"Removal files changed. Inspect {} before retrying.",
target.display()
));
).into());
}
}
erase(&parent, &target)?;
@@ -1010,9 +950,9 @@ impl PluginState {
app: &AppHandle,
action: impl FnOnce(&mut Service) -> Result<T>,
) -> Result<T> {
let mut guard = self.inner.lock().map_err(fail)?;
let mut guard = self.inner.lock()?;
if guard.is_none() {
*guard = Some(Service::open(app.path().app_data_dir().map_err(fail)?)?);
*guard = Some(Service::open(app.path().app_data_dir()?)?);
}
action(guard.as_mut().unwrap())
}
@@ -1060,8 +1000,7 @@ pub async fn plugins_choose(app: AppHandle, window: tauri::Window) -> Result<Vec
.add_filter("Plugin ZIP archives", &["zip"])
.blocking_pick_files()
})
.await
.map_err(fail)?;
.await?;
let Some(sources) = source else {
return Ok(Vec::new());
};
@@ -1070,7 +1009,7 @@ pub async fn plugins_choose(app: AppHandle, window: tauri::Window) -> Result<Vec
}
let paths: Vec<PathBuf> = sources
.into_iter()
.map(|source| source.into_path().map_err(fail))
.map(|source| source.into_path().map_err(Error::from_display))
.collect::<Result<_>>()?;
for path in &paths {
require_zip(path)?;
@@ -1094,7 +1033,7 @@ pub async fn plugins_from_git(
// Network access never holds the plugin service lock.
let download = tauri::async_runtime::spawn_blocking(move || {
crate::plugin_sources::download(&repository, token.as_deref())
}).await.map_err(fail)??;
}).await??;
app.state::<PluginState>().with(&app, |service| {
Ok(vec![service.inspect_download(window.label(), download)?])
})
@@ -1149,7 +1088,7 @@ pub async fn plugins_install(
let start = Instant::now();
while state.with(&app, |service| Ok(service.leases.get(id).is_some_and(|windows| !windows.is_empty())))?
&& start.elapsed() < Duration::from_secs(10) {
tauri::async_runtime::spawn_blocking(|| std::thread::sleep(Duration::from_millis(50))).await.map_err(fail)?;
tauri::async_runtime::spawn_blocking(|| std::thread::sleep(Duration::from_millis(50))).await?;
}
}
let installed = state.with(&app, |service| {
@@ -1168,7 +1107,7 @@ pub async fn plugins_install(
installed.err()
}
};
result.push(InstallResult { name, error });
result.push(InstallResult { name, error: error.map(String::from) });
}
changed(&app);
Ok(result)
@@ -1236,7 +1175,7 @@ pub async fn plugins_load(
.entry(id)
.or_default()
.insert(window.label().into());
String::from_utf8(current.files[&current.manifest.entry].clone()).map_err(fail)
String::from_utf8(current.files[&current.manifest.entry].clone()).map_err(Error::from)
})
}
#[tauri::command]
@@ -1297,8 +1236,7 @@ pub async fn plugins_remove(app: AppHandle, window: tauri::Window, token: String
result
})
})
.await
.map_err(fail)?;
.await?;
changed(&app);
result
}
@@ -1335,9 +1273,9 @@ pub async fn plugins_reveal(
if open_directory {
app.opener()
.open_path(path.to_string_lossy().into_owned(), None::<&str>)
.map_err(fail)
.map_err(Error::from)
} else {
app.opener().reveal_item_in_dir(path).map_err(fail)
app.opener().reveal_item_in_dir(path).map_err(Error::from)
}
}
#[tauri::command]
@@ -1355,7 +1293,7 @@ pub async fn plugins_data(
let parent = service.directory("plugin-data")?;
let dir = parent.join(&id);
if !dir.exists() {
fs::create_dir(&dir).map_err(fail)?;
fs::create_dir(&dir)?;
}
safe_child(&parent, &dir)?;
let path = dir.join("settings.json");
@@ -1363,16 +1301,15 @@ pub async fn plugins_data(
if value.len() > 1024 * 1024 {
return Err("Plugin settings exceed 1 MiB.".into());
}
serde_json::from_str::<serde_json::Value>(&value).map_err(fail)?;
serde_json::from_str::<serde_json::Value>(&value)?;
if path.exists() {
plain(&path)?;
}
let temp = dir.join(format!("{}.tmp", uid()));
fs::write(&temp, value).map_err(fail)?;
fs::rename(temp, &path).map_err(fail)?;
fsutil::replace_file(&path, &temp, value.as_bytes())?;
}
if path.exists() {
String::from_utf8(bounded(&path, 1024 * 1024)?).map_err(fail)
String::from_utf8(bounded(&path, 1024 * 1024)?).map_err(Error::from)
} else {
Ok("null".into())
}
@@ -1611,10 +1548,10 @@ mod tests {
let candidate = f.service.inspect("main", f.source.clone());
f.service.leases.entry(id.clone()).or_default().insert("main".into());
f.service.begin_update("main", &candidate.token).unwrap();
assert!(f.service.install("main", &candidate.token, true).unwrap_err().contains("cleanup"));
assert!(f.service.install("main", &candidate.token, true).unwrap_err().to_string().contains("cleanup"));
f.service.leases.clear();
fs::write(f.source.join("main.js"), "changed after review").unwrap();
assert!(f.service.install("main", &candidate.token, true).unwrap_err().contains("changed after review"));
assert!(f.service.install("main", &candidate.token, true).unwrap_err().to_string().contains("changed after review"));
assert_eq!(f.service.row(&id).unwrap().manifest.version, "1.0.0");
assert_eq!(fs::read_to_string(f.service.directory("plugins").unwrap().join(&id).join("main.js")).unwrap(), "export function activate() {}");
}
@@ -1684,7 +1621,7 @@ mod tests {
assert!(require_zip(&upper).is_ok());
let wrapped = f.root.join("wrapped.zip");
archive(&wrapped, &[("demo/plugin.json", b"{}")]);
assert!(package(&wrapped).unwrap_err().contains("at its root"));
assert!(package(&wrapped).unwrap_err().to_string().contains("at its root"));
}
#[test]
fn author_packager_produces_an_installable_repeatable_zip() {
@@ -1829,7 +1766,7 @@ mod tests {
assert!(package(&path).is_err());
assert!(!f.root.join("outside").exists());
archive(&path, &[("main.js", b"a"), ("MAIN.js", b"b")]);
assert!(package(&path).unwrap_err().contains("duplicate"));
assert!(package(&path).unwrap_err().to_string().contains("duplicate"));
let manifest = fs::read_to_string(f.source.join("plugin.json"))
.unwrap()
.replace("\"apiVersion\":1", "\"apiVersion\":99");