DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix: harden desktop security boundaries
[email protected]baae4837ab3d
diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex e5765753..cba7fb60 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -1,11 +1,8 @@{"$schema": "../gen/schemas/desktop-schema.json","identifier": "default",- "description": "Capability for the main window and the embedded Harness GUI; grants IPC (e.g. opener|open_url) to the remote-origin dsh page. The service port is NOT fixed: it defaults to 3080/3081 but is user-configurable and advances to the next free port when the default is occupied (service/workflow::find_available_port), so the allowlist must cover any loopback port, not a hardcoded pair.",+ "description": "Capability for the local desktop shell. The embedded remote Harness page does not receive native Tauri permissions and communicates with the shell through the restricted postMessage bridge. The service port is NOT fixed: it defaults to 3080/3081 but is user-configurable and advances to the next free port when the default is occupied (service/workflow::find_available_port).","windows": ["main"],- "remote": {- "urls": ["http://127.0.0.1:*"]- },"permissions": ["core:default","core:event:allow-listen",diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex d5f34448..6f077a23 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -28,9 +28,9 @@ use crate::utils::show_main_window;////// `data-tauri-drag-region` 的兼容脚本只处理鼠标事件;WebView2 的原生/// `app-region: drag` 才能让触摸输入进入窗口非客户区拖拽。ElasticOverscroll-/// 会抢走触摸手势,因此必须同时禁用。Wry 的默认安全功能也要显式保留。+/// 会抢走触摸手势,因此必须同时禁用。Wry 的默认安全功能保持启用。#[cfg(windows)]-const WINDOWS_DRAG_BROWSER_ARGS: &str = "--enable-features=msWebView2EnableDraggableRegions --disable-features=ElasticOverscroll,msWebOOUI,msPdfOOUI,msSmartScreenProtection";+const WINDOWS_DRAG_BROWSER_ARGS: &str = "--enable-features=msWebView2EnableDraggableRegions --disable-features=ElasticOverscroll,msWebOOUI,msPdfOOUI";#[cfg(windows)]fn windows_drag_browser_args() -> &'static str {@@ -453,7 +453,27 @@ mod tests {let args = windows_drag_browser_args();assert!(args.contains("--enable-features=msWebView2EnableDraggableRegions"));assert!(args.contains("--disable-features=ElasticOverscroll"));- assert!(args.contains("msWebOOUI,msPdfOOUI,msSmartScreenProtection"));+ assert!(args.contains("msWebOOUI,msPdfOOUI"));+ let smart_screen = ["ms", "SmartScreen", "Protection"].concat();+ assert!(!args.contains(smart_screen.as_str()));+ }+}++#[cfg(test)]+mod security_tests {+ #[test]+ fn remote_capability_does_not_cover_wildcard_loopback() {+ let capability = include_str!("../../capabilities/default.json");+ assert!(!capability.contains("\"remote\""));+ let wildcard_loopback = ["http://127.0.0.1:", "*"].concat();+ assert!(!capability.contains(wildcard_loopback.as_str()));+ }++ #[test]+ fn webview_security_features_are_not_disabled() {+ let source = include_str!("builder.rs");+ let smart_screen = ["ms", "SmartScreen", "Protection"].concat();+ assert!(!source.contains(smart_screen.as_str()));}}diff --git a/src-tauri/src/service/core/version.rs b/src-tauri/src/service/core/version.rsindex b01082e5..628bf0d0 100644--- a/src-tauri/src/service/core/version.rs+++ b/src-tauri/src/service/core/version.rs@@ -31,14 +31,24 @@ fn slot_dir(app_handle: &AppHandle, tag: &str) -> PathBuf {/// `dependencies/dsh-<tag>`(tag 以 `dsh-` 开头时旧命名会产生 `dsh-dsh-...`)。fn existing_slot_dir(app_handle: &AppHandle, tag: &str) -> Option<PathBuf> {let deps = dependencies_dir(app_handle);- let new = deps.join(tag);+ let new = safe_slot_path(&deps, tag).ok()?;if new.is_dir() {return Some(new);}- let legacy = deps.join(format!("dsh-{tag}"));+ let legacy = safe_slot_path(&deps, &format!("dsh-{tag}")).ok()?;legacy.is_dir().then_some(legacy)}+/// 构造槽位路径,并拒绝越出 dependencies 根目录的既有路径或符号链接。+fn safe_slot_path(deps: &Path, tag: &str) -> Result<PathBuf, String> {+ fs_guard::validate_id(tag)?;+ let path = deps.join(tag);+ if path.exists() {+ fs_guard::ensure_within(&path, deps)?;+ }+ Ok(path)+}+/// 读取发行版目录 `package.json` 中 `@deepseek-ai/dsh` 依赖版本(历史槽位展示用)。fn read_manifest_dsh_version(dir: &Path) -> Option<String> {let content = std::fs::read_to_string(dir.join("package.json")).ok()?;@@ -273,6 +283,7 @@ pub async fn set_active(app_handle: &AppHandle, id: &str) -> Result<HarnessCore,async fn switch_app_version(app_handle: &AppHandle, tag: &str) -> Result<(), String> {let deps = dependencies_dir(app_handle);let active_dir = config::get_dsh_install_path(app_handle);+ fs_guard::validate_id(tag)?;let target_dir = existing_slot_dir(app_handle, tag).ok_or_else(|| format!("CORE_VERSION_NOT_DOWNLOADED: {tag}"))?;let cur_tag = config::get_dsh_pkg_tag(app_handle);@@ -293,14 +304,14 @@ async fn switch_app_version(app_handle: &AppHandle, tag: &str) -> Result<(), Str}// 1. 当前激活目录让出激活位:改名为自己的 tag 槽位(残留槽位先清理)- let backup_dir = match &cur_tag {- Some(cur) => deps.join(cur),+ let backup_tag = cur_tag.clone().unwrap_or_else(|| {// 无 tag 记录(旧版安装):用版本号兜底命名槽位- None => deps.join(format!(+ format!("dsh-{}",config::get_dsh_version(app_handle).unwrap_or_else(|| "unknown".to_string())- )),- };+ )+ });+ let backup_dir = safe_slot_path(&deps, &backup_tag)?;if active_dir.exists() {if backup_dir.exists() && !download::remove_dir_with_retry(&backup_dir).await {return Err(format!(@@ -464,6 +475,36 @@ fn row_for_tag(app_handle: &AppHandle, tag: &str, dir: &Path) -> HarnessCore {mod tests {use super::*;+ #[test]+ fn slot_paths_reject_traversal_and_accept_release_tag() {+ let root = std::env::temp_dir().join(format!("dsh-core-slots-{}", std::process::id()));+ std::fs::create_dir_all(&root).unwrap();++ assert!(safe_slot_path(&root, "foo/../../target").is_err());+ let valid = "dsh-0.1.0-rc.8-32331963388";+ let expected = root.join(valid);+ assert_eq!(safe_slot_path(&root, valid).unwrap(), expected);++ std::fs::create_dir_all(&expected).unwrap();+ assert_eq!(safe_slot_path(&root, valid).unwrap(), expected);+ std::fs::remove_dir_all(&root).unwrap();+ }++ #[cfg(unix)]+ #[test]+ fn slot_paths_reject_symlink_escape() {+ let root = std::env::temp_dir().join(format!("dsh-core-slots-link-{}", std::process::id()));+ let outside =+ std::env::temp_dir().join(format!("dsh-core-slots-outside-{}", std::process::id()));+ std::fs::create_dir_all(&root).unwrap();+ std::fs::create_dir_all(&outside).unwrap();+ std::os::unix::fs::symlink(&outside, root.join("dsh-evil")).unwrap();++ assert!(safe_slot_path(&root, "dsh-evil").is_err());+ let _ = std::fs::remove_dir_all(root);+ let _ = std::fs::remove_dir_all(outside);+ }+#[test]fn list_dedupes_versions_keeping_last_tag() {// 模拟 pkg 仓库的测试打包:同一版本打多个 tag(最新在前),去重后每个版本diff --git a/src-tauri/src/service/plugin/recovery.rs b/src-tauri/src/service/plugin/recovery.rsindex 8fb70b1a..c84df73e 100644--- a/src-tauri/src/service/plugin/recovery.rs+++ b/src-tauri/src/service/plugin/recovery.rs@@ -23,6 +23,7 @@ use tauri::AppHandle;use super::errors;use super::installed::profile_dir;+use crate::service::fs_guard;/// 前端监听的事件名:需要弹出插件异常修复界面时推送。pub(crate) const RECOVERY_REQUIRED_EVENT: &str = "plugin-recovery-required";@@ -46,18 +47,40 @@ fn is_package_name(s: &str) -> bool {if s.is_empty() || s.contains(':') || s.chars().any(|c| c.is_whitespace()) {return false;}- // 路径穿越防护:`.` 与 `..` 虽由字符集放行(包名允许点),但单独出现- // 或作为路径片段时会被 `Path::join` 解析为上级目录——必须显式拒绝。- if s == "." || s == ".." || s.starts_with("..") || s.ends_with('/') || s.ends_with("..") {- return false;- }- let body = s.strip_prefix('@').unwrap_or(s);- // scoped 必须带 `/`(@scope/name)- if s.starts_with('@') && !body.contains('/') {++ let (scope, name) = if let Some((scope, name)) = s.split_once('/') {+ // scoped 包名必须恰好只有一层 scope/name,不能把多个路径片段带入 join。+ if !s.starts_with('@') || name.is_empty() || name.contains('/') {+ return false;+ }+ (Some(scope), name)+ } else {+ if s.starts_with('@') {+ return false;+ }+ (None, s)+ };++ fn valid_component(component: &str, is_scope: bool) -> bool {+ let component = if is_scope {+ component.strip_prefix('@').unwrap_or(component)+ } else {+ component+ };+ !component.is_empty()+ && component != "."+ && component != ".."+ && !component.starts_with("..")+ && !component.ends_with("..")+ && component+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_')+ }++ if scope.is_some_and(|scope| !valid_component(scope, true)) {return false;}- body.chars()- .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_' || c == '/')+ valid_component(name, false)}/// 是否是可行动的第三方插件引用(排除核心包与 @deepseek-ai 官方包)。@@ -526,7 +549,24 @@ fn remove_plugin_from_manifest(manifest: &mut serde_json::Value, id: &str) -> bo/// 删除 `node_modules/<id>`;scoped 目录删除后若 scope 空则一并清理。fn remove_plugin_dir(profile: &Path, id: &str) {let node_modules = profile.join("node_modules");- let dir = node_modules.join(id);+ let Ok(node_modules_root) = fs_guard::ensure_within(&node_modules, profile) else {+ log::warn!(+ "refusing to remove plugin from node_modules outside profile: {}",+ node_modules.display()+ );+ return;+ };+ let dir = node_modules_root.join(id);+ if !dir.exists() {+ return;+ }+ let Ok(dir) = fs_guard::ensure_within(&dir, &node_modules_root) else {+ log::warn!(+ "refusing to remove plugin outside node_modules: {}",+ dir.display()+ );+ return;+ };if let Err(e) = fs::remove_dir_all(&dir) {if e.kind() != std::io::ErrorKind::NotFound {log::warn!("failed to remove plugin dir {}: {e}", dir.display());@@ -537,14 +577,16 @@ fn remove_plugin_dir(profile: &Path, id: &str) {.then(|| id.split('/').next().unwrap_or_default()){if !scope.is_empty() && scope != id {- let scope_dir = node_modules.join(scope);+ let scope_dir = node_modules_root.join(scope);if scope_dir.is_dir()&& scope_dir.read_dir().map(|mut d| d.next().is_none()).unwrap_or(false){- let _ = fs::remove_dir_all(&scope_dir);+ if let Ok(scope_dir) = fs_guard::ensure_within(&scope_dir, &node_modules_root) {+ let _ = fs::remove_dir_all(scope_dir);+ }}}}@@ -643,12 +685,69 @@ mod tests {assert!(!is_package_name("has space"));assert!(!is_package_name("with:colon"));assert!(!is_package_name("@bare"));+ assert!(!is_package_name("foo/../../target"));+ assert!(!is_package_name("@scope/../../target"));+ assert!(!is_package_name("@scope/pkg/extra"));+ assert!(!is_package_name(r"foo\..\target"));+ assert!(!is_package_name(r"@scope\pkg"));+ assert!(!is_package_name("@scope/@pkg"));+ assert!(!is_package_name("@scope/.."));+ assert!(!is_package_name("@scope/."));+ assert!(is_package_name("foo.bar"));+ assert!(is_package_name("@scope/pkg.name"));assert!(!is_actionable_plugin_ref("@deepseek-ai/dsh-base"));// dshmarket 是第三方市场插件,可卸载(不应被当作核心保护包)assert!(is_actionable_plugin_ref("dshmarket"));assert!(is_actionable_plugin_ref("dsh-better-sidebar"));}+ #[test]+ fn remove_plugin_dir_rejects_path_escape() {+ let root = std::env::temp_dir().join(format!("dsh-plugin-recovery-{}", std::process::id()));+ let profile = root.join("profile");+ std::fs::create_dir_all(profile.join("node_modules/foo")).unwrap();+ let outside = profile.join("target");+ std::fs::create_dir_all(&outside).unwrap();++ remove_plugin_dir(&profile, "foo/../../target");++ assert!(outside.exists(), "path traversal target must remain");+ let _ = std::fs::remove_dir_all(root);+ }++ #[test]+ fn remove_plugin_dir_removes_valid_plugin() {+ let root =+ std::env::temp_dir().join(format!("dsh-plugin-recovery-valid-{}", std::process::id()));+ let profile = root.join("profile");+ let plugin = profile.join("node_modules/dsh-example");+ std::fs::create_dir_all(&plugin).unwrap();+ std::fs::write(plugin.join("index.js"), "module.exports = {};").unwrap();++ remove_plugin_dir(&profile, "dsh-example");++ assert!(!plugin.exists(), "valid plugin directory should be removed");+ let _ = std::fs::remove_dir_all(root);+ }++ #[cfg(unix)]+ #[test]+ fn remove_plugin_dir_rejects_node_modules_symlink_escape() {+ let root =+ std::env::temp_dir().join(format!("dsh-plugin-recovery-link-{}", std::process::id()));+ let profile = root.join("profile");+ let outside = root.join("outside-node-modules");+ let plugin = outside.join("dsh-example");+ std::fs::create_dir_all(&profile).unwrap();+ std::fs::create_dir_all(&plugin).unwrap();+ std::os::unix::fs::symlink(&outside, profile.join("node_modules")).unwrap();++ remove_plugin_dir(&profile, "dsh-example");++ assert!(plugin.exists(), "plugin outside profile must remain");+ let _ = std::fs::remove_dir_all(root);+ }+#[test]fn extract_refs_from_failure_log() {let log = r#"