Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

fix: diagnose and quarantine non-UTF8 patch layers (#1127)

Hairy3c3a28aa86a2
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 89d441e2..44f95222 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -104,11 +104,11 @@ tokio = { version = "1", features = [ "full" ] }
semver = "1"
dunce = "1.0.5"
sysinfo = { version = "0.39.6", default-features = false, features = [ "system" ] }
+tempfile = "3"
[dev-dependencies]
auto-launch = "0.5"
tauri = { version = "2", features = [ "test" ] }
-tempfile = "3"
# 选择数据存放目录(issue #871):Windows 走原生 IFileDialog、macOS 走 NSOpenPanel、
# Linux 走 xdg-desktop-portal(无 portal 时 rfd 自己回退到 zenity)。
@@ -184,6 +184,7 @@ windows-sys = { version = "0.61", features = [
"Win32_Foundation",
"Win32_Globalization",
"Win32_Security",
+ "Win32_Security_Authorization",
"Win32_Storage_FileSystem",
"Win32_System_Com",
"Win32_System_Diagnostics_ToolHelp",
diff --git a/src-tauri/src/service/plugin/atomic_write.rs b/src-tauri/src/service/plugin/atomic_write.rs
new file mode 100644
index 00000000..f44adab7
--- /dev/null
+++ b/src-tauri/src/service/plugin/atomic_write.rs
@@ -0,0 +1,662 @@
+use std::fs::File;
+use std::io::{self, Write};
+use std::path::Path;
+
+pub(super) fn write_patch_layer_atomically(path: &Path, rendered: &str) -> io::Result<()> {
+ match std::fs::symlink_metadata(path) {
+ Ok(metadata) if metadata.file_type().is_symlink() => {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "refusing to replace a symlink patch layer",
+ ));
+ }
+ Ok(_) => {}
+ Err(error) if error.kind() == io::ErrorKind::NotFound => {}
+ Err(error) => return Err(error),
+ }
+ let original = match File::options().read(true).write(true).open(path) {
+ Ok(file) => Some(file),
+ Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+ Err(error) => return Err(error),
+ };
+ let parent = path
+ .parent()
+ .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "patch layer has no parent"))?;
+ let mut temp = create_temp(parent, original.as_ref().map(|_| path))?;
+ #[cfg(unix)]
+ if let Some(original) = &original {
+ preserve_permissions(original, temp.as_file())?;
+ }
+ temp.write_all(rendered.as_bytes())?;
+ temp.as_file().sync_all()?;
+ if original.is_none() {
+ temp.persist_noclobber(path).map_err(|error| error.error)?;
+ return Ok(());
+ }
+ #[cfg(not(windows))]
+ temp.persist(path).map_err(|error| error.error)?;
+ #[cfg(windows)]
+ {
+ use std::os::windows::ffi::OsStrExt;
+ use windows_sys::Win32::Storage::FileSystem::ReplaceFileW;
+
+ let (file, temp) = temp.into_parts();
+ drop(file);
+ let wide = |path: &Path| {
+ path.as_os_str()
+ .encode_wide()
+ .chain(Some(0))
+ .collect::<Vec<u16>>()
+ };
+ let target = wide(path);
+ let source = wide(&temp);
+ if unsafe {
+ ReplaceFileW(
+ target.as_ptr(),
+ source.as_ptr(),
+ std::ptr::null(),
+ 0,
+ std::ptr::null(),
+ std::ptr::null(),
+ )
+ } == 0
+ {
+ return Err(io::Error::last_os_error());
+ }
+ }
+ Ok(())
+}
+
+fn create_temp(parent: &Path, original: Option<&Path>) -> io::Result<tempfile::NamedTempFile> {
+ #[cfg(target_os = "macos")]
+ reject_inheritable_parent_acl(parent)?;
+ let mut builder = tempfile::Builder::new();
+ builder.prefix(".cordis.patch-");
+ #[cfg(windows)]
+ if let Some(original) = original {
+ use std::os::windows::ffi::OsStrExt;
+ use std::os::windows::io::FromRawHandle;
+ use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
+ use windows_sys::Win32::Security::{
+ SetSecurityDescriptorControl, SECURITY_ATTRIBUTES, SE_DACL_PROTECTED,
+ };
+ use windows_sys::Win32::Storage::FileSystem::{
+ CreateFileW, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, FILE_GENERIC_READ, FILE_GENERIC_WRITE,
+ FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
+ };
+
+ let mut descriptor = security_descriptor(original)?;
+ if unsafe {
+ SetSecurityDescriptorControl(
+ descriptor.as_mut_ptr().cast(),
+ SE_DACL_PROTECTED,
+ SE_DACL_PROTECTED,
+ )
+ } == 0
+ {
+ return Err(io::Error::last_os_error());
+ }
+ let security = SECURITY_ATTRIBUTES {
+ nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
+ lpSecurityDescriptor: descriptor.as_mut_ptr().cast(),
+ bInheritHandle: 0,
+ };
+ return builder.make_in(parent, |path| {
+ let path: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
+ let handle = unsafe {
+ CreateFileW(
+ path.as_ptr(),
+ FILE_GENERIC_READ | FILE_GENERIC_WRITE,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ &security,
+ CREATE_NEW,
+ FILE_ATTRIBUTE_NORMAL,
+ std::ptr::null_mut(),
+ )
+ };
+ if handle == INVALID_HANDLE_VALUE {
+ return Err(io::Error::last_os_error());
+ }
+ Ok(unsafe { File::from_raw_handle(handle) })
+ });
+ }
+ #[cfg(not(windows))]
+ let _ = original;
+ builder.tempfile_in(parent)
+}
+
+#[cfg(target_os = "macos")]
+fn reject_inheritable_parent_acl(parent: &Path) -> io::Result<()> {
+ use std::os::fd::AsRawFd;
+
+ const ACL_TYPE_EXTENDED: libc::c_int = 0x100;
+ const ACL_FIRST_ENTRY: libc::c_int = 0;
+ const ACL_NEXT_ENTRY: libc::c_int = 1;
+ const ACL_ENTRY_FILE_INHERIT: libc::c_int = 1 << 5;
+
+ unsafe extern "C" {
+ fn acl_get_fd_np(fd: libc::c_int, kind: libc::c_int) -> *mut libc::c_void;
+ fn acl_get_entry(
+ acl: *mut libc::c_void,
+ entry_id: libc::c_int,
+ entry: *mut *mut libc::c_void,
+ ) -> libc::c_int;
+ fn acl_get_flagset_np(
+ entry: *mut libc::c_void,
+ flagset: *mut *mut libc::c_void,
+ ) -> libc::c_int;
+ fn acl_get_flag_np(flagset: *mut libc::c_void, flag: libc::c_int) -> libc::c_int;
+ fn acl_free(acl: *mut libc::c_void) -> libc::c_int;
+ }
+ let parent = File::open(parent)?;
+ let acl = unsafe { acl_get_fd_np(parent.as_raw_fd(), ACL_TYPE_EXTENDED) };
+ if acl.is_null() {
+ let error = io::Error::last_os_error();
+ return match error.raw_os_error() {
+ Some(libc::ENOENT) | Some(libc::ENOTSUP) | Some(libc::EOPNOTSUPP) => Ok(()),
+ _ => Err(error),
+ };
+ }
+ let mut entry_id = ACL_FIRST_ENTRY;
+ loop {
+ let mut entry = std::ptr::null_mut();
+ if unsafe { acl_get_entry(acl, entry_id, &mut entry) } != 0 {
+ let error = io::Error::last_os_error();
+ unsafe { acl_free(acl) };
+ return if error.raw_os_error() == Some(libc::EINVAL) {
+ Ok(())
+ } else {
+ Err(error)
+ };
+ }
+ let mut flagset = std::ptr::null_mut();
+ if unsafe { acl_get_flagset_np(entry, &mut flagset) } != 0 {
+ let error = io::Error::last_os_error();
+ unsafe { acl_free(acl) };
+ return Err(error);
+ }
+ let inheritable = unsafe { acl_get_flag_np(flagset, ACL_ENTRY_FILE_INHERIT) };
+ if inheritable < 0 {
+ let error = io::Error::last_os_error();
+ unsafe { acl_free(acl) };
+ return Err(error);
+ }
+ if inheritable > 0 {
+ unsafe { acl_free(acl) };
+ return Err(io::Error::new(
+ io::ErrorKind::PermissionDenied,
+ "refusing to stage a patch in a directory with an inheritable extended ACL",
+ ));
+ }
+ entry_id = ACL_NEXT_ENTRY;
+ }
+}
+
+#[cfg(windows)]
+fn security_descriptor(path: &Path) -> io::Result<Vec<u32>> {
+ use std::os::windows::ffi::OsStrExt;
+ use windows_sys::Win32::Security::{
+ GetFileSecurityW, DACL_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION,
+ };
+
+ let path: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
+ let info = DACL_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION;
+ let mut needed = 0;
+ unsafe { GetFileSecurityW(path.as_ptr(), info, std::ptr::null_mut(), 0, &mut needed) };
+ if needed == 0 {
+ return Err(io::Error::last_os_error());
+ }
+ let mut descriptor = vec![0u32; (needed as usize).div_ceil(4)];
+ if unsafe {
+ GetFileSecurityW(
+ path.as_ptr(),
+ info,
+ descriptor.as_mut_ptr().cast(),
+ needed,
+ &mut needed,
+ )
+ } == 0
+ {
+ return Err(io::Error::last_os_error());
+ }
+ Ok(descriptor)
+}
+
+#[cfg(unix)]
+fn preserve_permissions(original: &File, replacement: &File) -> io::Result<()> {
+ use std::os::fd::AsRawFd;
+ use std::os::unix::fs::MetadataExt;
+
+ let before = original.metadata()?;
+ let after = replacement.metadata()?;
+ if (before.uid(), before.gid()) != (after.uid(), after.gid())
+ && unsafe { libc::fchown(replacement.as_raw_fd(), before.uid(), before.gid()) } != 0
+ {
+ return Err(io::Error::last_os_error());
+ }
+ #[cfg(target_os = "linux")]
+ {
+ let acl = read_acl(original)?;
+ let result = match &acl {
+ Some(bytes) => unsafe {
+ libc::fsetxattr(
+ replacement.as_raw_fd(),
+ c"system.posix_acl_access".as_ptr(),
+ bytes.as_ptr().cast(),
+ bytes.len(),
+ 0,
+ )
+ },
+ None => unsafe {
+ libc::fremovexattr(replacement.as_raw_fd(), c"system.posix_acl_access".as_ptr())
+ },
+ };
+ if result < 0 {
+ let error = io::Error::last_os_error();
+ if acl.is_some()
+ || !matches!(
+ error.raw_os_error(),
+ Some(libc::ENODATA) | Some(libc::ENOTSUP)
+ )
+ {
+ return Err(error);
+ }
+ }
+ replacement.set_permissions(before.permissions())?;
+ if read_acl(replacement)? != acl {
+ return Err(io::Error::new(
+ io::ErrorKind::PermissionDenied,
+ "patch ACL could not be preserved",
+ ));
+ }
+ }
+ #[cfg(target_os = "macos")]
+ if unsafe {
+ libc::fcopyfile(
+ original.as_raw_fd(),
+ replacement.as_raw_fd(),
+ std::ptr::null_mut(),
+ libc::COPYFILE_SECURITY,
+ )
+ } != 0
+ {
+ return Err(io::Error::last_os_error());
+ }
+ let after = replacement.metadata()?;
+ if (before.uid(), before.gid(), before.mode()) != (after.uid(), after.gid(), after.mode()) {
+ return Err(io::Error::new(
+ io::ErrorKind::PermissionDenied,
+ "patch ownership or mode could not be preserved",
+ ));
+ }
+ Ok(())
+}
+
+#[cfg(target_os = "linux")]
+fn read_acl(file: &File) -> io::Result<Option<Vec<u8>>> {
+ use std::os::fd::AsRawFd;
+
+ let size = unsafe {
+ libc::fgetxattr(
+ file.as_raw_fd(),
+ c"system.posix_acl_access".as_ptr(),
+ std::ptr::null_mut(),
+ 0,
+ )
+ };
+ if size < 0 {
+ let error = io::Error::last_os_error();
+ return match error.raw_os_error() {
+ Some(libc::ENODATA) | Some(libc::ENOTSUP) => Ok(None),
+ _ => Err(error),
+ };
+ }
+ let mut bytes = vec![0u8; size as usize];
+ let size = unsafe {
+ libc::fgetxattr(
+ file.as_raw_fd(),
+ c"system.posix_acl_access".as_ptr(),
+ bytes.as_mut_ptr().cast(),
+ bytes.len(),
+ )
+ };
+ if size < 0 {
+ return Err(io::Error::last_os_error());
+ }
+ bytes.truncate(size as usize);
+ Ok(Some(bytes))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ const ORIGINAL: &str = "- id: plugin\n";
+
+ #[test]
+ fn replaces_complete_utf8_content_without_leaking_temp_files() {
+ let temp = tempfile::tempdir().unwrap();
+ let path = temp.path().join("cordis.patch.yml");
+ write_patch_layer_atomically(&path, ORIGINAL).unwrap();
+ write_patch_layer_atomically(&path, "- id: 中文插件\n").unwrap();
+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "- id: 中文插件\n");
+ assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 1);
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn readonly_or_locked_files_are_not_modified_and_temps_are_cleaned() {
+ use std::os::windows::fs::OpenOptionsExt;
+ let temp = tempfile::tempdir().unwrap();
+ let path = temp.path().join("cordis.patch.yml");
+ std::fs::write(&path, ORIGINAL).unwrap();
+ let mut permissions = path.metadata().unwrap().permissions();
+ permissions.set_readonly(true);
+ std::fs::set_permissions(&path, permissions).unwrap();
+ assert_eq!(
+ write_patch_layer_atomically(&path, "[]\n")
+ .unwrap_err()
+ .kind(),
+ io::ErrorKind::PermissionDenied
+ );
+ assert_eq!(std::fs::read_to_string(&path).unwrap(), ORIGINAL);
+ let mut permissions = path.metadata().unwrap().permissions();
+ permissions.set_readonly(false);
+ std::fs::set_permissions(&path, permissions).unwrap();
+ let lock = File::options()
+ .read(true)
+ .share_mode(1 | 2)
+ .open(&path)
+ .unwrap();
+ assert!(write_patch_layer_atomically(&path, "[]\n").is_err());
+ assert_eq!(std::fs::read_to_string(&path).unwrap(), ORIGINAL);
+ assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 1);
+ drop(lock);
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn restricted_dacl_is_applied_at_temp_creation_and_preserved_on_replacement() {
+ use std::os::windows::ffi::OsStrExt;
+ use windows_sys::Win32::Security::Authorization::{
+ ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,
+ };
+ use windows_sys::Win32::Security::{
+ GetSecurityDescriptorControl, GetSecurityDescriptorDacl, SetFileSecurityW,
+ DACL_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION, SE_DACL_PROTECTED,
+ };
+
+ fn dacl(path: &Path) -> Vec<u8> {
+ let mut descriptor = security_descriptor(path).unwrap();
+ let mut present = 0;
+ let mut defaulted = 0;
+ let mut acl = std::ptr::null_mut();
+ let mut control = 0;
+ let mut revision = 0;
+ assert_ne!(
+ unsafe {
+ GetSecurityDescriptorControl(
+ descriptor.as_mut_ptr().cast(),
+ &mut control,
+ &mut revision,
+ )
+ },
+ 0
+ );
+ assert_ne!(control & SE_DACL_PROTECTED, 0);
+ assert_ne!(
+ unsafe {
+ GetSecurityDescriptorDacl(
+ descriptor.as_mut_ptr().cast(),
+ &mut present,
+ &mut acl,
+ &mut defaulted,
+ )
+ },
+ 0
+ );
+ assert_ne!(present, 0);
+ assert!(!acl.is_null());
+ unsafe { std::slice::from_raw_parts(acl.cast::<u8>(), (*acl).AclSize as usize) }
+ .to_vec()
+ }
+
+ let temp = tempfile::tempdir().unwrap();
+ let path = temp.path().join("cordis.patch.yml");
+ std::fs::write(&path, ORIGINAL).unwrap();
+ let sddl: Vec<u16> = "D:P(A;;FA;;;OW)".encode_utf16().chain(Some(0)).collect();
+ let mut descriptor = std::ptr::null_mut();
+ assert_ne!(
+ unsafe {
+ ConvertStringSecurityDescriptorToSecurityDescriptorW(
+ sddl.as_ptr(),
+ SDDL_REVISION_1,
+ &mut descriptor,
+ std::ptr::null_mut(),
+ )
+ },
+ 0
+ );
+ let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
+ let result = unsafe {
+ SetFileSecurityW(
+ wide.as_ptr(),
+ DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
+ descriptor,
+ )
+ };
+ unsafe { windows_sys::Win32::Foundation::LocalFree(descriptor) };
+ assert_ne!(result, 0);
+ let before = dacl(&path);
+ let staging = create_temp(temp.path(), Some(&path)).unwrap();
+ assert_eq!(dacl(staging.path()), before);
+ assert_eq!(std::fs::read(staging.path()).unwrap(), b"");
+ drop(staging);
+ write_patch_layer_atomically(&path, "- id: token\n").unwrap();
+ assert_eq!(dacl(&path), before);
+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "- id: token\n");
+ assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 1);
+ }
+
+ #[cfg(target_os = "macos")]
+ fn set_everyone_acl(parent: &Path, file_inherit: bool) {
+ use std::os::fd::AsRawFd;
+
+ const ACL_TYPE_EXTENDED: libc::c_int = 0x100;
+ const ACL_FIRST_ENTRY: libc::c_int = 0;
+ const ACL_EXTENDED_ALLOW: libc::c_int = 1;
+ const ACL_READ_DATA: libc::c_int = 1 << 1;
+ const ACL_ENTRY_FILE_INHERIT: libc::c_int = 1 << 5;
+ const EVERYONE_GUID: [u8; 16] = [
+ 0xab, 0xcd, 0xef, 0xab, 0xcd, 0xef, 0xab, 0xcd, 0xef, 0xab, 0xcd, 0xef, 0x00, 0x00,
+ 0x00, 0x0c,
+ ];
+
+ unsafe extern "C" {
+ fn acl_init(count: libc::c_int) -> *mut libc::c_void;
+ fn acl_create_entry(
+ acl: *mut *mut libc::c_void,
+ entry: *mut *mut libc::c_void,
+ ) -> libc::c_int;
+ fn acl_set_tag_type(entry: *mut libc::c_void, tag: libc::c_int) -> libc::c_int;
+ fn acl_set_qualifier(
+ entry: *mut libc::c_void,
+ qualifier: *const libc::c_void,
+ ) -> libc::c_int;
+ fn acl_get_permset(
+ entry: *mut libc::c_void,
+ permset: *mut *mut libc::c_void,
+ ) -> libc::c_int;
+ fn acl_add_perm(permset: *mut libc::c_void, perm: libc::c_int) -> libc::c_int;
+ fn acl_set_permset(entry: *mut libc::c_void, permset: *mut libc::c_void)
+ -> libc::c_int;
+ fn acl_get_flagset_np(
+ entry: *mut libc::c_void,
+ flagset: *mut *mut libc::c_void,
+ ) -> libc::c_int;
+ fn acl_add_flag_np(flagset: *mut libc::c_void, flag: libc::c_int) -> libc::c_int;
+ fn acl_set_flagset_np(
+ entry: *mut libc::c_void,
+ flagset: *mut libc::c_void,
+ ) -> libc::c_int;
+ fn acl_get_flag_np(flagset: *mut libc::c_void, flag: libc::c_int) -> libc::c_int;
+ fn acl_set_fd_np(
+ fd: libc::c_int,
+ acl: *mut libc::c_void,
+ kind: libc::c_int,
+ ) -> libc::c_int;
+ fn acl_get_fd_np(fd: libc::c_int, kind: libc::c_int) -> *mut libc::c_void;
+ fn acl_get_entry(
+ acl: *mut libc::c_void,
+ entry_id: libc::c_int,
+ entry: *mut *mut libc::c_void,
+ ) -> libc::c_int;
+ fn acl_free(obj: *mut libc::c_void) -> libc::c_int;
+ }
+
+ let parent = File::open(parent).unwrap();
+ unsafe {
+ let mut acl = acl_init(1);
+ assert!(!acl.is_null());
+ let mut entry = std::ptr::null_mut();
+ assert_eq!(acl_create_entry(&mut acl, &mut entry), 0);
+ assert_eq!(acl_set_tag_type(entry, ACL_EXTENDED_ALLOW), 0);
+ assert_eq!(
+ acl_set_qualifier(entry, EVERYONE_GUID.as_ptr().cast::<libc::c_void>()),
+ 0
+ );
+ let mut permset = std::ptr::null_mut();
+ assert_eq!(acl_get_permset(entry, &mut permset), 0);
+ assert_eq!(acl_add_perm(permset, ACL_READ_DATA), 0);
+ assert_eq!(acl_set_permset(entry, permset), 0);
+ let mut flagset = std::ptr::null_mut();
+ assert_eq!(acl_get_flagset_np(entry, &mut flagset), 0);
+ if file_inherit {
+ assert_eq!(acl_add_flag_np(flagset, ACL_ENTRY_FILE_INHERIT), 0);
+ }
+ assert_eq!(acl_set_flagset_np(entry, flagset), 0);
+ assert_eq!(acl_set_fd_np(parent.as_raw_fd(), acl, ACL_TYPE_EXTENDED), 0);
+ acl_free(acl);
+
+ let applied = acl_get_fd_np(parent.as_raw_fd(), ACL_TYPE_EXTENDED);
+ assert!(!applied.is_null());
+ let mut applied_entry = std::ptr::null_mut();
+ assert_eq!(
+ acl_get_entry(applied, ACL_FIRST_ENTRY, &mut applied_entry),
+ 0
+ );
+ let mut applied_flags = std::ptr::null_mut();
+ assert_eq!(acl_get_flagset_np(applied_entry, &mut applied_flags), 0);
+ assert_eq!(
+ acl_get_flag_np(applied_flags, ACL_ENTRY_FILE_INHERIT),
+ i32::from(file_inherit)
+ );
+ acl_free(applied);
+ }
+ }
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn macos_rejects_inherited_acl_before_creating_a_temp_and_keeps_original() {
+ let temp = tempfile::tempdir().unwrap();
+ let path = temp.path().join("cordis.patch.yml");
+ std::fs::write(&path, ORIGINAL).unwrap();
+ write_patch_layer_atomically(&path, "[]\n").unwrap();
+ set_everyone_acl(temp.path(), true);
+ let error = write_patch_layer_atomically(&path, "- id: secret\n").unwrap_err();
+ assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
+ assert!(error.to_string().contains("extended ACL"));
+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "[]\n");
+ assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 1);
+ }
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn macos_allows_parent_acl_without_inheritable_entries() {
+ let temp = tempfile::tempdir().unwrap();
+ let path = temp.path().join("cordis.patch.yml");
+ std::fs::write(&path, ORIGINAL).unwrap();
+ set_everyone_acl(temp.path(), false);
+ write_patch_layer_atomically(&path, "- id: token\n").unwrap();
+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "- id: token\n");
+ assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 1);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn unix_identity_and_mode_are_preserved() {
+ use std::os::unix::fs::{MetadataExt, PermissionsExt};
+ let temp = tempfile::tempdir().unwrap();
+ let path = temp.path().join("cordis.patch.yml");
+ std::fs::write(&path, ORIGINAL).unwrap();
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640)).unwrap();
+ let before = path.metadata().unwrap();
+ write_patch_layer_atomically(&path, "[]\n").unwrap();
+ let after = path.metadata().unwrap();
+ assert_eq!(
+ (after.uid(), after.gid(), after.mode()),
+ (before.uid(), before.gid(), before.mode())
+ );
+ assert_ne!(after.ino(), before.ino());
+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "[]\n");
+ }
+
+ #[cfg(target_os = "linux")]
+ #[test]
+ fn linux_access_acl_is_preserved_and_parent_default_acl_is_not_inherited() {
+ use std::os::fd::AsRawFd;
+ fn acl() -> Vec<u8> {
+ let mut bytes = 2u32.to_le_bytes().to_vec();
+ for (tag, permission, id) in [
+ (1u16, 6u16, u32::MAX),
+ (2, 4, 65534),
+ (4, 0, u32::MAX),
+ (16, 4, u32::MAX),
+ (32, 0, u32::MAX),
+ ] {
+ bytes.extend(tag.to_le_bytes());
+ bytes.extend(permission.to_le_bytes());
+ bytes.extend(id.to_le_bytes());
+ }
+ bytes
+ }
+ let temp = tempfile::tempdir().unwrap();
+ let path = temp.path().join("cordis.patch.yml");
+ let plain = temp.path().join("plain.patch.yml");
+ std::fs::write(&path, ORIGINAL).unwrap();
+ std::fs::write(&plain, ORIGINAL).unwrap();
+ let original = File::open(&path).unwrap();
+ let acl = acl();
+ assert_eq!(
+ unsafe {
+ libc::fsetxattr(
+ original.as_raw_fd(),
+ c"system.posix_acl_access".as_ptr(),
+ acl.as_ptr().cast(),
+ acl.len(),
+ 0,
+ )
+ },
+ 0
+ );
+ let parent = File::open(temp.path()).unwrap();
+ assert_eq!(
+ unsafe {
+ libc::fsetxattr(
+ parent.as_raw_fd(),
+ c"system.posix_acl_default".as_ptr(),
+ acl.as_ptr().cast(),
+ acl.len(),
+ 0,
+ )
+ },
+ 0
+ );
+ let before = read_acl(&original).unwrap();
+ assert_eq!(before, Some(acl));
+ assert_eq!(read_acl(&File::open(&plain).unwrap()).unwrap(), None);
+ write_patch_layer_atomically(&path, "[]\n").unwrap();
+ write_patch_layer_atomically(&plain, "[]\n").unwrap();
+ assert_eq!(read_acl(&File::open(path).unwrap()).unwrap(), before);
+ assert_eq!(read_acl(&File::open(plain).unwrap()).unwrap(), None);
+ }
+}
diff --git a/src-tauri/src/service/plugin/disable.rs b/src-tauri/src/service/plugin/disable.rs
index 3ae078f4..cb370083 100644
--- a/src-tauri/src/service/plugin/disable.rs
+++ b/src-tauri/src/service/plugin/disable.rs
@@ -154,7 +154,8 @@ pub(crate) fn add_patch_disable(profile: &Path, id: &str) -> Result<bool, String
}
let rendered = serde_yaml::to_string(&serde_yaml::Value::Sequence(entries))
.map_err(|e| format!("DISABLE_PATCH_RENDER_FAILED: {e}"))?;
- fs::write(&path, rendered).map_err(|e| format!("DISABLE_PATCH_WRITE_FAILED: {e}"))?;
+ super::atomic_write::write_patch_layer_atomically(&path, &rendered)
+ .map_err(|e| format!("DISABLE_PATCH_WRITE_FAILED: {e}"))?;
log::info!("Disabled plugin {id} via cordis.patch.yml override");
Ok(true)
}
@@ -198,7 +199,8 @@ pub(crate) fn strip_patch_disable(profile: &Path, id: &str) -> Result<bool, Stri
}
let rendered = serde_yaml::to_string(&serde_yaml::Value::Sequence(kept))
.map_err(|e| format!("ENABLE_PATCH_RENDER_FAILED: {e}"))?;
- fs::write(&path, rendered).map_err(|e| format!("ENABLE_PATCH_WRITE_FAILED: {e}"))?;
+ super::atomic_write::write_patch_layer_atomically(&path, &rendered)
+ .map_err(|e| format!("ENABLE_PATCH_WRITE_FAILED: {e}"))?;
log::info!("Stripped cordis.patch.yml disable override for plugin {id}");
Ok(true)
}
diff --git a/src-tauri/src/service/plugin/internal/mod.rs b/src-tauri/src/service/plugin/internal/mod.rs
index a281fc39..e247f97f 100644
--- a/src-tauri/src/service/plugin/internal/mod.rs
+++ b/src-tauri/src/service/plugin/internal/mod.rs
@@ -241,10 +241,12 @@ fn repair_loader_state(
Ok(raw) => raw,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
Err(error) => {
- return Err(format!(
- "INTERNAL_PLUGIN_PATCH_READ_FAILED: {}: {error}",
- patch_path.display()
- ))
+ let code = if error.kind() == std::io::ErrorKind::InvalidData {
+ super::patch_guard::PATCH_ENCODING_FAILED
+ } else {
+ "INTERNAL_PLUGIN_PATCH_READ_FAILED"
+ };
+ return Err(format!("{code}: {}: {error}", patch_path.display()));
}
};
let mut patch = serde_yaml::from_str::<serde_yaml::Value>(&raw).map_err(|e| {
@@ -260,12 +262,14 @@ fn repair_loader_state(
}
let rendered = serde_yaml::to_string(&patch)
.map_err(|e| format!("INTERNAL_PLUGIN_PATCH_RENDER_FAILED: {e}"))?;
- std::fs::write(&patch_path, rendered).map_err(|e| {
- format!(
- "INTERNAL_PLUGIN_PATCH_WRITE_FAILED: {}: {e}",
- patch_path.display()
- )
- })?;
+ super::atomic_write::write_patch_layer_atomically(&patch_path, &rendered).map_err(
+ |e| {
+ format!(
+ "INTERNAL_PLUGIN_PATCH_WRITE_FAILED: {}: {e}",
+ patch_path.display()
+ )
+ },
+ )?;
log::warn!(
"INTERNAL_PLUGIN_PROFILE_MIGRATED: removed stale internal loader entries from {}",
patch_path.display()
@@ -1332,6 +1336,65 @@ mod tests {
use super::*;
+ #[test]
+ fn loader_rejects_non_utf8_layers_without_rewriting_and_recovers_after_quarantine() {
+ for bytes in [
+ b"\xff\xfe[\0]\0\n\0".as_slice(),
+ b"- id: plugin\n name: \xc4\xe3\xba\xc3\n".as_slice(),
+ ] {
+ for home_layer in [false, true] {
+ let temp = tempfile::tempdir().unwrap();
+ let home = temp.path();
+ let profile = home.join("profiles/tauri");
+ std::fs::create_dir_all(&profile).unwrap();
+ let path = if home_layer { home } else { &profile }.join("cordis.patch.yml");
+ std::fs::write(&path, bytes).unwrap();
+
+ for prepare in [false, true] {
+ let error =
+ repair_loader_state(&profile, home, &[], &mut None, prepare).unwrap_err();
+ assert!(
+ error.starts_with("INTERNAL_PLUGIN_PATCH_ENCODING_FAILED: "),
+ "{error}"
+ );
+ assert!(error.contains(&path.display().to_string()), "{error}");
+ assert!(error.contains("UTF-8"), "{error}");
+ assert_eq!(std::fs::read(&path).unwrap(), bytes);
+ }
+
+ let recovery_profile = if home_layer {
+ let safe = home.join("profiles/safe");
+ std::fs::create_dir_all(&safe).unwrap();
+ safe
+ } else {
+ profile
+ };
+ let report =
+ super::super::patch_guard::quarantine_patch_layers_in(&recovery_profile, home);
+ assert!(!report.has_failures(), "{report:?}");
+ assert_eq!(report.quarantined.len(), 1);
+ assert_eq!(std::fs::read(&report.quarantined[0].backup).unwrap(), bytes);
+ assert_eq!(
+ repair_loader_state(&recovery_profile, home, &[], &mut None, true),
+ Ok(false)
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn loader_keeps_io_errors_distinct_from_encoding_errors() {
+ let temp = tempfile::tempdir().unwrap();
+ let profile = temp.path().join("profiles/tauri");
+ std::fs::create_dir_all(profile.join("cordis.patch.yml")).unwrap();
+ let error = repair_loader_state(&profile, temp.path(), &[], &mut None, true).unwrap_err();
+ assert!(
+ error.starts_with("INTERNAL_PLUGIN_PATCH_READ_FAILED: "),
+ "{error}"
+ );
+ assert!(profile.join("cordis.patch.yml").is_dir());
+ }
+
#[test]
fn early_prepare_uses_normal_kernel_and_defers_repairs_without_installing() {
let root = tempfile::tempdir().unwrap();
diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rs
index 5200568b..72c15a95 100644
--- a/src-tauri/src/service/plugin/mod.rs
+++ b/src-tauri/src/service/plugin/mod.rs
@@ -34,6 +34,7 @@
//! - [`hmr`]:本地路径插件的热重载(把已挂载的本地插件源码目录写进桌面端独占的
//! 补丁层,随启动以 `--patch` 注入核心 HMR,源码改动即时生效)
+mod atomic_write;
mod cancel;
pub mod compat;
pub mod disable;
diff --git a/src-tauri/src/service/plugin/patch_entries.rs b/src-tauri/src/service/plugin/patch_entries.rs
index 082a7c28..6eb1b23a 100644
--- a/src-tauri/src/service/plugin/patch_entries.rs
+++ b/src-tauri/src/service/plugin/patch_entries.rs
@@ -22,6 +22,7 @@ use std::path::Path;
use serde_yaml::{Mapping, Value};
use tauri::AppHandle;
+use super::atomic_write::write_patch_layer_atomically;
use super::installed::ProfilePackageJson;
use super::patch_guard::{backup_path, now_stamp, patch_layer_paths};
@@ -125,7 +126,12 @@ pub(crate) fn strip_unresolved_entries_in(
.map_err(|e| format!("PATCH_LAYER_STRIP_BACKUP_FAILED: {}: {e}", backup.display()))?;
let rendered = serde_yaml::to_string(&Value::Sequence(kept))
.map_err(|e| format!("PATCH_LAYER_STRIP_RENDER_FAILED: {e}"))?;
- write_patch_layer_atomically(&layer, &rendered, &stamp)?;
+ write_patch_layer_atomically(&layer, &rendered).map_err(|error| {
+ format!(
+ "PATCH_LAYER_STRIP_WRITE_FAILED: {}: {error}",
+ layer.display()
+ )
+ })?;
log::warn!(
"PATCH_LAYER_ENTRIES_STRIPPED: {} -> {} (removed {removed})",
layer.display(),
@@ -354,28 +360,6 @@ fn has_effective_id(map: &Mapping) -> bool {
}
}
-/// 原子改写补丁层:先写同目录临时文件再改名替换。
-///
-/// `fs::write` 会先截断原文件,写到一半失败(磁盘满 / 被中断)会把用户手写的补丁层
-/// 截成半截 YAML——虽然 `.bak-<时间戳>` 备份还在,但半截文件会让下次启动多报一个
-/// 语法错误。同目录 `rename` 在 Windows(`MOVEFILE_REPLACE_EXISTING`)与 Unix 上
-/// 都是原子替换,失败时原文件保持不动。
-fn write_patch_layer_atomically(layer: &Path, rendered: &str, stamp: &str) -> Result<(), String> {
- let name = layer
- .file_name()
- .map(|name| name.to_string_lossy().into_owned())
- .unwrap_or_default();
- let temp = layer.with_file_name(format!("{name}.tmp-{stamp}"));
- std::fs::write(&temp, rendered).map_err(|e| {
- let _ = std::fs::remove_file(&temp);
- format!("PATCH_LAYER_STRIP_WRITE_FAILED: {}: {e}", temp.display())
- })?;
- std::fs::rename(&temp, layer).map_err(|e| {
- let _ = std::fs::remove_file(&temp);
- format!("PATCH_LAYER_STRIP_WRITE_FAILED: {}: {e}", layer.display())
- })
-}
-
/// 取映射字段;用迭代而不是 `Mapping::get`,避开 serde_yaml 的索引泛型差异。
fn map_get<'a>(map: &'a Mapping, key: &str) -> Option<&'a Value> {
map.iter()
@@ -781,6 +765,33 @@ mod tests {
assert!(with_id("id: 7"));
}
+ #[cfg(unix)]
+ #[test]
+ fn strip_rejects_a_symlink_to_a_sibling_profile_without_changing_its_entries() {
+ let temp = tempfile::tempdir().unwrap();
+ let profile = temp.path().join("profiles/tauri");
+ let sibling = temp.path().join("profiles/work");
+ std::fs::create_dir_all(&profile).unwrap();
+ std::fs::create_dir_all(&sibling).unwrap();
+ install_package(&sibling, "dsh-file-edit");
+ let target = sibling.join("cordis.patch.yml");
+ std::fs::write(&target, DANGLING_LAYER).unwrap();
+ let link = profile.join("cordis.patch.yml");
+ std::os::unix::fs::symlink(&target, &link).unwrap();
+
+ let error = strip_unresolved_entries_in(&profile, temp.path(), None).unwrap_err();
+ assert!(
+ error.starts_with("PATCH_LAYER_STRIP_WRITE_FAILED: "),
+ "{error}"
+ );
+ assert!(error.contains("symlink"), "{error}");
+ assert_eq!(std::fs::read_to_string(&target).unwrap(), DANGLING_LAYER);
+ assert!(std::fs::symlink_metadata(&link)
+ .unwrap()
+ .file_type()
+ .is_symlink());
+ }
+
/// 原子改写:成功路径不留临时文件,且内容与备份都在。
#[test]
fn strip_leaves_no_temp_file_behind() {
@@ -794,7 +805,7 @@ mod tests {
.unwrap()
.filter_map(|entry| entry.ok())
.map(|entry| entry.file_name().to_string_lossy().into_owned())
- .filter(|name| name.contains(".tmp-"))
+ .filter(|name| name.contains(".tmp-") || name.starts_with(".cordis.patch-"))
.collect();
assert!(leftovers.is_empty(), "{leftovers:?}");
let _ = std::fs::remove_dir_all(&profile);
diff --git a/src-tauri/src/service/plugin/patch_guard.rs b/src-tauri/src/service/plugin/patch_guard.rs
index 49ff3a1d..e7dc2a91 100644
--- a/src-tauri/src/service/plugin/patch_guard.rs
+++ b/src-tauri/src/service/plugin/patch_guard.rs
@@ -97,12 +97,16 @@ pub(crate) fn preflight_at(
Err(unresolved_entries_message(&entries))
}
-/// 解析补丁层:语法错误时返回 serde_yaml 的错误文本(含行列号)。
-///
-/// 文件不存在、读不出来(权限错位/竞态)都不算语法错误——那些由可写性预检与
-/// 上游自身的错误路径负责,本模块只处理「文件在、但 YAML 解析不了」。
+pub(super) const PATCH_ENCODING_FAILED: &str = "INTERNAL_PLUGIN_PATCH_ENCODING_FAILED";
+
fn parse_error(path: &Path) -> Option<String> {
- let raw = std::fs::read_to_string(path).ok()?;
+ let raw = match std::fs::read_to_string(path) {
+ Ok(raw) => raw,
+ Err(error) if error.kind() == std::io::ErrorKind::InvalidData => {
+ return Some(format!("{PATCH_ENCODING_FAILED}: {error}"));
+ }
+ Err(_) => return None,
+ };
serde_yaml::from_str::<serde_yaml::Value>(&raw)
.err()
.map(|error| error.to_string())
@@ -301,6 +305,51 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
+ #[test]
+ fn quarantine_preserves_non_utf8_bytes_in_both_layers() {
+ for bytes in [
+ b"\xff\xfe-\0 \0i\0d\0:\0 \0x\0\n\0".as_slice(),
+ b"- id: plugin\n name: \xc4\xe3\xba\xc3\n".as_slice(),
+ b"# truncated \xe4\xb8".as_slice(),
+ ] {
+ let temp = tempfile::tempdir().unwrap();
+ let home = temp.path();
+ let profile = home.join("profiles/tauri");
+ std::fs::create_dir_all(&profile).unwrap();
+ let paths = patch_layer_paths(&profile, home);
+ for path in &paths {
+ std::fs::write(path, bytes).unwrap();
+ let error = parse_error(path).expect("encoding damage must be quarantinable");
+ assert!(error.contains("UTF-8"), "{error}");
+ assert_eq!(std::fs::read(path).unwrap(), bytes);
+ }
+
+ let report = quarantine_patch_layers_in(&profile, home);
+ assert!(!report.has_failures(), "{report:?}");
+ assert_eq!(report.quarantined.len(), 2);
+ for (record, path) in report.quarantined.iter().zip(&paths) {
+ assert_eq!(record.original, path.display().to_string());
+ assert!(!path.exists());
+ assert_eq!(std::fs::read(&record.backup).unwrap(), bytes);
+ }
+ let repeated = quarantine_patch_layers_in(&profile, home);
+ assert!(repeated.quarantined.is_empty());
+ assert!(!repeated.has_failures());
+ }
+ }
+
+ #[test]
+ fn quarantine_does_not_mistake_io_errors_for_encoding_damage() {
+ let temp = tempfile::tempdir().unwrap();
+ let path = temp.path().join(PATCH_FILENAME);
+ std::fs::create_dir(&path).unwrap();
+ assert!(parse_error(&path).is_none());
+ let report = quarantine_layers(std::slice::from_ref(&path), "20261017000000");
+ assert!(report.quarantined.is_empty());
+ assert!(report.failures.is_empty());
+ assert!(path.is_dir());
+ }
+
#[test]
fn quarantine_moves_only_unparsable_layers() {
let profile = tmp_dir("quarantine-profile");
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index fd015248..42e9b5a8 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -128,8 +128,9 @@
"errors.patch_entry_unresolved": "A patch layer references a plugin package that cannot be resolved, so Harness cannot load the plugin tree: {{detail}}. This usually means a plugin was uninstalled while the hand-written insert entry stayed in cordis.patch.yml. Remove those entries (or reinstall the plugin) and retry, or use \"Remove dangling entries\" to strip only the unresolvable entries (the original file is backed up as `.bak-<timestamp>` first).",
"errors.patch_entry_unresolved_item": "{{layer}} line {{line}}: {{id}} → {{name}}{{note}}",
"errors.patch_entry_unresolved_declared": " (still declared in package.json — reinstalling that plugin is the fix)",
+ "errors.patch_layer_encoding_failed": "A patch file is not valid UTF-8, so Harness cannot read it: {{detail}}. Open it in an editor using its original encoding, then save it as UTF-8 without BOM and retry. The app will not automatically transcode or overwrite it. Choose \"Quarantine broken patch files\" to rename broken files in the current profile and home layers to byte-preserving `.broken-<timestamp>` backups and start. Fix the backup's encoding and rename it back to restore it. \"Safe Mode\" switches to the safe profile and quarantines broken files in the safe profile and home layers; the original profile’s patch file is left unchanged. The home layer applies to all profiles; switching profiles alone cannot bypass it.",
"errors.patch_layer_parse_failed": "A patch layer has a YAML syntax error, so Harness cannot parse it: {{detail}}. The usual cause is an unquoted `!!js` expression that contains `:` or `?` — quote it (`!!js \"…\"`) or use a block scalar (`|-`), then retry. You can also use \"Quarantine broken patch files\" to start anyway; that file is renamed to a `.broken-<timestamp>` backup and restored by renaming it back.",
- "errors.patch_quarantine_failed": "Could not quarantine the broken patch file (rename failed): {{detail}}. The file is still in place, so restarting will hit the same parse error. Close whatever is holding the file (editor / sync client / antivirus), or rename it to a `.broken-<timestamp>` backup manually, then retry.",
+ "errors.patch_quarantine_failed": "Could not quarantine the broken patch file (rename failed): {{detail}}. The file is still in place, so restarting will fail again. Close whatever is holding the file (editor / sync client / antivirus), or rename it to a `.broken-<timestamp>` backup manually, then retry.",
"ui.service_url": "Service URL",
"ui.port": "Port",
"ui.heap_limit": "Service memory limit",
@@ -169,9 +170,9 @@
"buttons.quarantine_patch": "Quarantine broken patch files",
"buttons.strip_patch_entries": "Remove dangling entries",
"patch.entries_stripped_toast": "Removed {{count}} unresolvable patch entries; the original file was backed up as {{backup}}.",
- "patch.quarantined_toast": "Quarantined an unparsable patch file: {{original}} → {{backup}}. Fix the syntax and rename it back to restore it.",
+ "patch.quarantined_toast": "Quarantined a broken patch file: {{original}} → {{backup}}. Fix the syntax or encoding and rename it back to restore it.",
"patch.quarantine_failed_toast": "Failed to quarantine a broken patch file: {{path}} ({{error}})",
- "hints.safe_mode": "Restart with only the core bundles and built-in plugins, uninstalling any other plugin from that profile to isolate the ones that fail to start. Patch files that cannot be parsed (a YAML syntax error) are also moved aside as `.broken-<timestamp>` backups. Switch back to your profile in the sidebar to exit safe mode.",
+ "hints.safe_mode": "Switch to the safe profile with only core bundles and built-in plugins, uninstalling other plugins from that profile to isolate startup failures. Patch files in the safe profile and home layers with YAML syntax errors or invalid UTF-8 are renamed to byte-preserving `.broken-<timestamp>` backups; startup stops if quarantine fails. The original profile’s patch file is left unchanged. Fix it before switching back in the sidebar to exit safe mode.",
"messages.clipboard_copied": "Copied to clipboard",
"messages.environment_copied": "Environment info copied to clipboard",
"messages.clipboard_failed": "Copy failed",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 9b22ce72..b0414303 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -128,8 +128,9 @@
"errors.patch_entry_unresolved": "补丁层引用了装不出来的插件包,Harness 无法加载整棵插件树:{{detail}}。通常是插件被卸载后,手写的 insert 条目还留在 cordis.patch.yml 里。请移除这些条目(或重新安装对应插件)后重试;也可以点「移除悬空条目」,由桌面端只剥离解析不到的条目(原文件会先备份为 `.bak-<时间戳>`)。",
"errors.patch_entry_unresolved_item": "{{layer}} 第 {{line}} 行:{{id}} → {{name}}{{note}}",
"errors.patch_entry_unresolved_declared": "(依赖仍在 package.json 里,重装该插件即可)",
+ "errors.patch_layer_encoding_failed": "补丁文件不是有效的 UTF-8,Harness 无法读取:{{detail}}。请用编辑器按原编码打开并另存为 UTF-8(无 BOM)后重试,应用不会自动转码或覆盖原文件;也可以点「隔离损坏的补丁文件」,把当前档案层和 home 层的损坏文件原样改名为 `.broken-<时间戳>` 备份后启动。修复备份的编码后改回原名即可恢复。「安全模式」会切换到 safe 档案,并隔离 safe 档案层和 home 层的损坏文件;原档案的补丁文件保留不变。home 层作用于所有档案,仅切换档案无法绕过。",
"errors.patch_layer_parse_failed": "补丁层存在 YAML 语法错误,Harness 无法解析:{{detail}}。常见原因是 `!!js` 表达式里含 `:` 或 `?` 却未加引号——请改成 `!!js \"…\"`(或块标量 `|-`)后重试;也可以点「隔离损坏的补丁文件」,把该文件改名为 `.broken-<时间戳>` 备份后先启动(修好语法后改回原名即可恢复)。",
- "errors.patch_quarantine_failed": "无法隔离损坏的补丁文件(改名失败):{{detail}}。文件仍在原处,重启会再次报同样的解析错误。请先关闭占用该文件的程序(编辑器 / 同步网盘 / 杀毒软件),或手动把该文件改名为 `.broken-<时间戳>` 备份,然后重试。",
+ "errors.patch_quarantine_failed": "无法隔离损坏的补丁文件(改名失败):{{detail}}。文件仍在原处,重启仍会失败。请先关闭占用该文件的程序(编辑器 / 同步网盘 / 杀毒软件),或手动把该文件改名为 `.broken-<时间戳>` 备份,然后重试。",
"ui.service_url": "服务地址",
"ui.port": "服务端口",
"ui.heap_limit": "服务内存上限",
@@ -169,9 +170,9 @@
"buttons.quarantine_patch": "隔离损坏的补丁文件",
"buttons.strip_patch_entries": "移除悬空条目",
"patch.entries_stripped_toast": "已移除 {{count}} 个解析不到的补丁条目:原文件已备份为 {{backup}}。",
- "patch.quarantined_toast": "已隔离无法解析的补丁文件:{{original}} → {{backup}}。修好语法后改回原名即可恢复。",
+ "patch.quarantined_toast": "已隔离损坏的补丁文件:{{original}} → {{backup}}。修好语法或编码后改回原名即可恢复。",
"patch.quarantine_failed_toast": "隔离补丁文件失败:{{path}}({{error}})",
- "hints.safe_mode": "仅加载核心组件与内置插件重启,并卸载该档案中的其它插件以隔离启动失败;解析不了的补丁文件(YAML 语法错误)也会被改名为 `.broken-<时间戳>` 备份。在侧边栏切回原档案即可退出安全模式。",
+ "hints.safe_mode": "切换到 safe 档案,仅加载核心组件与内置插件,并卸载该档案中的其它插件以隔离启动失败。safe 档案层和 home 层中有 YAML 语法错误或非 UTF-8 编码的补丁文件会原样改名为 `.broken-<时间戳>` 备份;隔离失败时不会继续启动。原档案的补丁文件保留不变,修复后可在侧边栏切回原档案退出安全模式。",
"messages.clipboard_copied": "已复制到剪贴板",
"messages.environment_copied": "环境信息已复制到剪贴板",
"messages.clipboard_failed": "复制失败",
diff --git a/src/store/modules/harness/patch-layer.ts b/src/store/modules/harness/patch-layer.ts
index d756e908..96d23acd 100644
--- a/src/store/modules/harness/patch-layer.ts
+++ b/src/store/modules/harness/patch-layer.ts
@@ -1,35 +1,22 @@
-/**
- * 补丁层问题的识别与信息提取(纯函数,便于单测)。
- *
- * 两类问题:
- * - YAML 语法错误:Rust 侧 `service::plugin::internal::repair_loader_state` 解析
- * 档案层 / home 层的 `cordis.patch.yml` 失败时抛出
- * `INTERNAL_PLUGIN_PATCH_PARSE_FAILED: <路径>: <错误>`(见
- * `service::plugin::patch_guard` 的模块说明),随后被包成
- * `INTERNAL_PLUGIN_INSTALL_FAILED` 并挂在「Plugin installation 阶段」——用户看到
- * 的是「插件安装失败」,实际原因却是补丁文件写错了(issue #525)。
- * - 悬空 insert 条目:手写的 `insert` 引用了装不出来的包,loader 抛
- * `ERR_MODULE_NOT_FOUND` 让整棵树加载失败(见 `service::plugin::patch_entries`),
- * 启动前预检抛出 `PATCH_LAYER_ENTRY_UNRESOLVED: {json}`。
- *
- * 两类都在这里转成「哪个文件、哪一行、怎么改」的针对性提示与恢复入口。
- */
-
-/** Rust 侧补丁层解析失败的错误码。 */
export const PATCH_PARSE_ERROR_CODE = 'INTERNAL_PLUGIN_PATCH_PARSE_FAILED'
+export const PATCH_ENCODING_ERROR_CODE = 'INTERNAL_PLUGIN_PATCH_ENCODING_FAILED'
-/** 启动失败信息里是否包含补丁层解析失败。 */
export function containsPatchLayerParseError(message: string): boolean {
return message.includes(`${PATCH_PARSE_ERROR_CODE}:`)
}
-/** 提取补丁层解析失败的「路径 + YAML 错误(含行列号)」片段(无则空串)。 */
+export function containsPatchLayerEncodingError(message: string): boolean {
+ return message.includes(`${PATCH_ENCODING_ERROR_CODE}:`)
+}
+
export function patchLayerErrorDetail(message: string): string {
- const marker = `${PATCH_PARSE_ERROR_CODE}:`
- const at = message.indexOf(marker)
- if (at < 0)
- return ''
- return message.slice(at + marker.length).trim()
+ for (const code of [PATCH_ENCODING_ERROR_CODE, PATCH_PARSE_ERROR_CODE]) {
+ const marker = `${code}:`
+ const at = message.indexOf(marker)
+ if (at >= 0)
+ return message.slice(at + marker.length).trim()
+ }
+ return ''
}
/** Rust 侧补丁层「隔离失败」的错误码。 */
diff --git a/src/store/modules/harness/utils.ts b/src/store/modules/harness/utils.ts
index 6284d730..31f1baf6 100644
--- a/src/store/modules/harness/utils.ts
+++ b/src/store/modules/harness/utils.ts
@@ -15,6 +15,7 @@ import {
} from './constants'
import {
containsPatchEntryUnresolved,
+ containsPatchLayerEncodingError,
containsPatchLayerParseError,
containsQuarantineFailure,
patchEntryUnresolvedEntries,
@@ -242,10 +243,12 @@ export async function attachStartupDiagnostics(err: unknown, processExited = fal
diagnosed.heapOomHint = peakMb === undefined ? hint : `${hint} ${i18next.t('errors.heap_oom_peak', { peak: peakMb })}`
}
}
- // 补丁层 YAML 语法错误(issue #525):真实原因是用户手写的 `cordis.patch.yml`
- // 解析不了,但失败阶段是「Plugin installation」,很容易被当成插件损坏。这里挂上
- // 「哪个文件、哪一行、怎么改」的提示(错误页据此给出隔离入口)。
- if (containsPatchLayerParseError(diagnosed.message)) {
+ if (containsPatchLayerEncodingError(diagnosed.message)) {
+ diagnosed.patchLayerHint = i18next.t('errors.patch_layer_encoding_failed', {
+ detail: patchLayerErrorDetail(diagnosed.message),
+ })
+ }
+ else if (containsPatchLayerParseError(diagnosed.message)) {
diagnosed.patchLayerHint = i18next.t('errors.patch_layer_parse_failed', {
detail: patchLayerErrorDetail(diagnosed.message),
})
diff --git a/test/patch-layer.test.ts b/test/patch-layer.test.ts
index 795d3df4..b0b34993 100644
--- a/test/patch-layer.test.ts
+++ b/test/patch-layer.test.ts
@@ -1,7 +1,13 @@
import { readFileSync } from 'node:fs'
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import i18next from 'i18next'
+import { createElement } from 'react'
+import { renderToStaticMarkup } from 'react-dom/server'
+import { I18nextProvider } from 'react-i18next'
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { resources } from '../src/i18n/index.resource'
import {
containsPatchEntryUnresolved,
+ containsPatchLayerEncodingError,
containsPatchLayerParseError,
containsQuarantineFailure,
PATCH_ENTRY_UNRESOLVED_CODE,
@@ -12,6 +18,7 @@ import {
const eventListeners = new Map<string, (event: unknown) => void>()
const invoke = vi.fn()
+const toast = vi.fn()
vi.mock('@tauri-apps/api/core', () => ({ invoke }))
vi.mock('@tauri-apps/api/event', () => ({
@@ -20,24 +27,61 @@ vi.mock('@tauri-apps/api/event', () => ({
return vi.fn()
}),
}))
+vi.mock('@/utils/toast', () => ({ toast }))
vi.mock('@/config/client', () => ({ queryClient: { invalidateQueries: vi.fn() } }))
+vi.mock('@/store', async () => ({ store: { harness: (await import('../src/store/modules/harness')).harness } }))
vi.mock('../src/store/modules/harness-updater', () => ({
harnessUpdater: { checkForUpdate: vi.fn() },
}))
// 必须在 mock 工厂所需的变量初始化之后再取用 store(vi.mock 会被提升到文件顶部)。
const { harness } = await import('../src/store/modules/harness')
+const { attachStartupDiagnostics } = await import('../src/store/modules/harness/utils')
+const { Setup } = await import('../src/layout/components/setup')
-beforeEach(() => {
+beforeAll(async () => {
+ await i18next.init({ resources, lng: 'zh-CN', interpolation: { escapeValue: false }, keySeparator: false, nsSeparator: false, initAsync: false })
+})
+
+beforeEach(async () => {
+ await i18next.changeLanguage('zh-CN')
eventListeners.clear()
invoke.mockReset()
+ toast.mockReset()
+ invoke.mockImplementation(async (command: string) => {
+ switch (command) {
+ case 'get_runtime_info': return { service_url: 'http://127.0.0.1:31415' }
+ case 'runtime_ready': return true
+ case 'proxy_health_check': return 'Healthy'
+ case 'get_preinstall_pending': return false
+ case 'get_profiles': return [{ id: 'tauri', active: true }]
+ case 'get_app_config': return { installed: true }
+ case 'read_service_logs': return ''
+ case 'ensure_internal_plugins':
+ case 'launch_harness':
+ case 'harness_ownership':
+ case 'shutdown_harness': return undefined
+ default: throw new Error(`Unexpected command: ${command}`)
+ }
+ })
Object.assign(harness, {
status: 'ready',
errorMsg: '',
errorLogs: [],
+ patchLayerHint: '',
+ serviceHealthy: false,
+ serviceRunning: false,
+ iframeAliveKey: harness.iframeKey,
busyAction: null,
})
})
+
+afterEach(() => {
+ harness.serviceHealthy = false
+ harness.serviceRunning = false
+ vi.restoreAllMocks()
+})
+
/**
* issue #525:用户手写的 `cordis.patch.yml` 解析失败时,启动失败信息里的真实
* 原因被包在「Plugin installation 阶段失败」里,前端必须能识别出来并给出
@@ -79,6 +123,168 @@ describe('patch layer diagnostics', () => {
const QUARANTINE_FAILURE = 'PATCH_LAYER_QUARANTINE_FAILED: '
+ 'C:\\Users\\Administrator\\.dsh\\cordis.patch.yml: Access is denied. (os error 5)'
+describe('patch layer encoding recovery', () => {
+ it('recognizes wrapped encoding failures without treating IO errors as damaged patches', () => {
+ expect(containsPatchLayerEncodingError('INTERNAL_PLUGIN_INSTALL_FAILED: INTERNAL_PLUGIN_PATCH_ENCODING_FAILED: /tmp/cordis.patch.yml: invalid UTF-8')).toBe(true)
+ expect(containsPatchLayerEncodingError('INTERNAL_PLUGIN_PATCH_READ_FAILED: /tmp/cordis.patch.yml: Permission denied')).toBe(false)
+ expect(containsPatchLayerEncodingError('see INTERNAL_PLUGIN_PATCH_ENCODING_FAILED for details')).toBe(false)
+ expect(containsPatchLayerEncodingError(REAL_FAILURE)).toBe(false)
+ })
+
+ it.each(['profiles\\tauri\\cordis.patch.yml', 'cordis.patch.yml'])('shows a UTF-8 hint and quarantine button for %s', async (layer) => {
+ const detail = `C:\\Users\\26231\\.dsh\\${layer}: stream did not contain valid UTF-8`
+ const message = `Harness 在Plugin installation阶段失败。最后的就绪状态:INTERNAL_PLUGIN_PATCH_ENCODING_FAILED: ${detail}`
+ invoke.mockResolvedValue('')
+
+ const diagnosed = await attachStartupDiagnostics(message)
+ expect(diagnosed.message).toBe(message)
+ expect(diagnosed.patchLayerHint).toContain(detail)
+ expect(diagnosed.patchLayerHint).toContain('另存为 UTF-8')
+ expect(diagnosed.patchLayerHint).toContain('.broken-')
+ expect(diagnosed.patchLayerHint).toContain('不会自动转码')
+ expect(diagnosed.patchLayerHint).not.toContain('YAML 语法错误')
+ expect(patchLayerErrorDetail(message)).toBe(detail)
+
+ Object.assign(harness, { status: 'error', errorMsg: message, patchLayerHint: diagnosed.patchLayerHint })
+ const html = renderToStaticMarkup(createElement(I18nextProvider, { i18n: i18next }, createElement(Setup)))
+ expect(html).toContain('另存为 UTF-8')
+ expect(html).toContain('隔离损坏的补丁文件</button>')
+ expect(html).not.toContain('移除悬空条目</button>')
+ })
+
+ it('does not offer destructive encoding recovery for an IO read failure', async () => {
+ const message = 'INTERNAL_PLUGIN_PATCH_READ_FAILED: C:/data/cordis.patch.yml: Access is denied. (os error 5)'
+ invoke.mockResolvedValue('')
+ const diagnosed = await attachStartupDiagnostics(message)
+ expect(diagnosed.patchLayerHint).toBeUndefined()
+ expect(patchLayerErrorDetail(message)).toBe('')
+ Object.assign(harness, { status: 'error', errorMsg: message })
+ const html = renderToStaticMarkup(createElement(I18nextProvider, { i18n: i18next }, createElement(Setup)))
+ expect(html).not.toContain('隔离损坏的补丁文件</button>')
+ })
+
+ it('provides manual UTF-8 recovery instructions in both locales', () => {
+ for (const locale of Object.values(resources)) {
+ const hint = (locale.translation as Record<string, string>)['errors.patch_layer_encoding_failed']
+ expect(hint).toContain('UTF-8')
+ expect(hint).toContain('{{detail}}')
+ expect(hint).toContain('.broken-')
+ }
+ })
+
+ it.each([
+ ['zh-CN', '另存为 UTF-8', '隔离损坏的补丁文件', '安全模式'],
+ ['en-US', 'save it as UTF-8', 'Quarantine broken patch files', 'Safe Mode'],
+ ])('renders the localized encoding recovery controls in %s', async (language, instruction, quarantine, safeMode) => {
+ await i18next.changeLanguage(language)
+ const diagnosed = await attachStartupDiagnostics('INTERNAL_PLUGIN_PATCH_ENCODING_FAILED: /tmp/cordis.patch.yml: invalid UTF-8')
+ Object.assign(harness, { status: 'error', errorMsg: diagnosed.message, patchLayerHint: diagnosed.patchLayerHint })
+
+ const html = renderToStaticMarkup(createElement(I18nextProvider, { i18n: i18next }, createElement(Setup)))
+ expect(html).toContain(instruction)
+ expect(html).toContain(`${quarantine}</button>`)
+ expect(html).toContain(`${safeMode}</button>`)
+ })
+
+ it.each([
+ ['zh-CN', 'safe 档案', '原档案的补丁文件保留不变'],
+ ['en-US', 'safe profile', 'original profile’s patch file is left unchanged'],
+ ])('describes the safe profile and unchanged original patch in %s', (language, profile, preserved) => {
+ const hint = i18next.t('errors.patch_layer_encoding_failed', { lng: language })
+ expect(hint).toContain(profile)
+ expect(hint).toContain(preserved)
+ expect(hint).toContain('home')
+ })
+
+ it.each(['zh-CN', 'en-US'])('mentions encoding damage in the safe-mode explanation in %s', (language) => {
+ const hint = i18next.t('hints.safe_mode', { lng: language })
+ expect(hint).toContain('UTF-8')
+ expect(hint).toContain('home')
+ expect(hint).toContain('.broken-')
+ })
+
+ it.each([
+ ['zh-CN', '语法或编码'],
+ ['en-US', 'syntax or encoding'],
+ ])('provides encoding-aware restoration instructions after quarantine in %s', (language, repair) => {
+ expect(i18next.t('patch.quarantined_toast', { lng: language })).toContain(repair)
+ })
+
+ it.each([
+ ['zh-CN', '同样的解析错误'],
+ ['en-US', 'same parse error'],
+ ])('does not mislabel failed encoding quarantine as a parse error in %s', (language, misleading) => {
+ expect(i18next.t('errors.patch_quarantine_failed', { lng: language })).not.toContain(misleading)
+ })
+})
+
+describe('encoding recovery actions', () => {
+ it.each([
+ ['quarantine_broken_patch_layers', 'profiles/tauri/cordis.patch.yml'],
+ ['quarantine_broken_patch_layers', 'cordis.patch.yml'],
+ ['enter_safe_mode', 'cordis.patch.yml'],
+ ])('starts only after %s reports the backup for %s', async (command, layer) => {
+ const original = `/tmp/issue1118/${layer}`
+ const backup = `${original}.broken-20261017220000`
+ const runtimeInvoke = invoke.getMockImplementation()!
+ invoke.mockImplementation(async (name: string) => {
+ if (name === command) {
+ expect(harness.busyAction).toBe('repair')
+ expect(invoke).not.toHaveBeenCalledWith('launch_harness')
+ return { quarantined: [{ original, backup, error: 'invalid UTF-8' }], failures: [] }
+ }
+ return runtimeInvoke(name)
+ })
+ Object.assign(harness, { status: 'error', errorMsg: `INTERNAL_PLUGIN_PATCH_ENCODING_FAILED: ${original}: invalid UTF-8` })
+
+ if (command === 'enter_safe_mode')
+ await harness.enterSafeMode()
+ else
+ await harness.quarantineBrokenPatchLayers()
+
+ expect(invoke.mock.calls.filter(([name]) => name === command)).toEqual([[command]])
+ expect(invoke.mock.calls.filter(([name]) => name === 'launch_harness')).toEqual([['launch_harness']])
+ if (command === 'enter_safe_mode')
+ expect(invoke).not.toHaveBeenCalledWith('shutdown_harness')
+ else
+ expect(invoke).toHaveBeenCalledWith('shutdown_harness')
+ expect(toast).toHaveBeenCalledExactlyOnceWith(expect.stringContaining(`${original} → ${backup}`), { variant: 'accent', timeout: 10_000 })
+ expect(harness.status).toBe('ready')
+ expect(harness.serviceHealthy).toBe(true)
+ expect(harness.errorMsg).toBe('')
+ expect(harness.patchLayerHint).toBe('')
+ expect(harness.busyAction).toBe(null)
+ })
+
+ it.each(['quarantine_broken_patch_layers', 'enter_safe_mode'])('does not restart after %s cannot move the broken home patch', async (command) => {
+ const failure = 'PATCH_LAYER_QUARANTINE_FAILED: /tmp/issue1118/cordis.patch.yml: Access is denied. (os error 5)'
+ const logError = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const runtimeInvoke = invoke.getMockImplementation()!
+ invoke.mockImplementation(async (name: string) => {
+ if (name === command)
+ throw failure
+ return runtimeInvoke(name)
+ })
+
+ if (command === 'enter_safe_mode')
+ await harness.enterSafeMode()
+ else
+ await harness.quarantineBrokenPatchLayers()
+
+ expect(logError).toHaveBeenCalledWith(expect.any(String), failure)
+ expect(invoke.mock.calls.filter(([name]) => name === command)).toEqual([[command]])
+ expect(invoke).not.toHaveBeenCalledWith('launch_harness')
+ expect(invoke).not.toHaveBeenCalledWith('shutdown_harness')
+ expect(invoke).not.toHaveBeenCalledWith('ensure_internal_plugins')
+ expect(toast).not.toHaveBeenCalled()
+ expect(harness.status).toBe('error')
+ expect(harness.errorMsg).toBe(failure)
+ expect(harness.patchLayerHint).toContain('Access is denied.')
+ expect(harness.patchLayerHint).toContain('文件仍在原处')
+ expect(harness.busyAction).toBe(null)
+ })
+})
+
describe('patch quarantine failures', () => {
it('recognizes an aborted quarantine', () => {
expect(containsQuarantineFailure(QUARANTINE_FAILURE)).toBe(true)
@@ -213,25 +419,6 @@ describe('unresolved-entry recovery wiring', () => {
const pending = new Promise<void>((resolve) => {
release = resolve
})
- // 让修复之后的 restart 能安静跑完:这条用例只关心占住忙态的时机。
- invoke.mockImplementation(async (command: string) => {
- if (command === 'get_runtime_info')
- return { service_url: 'http://127.0.0.1:31415' }
- if (command === 'runtime_ready')
- return true
- if (command === 'proxy_health_check')
- return 'Healthy'
- if (command === 'get_preinstall_pending')
- return false
- if (command === 'detect_plugin_recovery')
- return { plugins: [], reason: 'unknown', detail: '', rawError: '' }
- if (command === 'read_service_logs')
- return ''
- if (command === 'get_app_config')
- return { installed: true, port: 3080, harness_max_heap_mb: 16384, proxy_url: '', auto_start: true, cli_link_enabled: true, zoom_factor: 1, close_action: 'tray', backup_retention_count: 10, backup_include_credentials: false, language: null }
- return undefined
- })
-
const repair = harness.runPatchRepair('safe-mode', async () => {
await pending
})
@@ -240,5 +427,8 @@ describe('unresolved-entry recovery wiring', () => {
expect(harness.busyAction).toBe('repair')
release()
await repair
+ expect(harness.status).toBe('ready')
+ expect(harness.serviceHealthy).toBe(true)
+ expect(harness.busyAction).toBe(null)
})
})