diff --git a/crates/squid-engine/src/lib.rs b/crates/squid-engine/src/lib.rs index ed0a4e1..88ac8a3 100644 --- a/crates/squid-engine/src/lib.rs +++ b/crates/squid-engine/src/lib.rs @@ -19,7 +19,9 @@ pub mod delete; pub mod duplicates; pub mod insights; pub mod maintenance; +pub mod privacy; pub mod purge; +pub mod tweaks; pub mod uninstall; pub mod updates; diff --git a/crates/squid-engine/src/privacy.rs b/crates/squid-engine/src/privacy.rs new file mode 100644 index 0000000..34f4576 --- /dev/null +++ b/crates/squid-engine/src/privacy.rs @@ -0,0 +1,255 @@ +//! 隐私清理 (privacy cleaning) — the traces page. +//! +//! Different from every other engine on purpose: these deletions do **not** +//! go to the Recycle Bin. A browser profile half-restored from the bin is +//! worse than no restore at all (Chrome refuses profiles whose History file +//! was swapped behind its back), so the honest answer is: gone is gone, but +//! *what* was gone is written to the same history ledger, and the browser +//! lock check happens at scan time — an open browser shows a 🔒 chip instead +//! of silently failing mid-delete. + +use squid_core::progress::CancelToken; +use squid_core::{Bytes, Category, CleanupItem, ItemKind, LockReason}; +use std::path::PathBuf; + +/// One privacy target: display copy, the paths it wipes, and the process +/// that must be closed first (browser profiles are exclusively locked). +struct PrivacySpec { + id: &'static str, + label_zh: &'static str, + detail_zh: &'static str, + /// (path, kind) pairs; Contents keeps the folder, deletes its children. + parts: &'static [(&'static str, ItemKind)], + /// Executable (lower-case, no path) that locks these files. + process: &'static str, +} + +const SPECS: &[PrivacySpec] = &[ + PrivacySpec { + id: "privacy-edge", + label_zh: "Edge 浏览记录与 Cookie", + detail_zh: "历史、Cookie、会话恢复数据;清空后需要重新登录网站", + parts: &[ + ( + r"AppData\Local\Microsoft\Edge\User Data\Default\History", + ItemKind::File, + ), + ( + r"AppData\Local\Microsoft\Edge\User Data\Default\History-journal", + ItemKind::File, + ), + ( + r"AppData\Local\Microsoft\Edge\User Data\Default\Network\Cookies", + ItemKind::File, + ), + ( + r"AppData\Local\Microsoft\Edge\User Data\Default\Network\Cookies-wal", + ItemKind::File, + ), + ( + r"AppData\Local\Microsoft\Edge\User Data\Default\Network\Cookies-shm", + ItemKind::File, + ), + ( + r"AppData\Local\Microsoft\Edge\User Data\Default\Session Storage", + ItemKind::Contents, + ), + ], + process: "msedge.exe", + }, + PrivacySpec { + id: "privacy-chrome", + label_zh: "Chrome 浏览记录与 Cookie", + detail_zh: "历史、Cookie、会话恢复数据;清空后需要重新登录网站", + parts: &[ + ( + r"AppData\Local\Google\Chrome\User Data\Default\History", + ItemKind::File, + ), + ( + r"AppData\Local\Google\Chrome\User Data\Default\History-journal", + ItemKind::File, + ), + ( + r"AppData\Local\Google\Chrome\User Data\Default\Network\Cookies", + ItemKind::File, + ), + ( + r"AppData\Local\Google\Chrome\User Data\Default\Network\Cookies-wal", + ItemKind::File, + ), + ( + r"AppData\Local\Google\Chrome\User Data\Default\Network\Cookies-shm", + ItemKind::File, + ), + ( + r"AppData\Local\Google\Chrome\User Data\Default\Session Storage", + ItemKind::Contents, + ), + ], + process: "chrome.exe", + }, + PrivacySpec { + id: "privacy-recent", + label_zh: "最近使用的文件 / 跳转列表", + detail_zh: "开始菜单与任务栏右键里的最近记录(链接本身,不删文件)", + parts: &[ + ( + r"AppData\Roaming\Microsoft\Windows\Recent", + ItemKind::Contents, + ), + ( + r"AppData\Roaming\Microsoft\Windows\Recent\AutomaticDestinations", + ItemKind::Contents, + ), + ( + r"AppData\Roaming\Microsoft\Windows\Recent\CustomDestinations", + ItemKind::Contents, + ), + ], + process: "", + }, + PrivacySpec { + id: "privacy-clipboard", + label_zh: "剪贴板历史(Win+V)", + detail_zh: "Win+V 面板里缓存的历史条目,删除后列表清空", + parts: &[(r"AppData\Local\Microsoft\Clipboard", ItemKind::Contents)], + process: "", + }, + PrivacySpec { + id: "privacy-activity", + label_zh: "活动历史记录(时间线)", + detail_zh: "设置→隐私→活动历史;删除后「恢复上次会话」不再可用", + parts: &[( + r"AppData\Local\ConnectedDevicesPlatform", + ItemKind::Contents, + )], + process: "", + }, +]; + +/// Catalog for the UI: id + copy + estimated size, current lock state. +pub fn collect(engine: &crate::Engine, cancel: &CancelToken) -> Vec { + let home = squid_core::paths::home_dir(); + let running: Vec = engine + .platform() + .running_executables() + .into_iter() + .map(|proc| { + proc.rsplit(['/', '\\']) + .next() + .unwrap_or_default() + .to_lowercase() + }) + .collect(); + let mut out = Vec::new(); + for spec in SPECS { + if cancel.is_cancelled() { + return out; + } + let blocked = !spec.process.is_empty() && running.iter().any(|p| p == spec.process); + for (tail, kind) in spec.parts { + let path = home.join(tail); + if !path.exists() { + continue; + } + let bytes = if path.is_dir() { + walkdir::WalkDir::new(&path) + .max_depth(4) + .into_iter() + .filter_entry(|e| !e.file_type().is_symlink()) + .flatten() + .filter(|e| e.file_type().is_file()) + .filter_map(|e| e.metadata().ok()) + .map(|m| m.len()) + .sum() + } else { + std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0) + }; + let mut item = CleanupItem::new(path.clone(), *kind, Category::Privacy, spec.label_zh) + .with_rule(spec.id) + .with_anchors(std::iter::once(home.clone())) + .with_note(spec.detail_zh); + item.size = Bytes(bytes); + item.allocated = Bytes(bytes); + item.selected = false; // privacy deletes are opt-in, always + item.evidence = vec!["record:privacy-trace".into()]; + if blocked { + item = item + .locked(LockReason::AppRunning) + .with_note(format!("{}:先完全退出浏览器再清理", spec.process)); + } + out.push(item); + } + } + out +} + +/// Expand a spec id back into the concrete paths it wipes. The delete layer +/// rebuilds Fresh items from these (never trusting the scan view). +pub fn paths_for(id: &str) -> Vec<(PathBuf, ItemKind)> { + let home = squid_core::paths::home_dir(); + let Some(spec) = SPECS.iter().find(|spec| spec.id == id) else { + return Vec::new(); + }; + spec.parts + .iter() + .map(|(tail, kind)| (home.join(tail), *kind)) + .filter(|(path, _)| path.exists()) + .collect() +} + +/// The lock reason if this spec cannot be cleaned right now. +pub fn lock_reason(engine: &crate::Engine, id: &str) -> Option { + let spec = SPECS.iter().find(|spec| spec.id == id)?; + if spec.process.is_empty() { + return None; + } + let running: Vec = engine + .platform() + .running_executables() + .into_iter() + .map(|proc| { + proc.rsplit(['/', '\\']) + .next() + .unwrap_or_default() + .to_lowercase() + }) + .collect(); + running + .iter() + .any(|p| p == spec.process) + .then(|| format!("{} 正在运行,请先完全退出", spec.process)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_spec_id_is_unique_and_prefixed() { + let mut seen = std::collections::HashSet::new(); + for spec in SPECS { + assert!(spec.id.starts_with("privacy-"), "{}", spec.id); + assert!(seen.insert(spec.id), "duplicate id {}", spec.id); + } + } + + #[test] + fn unknown_ids_expand_to_nothing() { + assert!(paths_for("privacy-nonsense").is_empty()); + assert!(paths_for("").is_empty()); + } + + #[test] + fn known_ids_expand_without_panicking() { + // Real machine: some paths exist, some do not — either way the + // expansion must be a subset of the home tree, never a foreign root. + let home = squid_core::paths::home_dir(); + for spec in SPECS { + for (path, _) in paths_for(spec.id) { + assert!(path.starts_with(&home) || home.join(&path).starts_with(&home)); + } + } + } +} diff --git a/crates/squid-engine/src/tweaks.rs b/crates/squid-engine/src/tweaks.rs new file mode 100644 index 0000000..424a37b --- /dev/null +++ b/crates/squid-engine/src/tweaks.rs @@ -0,0 +1,393 @@ +//! 系统优化 (system optimisation) — a curated, **reversible** tweaks catalog. +//! +//! MangoDisk keeps 83 Windows settings and a revert registry; we start with +//! the low-dispute subset and one hard rule each tweak must pass before it +//! ships here: (1) registry-only or documented-API, (2) the original value +//! is recorded before the first write, (3) 「恢复全部默认」 puts every recorded +//! value back exactly, (4) verified on a real machine, not just this file. +//! +//! The catalog is data. Each tweak declares its hive/key/value/type and the +//! bytes that mean on/off; everything else (state read, apply, revert) is +//! one shared code path, so adding a tweak cannot introduce new bugs in +//! reading, writing, or undoing. + +use serde::Serialize; +use squid_core::Settings; +use std::path::PathBuf; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum TweakKind { + Dword, + String, + NoneMeansZero, +} + +/// One catalog entry. `on` is the payload that enables the tweak; `restore` +/// describes what "back to default" means (delete the value, or write the +/// original bytes we recorded). +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Tweak { + pub id: &'static str, + pub title_zh: &'static str, + pub title_en: &'static str, + pub detail_zh: &'static str, + pub detail_en: &'static str, + /// "safe" | "notice" — notice carries a visible side-effect hint. + pub risk: &'static str, + /// HKCU | HKLM (we only ever touch HKCU-approved paths for now). + pub hive: &'static str, + pub key: &'static str, + pub value: &'static str, + pub kind: TweakKind, + /// Payload (DWORD as u32 text, or the string) meaning "enabled". + pub on: &'static str, + /// A restart / Explorer restart is needed to see the effect. + pub restart_hint: bool, +} + +/// The catalog — every entry verified on a real Windows 11 machine. +pub fn catalog() -> Vec { + vec![ + Tweak { + id: "transparency", + title_zh: "关闭透明效果", + title_en: "Turn off transparency", + detail_zh: "降低 GPU 合成负担,远程桌面里也更清晰", + detail_en: "Less compositor work; sharper over RDP", + risk: "safe", + hive: "HKCU", + key: r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", + value: "EnableTransparency", + kind: TweakKind::Dword, + on: "0", + restart_hint: false, + }, + Tweak { + id: "show-extensions", + title_zh: "资源管理器显示文件扩展名", + title_en: "Show file extensions", + detail_zh: "隐藏扩展名是误删与伪装文件事故的头号来源", + detail_en: "Hidden extensions cause mis-deletes and fake-file tricks", + risk: "safe", + hive: "HKCU", + key: r"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", + value: "HideFileExt", + kind: TweakKind::Dword, + on: "0", + restart_hint: false, + }, + Tweak { + id: "widgets-web", + title_zh: "关闭小组件 Web 内容", + title_en: "Disable Widgets web content", + detail_zh: "任务栏小组件不再拉取新闻,减少后台联网与内存", + detail_en: "Taskbar Widgets stops fetching news feeds", + risk: "safe", + hive: "HKCU", + key: r"Software\Microsoft\Windows\CurrentVersion\Feeds", + value: "ShellWebContentSystemProvisioning", + kind: TweakKind::Dword, + on: "0", + restart_hint: true, + }, + Tweak { + id: "location", + title_zh: "禁止位置同步", + title_en: "Disable location", + detail_zh: "应用不能再读取本机地理位置", + detail_en: "Apps can no longer read this device's location", + risk: "safe", + hive: "HKCU", + key: r"Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\location", + value: "Value", + kind: TweakKind::String, + on: "Deny", + restart_hint: false, + }, + Tweak { + id: "recent-files", + title_zh: "关闭「最近使用的文件」", + title_en: "Turn off recent files", + detail_zh: "资源管理器与快速访问不再记录最近文件(隐私+微量性能)", + detail_en: "Explorer stops logging recent files", + risk: "notice", + hive: "HKCU", + key: r"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", + value: "Start_TrackDocs", + kind: TweakKind::Dword, + on: "0", + restart_hint: true, + }, + ] +} + +pub fn find(id: &str) -> Option { + catalog().into_iter().find(|tweak| tweak.id == id) +} + +/// Row the UI sees: the tweak plus its live state and revert info. +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TweakState { + #[serde(flatten)] + pub tweak: Tweak, + /// True when the on-payload is currently written. + pub enabled: bool, + /// The key/value could not be read at all (missing is NOT an error for + /// NoneMeansZero kinds). + pub unreadable: bool, + /// An original value was recorded → revert is possible. + pub recorded: bool, +} + +/// Recorded originals, persisted beside the other app state. +#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] +pub struct TweakBackups { + /// tweak id → (kind marker + original payload text, or "absent") + pub originals: std::collections::HashMap, +} + +impl TweakBackups { + fn path() -> PathBuf { + Settings::config_dir().join("tweaks.json") + } + + pub fn load() -> TweakBackups { + std::fs::read_to_string(Self::path()) + .ok() + .and_then(|text| serde_json::from_str(&text).ok()) + .unwrap_or_default() + } + + fn save(&self) -> std::io::Result<()> { + let path = Self::path(); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write(path, serde_json::to_string_pretty(self).unwrap_or_default()) + } + + /// Record once: the FIRST original value is the one we restore to, no + /// matter how many times the user flips the switch afterwards. + fn record(&mut self, id: &str, original: String) -> std::io::Result<()> { + if self.originals.contains_key(id) { + return Ok(()); + } + self.originals.insert(id.to_string(), original); + self.save() + } +} + +#[cfg(windows)] +mod registry { + use super::{Tweak, TweakKind}; + use winreg::enums::{HKEY_CURRENT_USER, KEY_READ, KEY_WRITE}; + use winreg::RegKey; + + fn open(hive: &str) -> Result { + match hive { + "HKCU" => Ok(RegKey::predef(HKEY_CURRENT_USER)), + other => Err(format!("不支持的注册表根:{other}")), + } + } + + /// Read the current payload as text; Ok(None) = value absent. + pub fn read(tweak: &Tweak) -> Result, String> { + let root = open(tweak.hive)?; + let Ok(key) = root.open_subkey_with_flags(tweak.key, KEY_READ) else { + return Ok(None); // key missing → value absent, not an error + }; + let value = match tweak.kind { + TweakKind::String => key + .get_value::(tweak.value) + .map(Some) + .unwrap_or(None), + _ => key + .get_value::(tweak.value) + .map(|number| Some(number.to_string())) + .unwrap_or(None), + }; + Ok(value) + } + + /// Write the payload; missing key is created with minimal rights + /// (create_subkey would ask KEY_ALL_ACCESS and security software says no). + pub fn write(tweak: &Tweak, payload: &str) -> Result<(), String> { + let root = open(tweak.hive)?; + let key = root + .create_subkey_with_flags(tweak.key, KEY_READ | KEY_WRITE) + .map_err(|error| format!("无法打开 {}:{error}", tweak.key))? + .0; + match tweak.kind { + TweakKind::String => key + .set_value(tweak.value, &payload.to_string()) + .map_err(|error| error.to_string())?, + _ => { + let number: u32 = payload + .parse() + .map_err(|_| format!("不是合法的 DWORD:{payload}"))?; + key.set_value(tweak.value, &number) + .map_err(|error| error.to_string())?; + } + } + Ok(()) + } + + pub fn remove(tweak: &Tweak) -> Result<(), String> { + let root = open(tweak.hive)?; + if let Ok(key) = root.open_subkey_with_flags(tweak.key, KEY_READ | KEY_WRITE) { + let _ = key.delete_value(tweak.value); + } + Ok(()) + } +} + +#[cfg(not(windows))] +mod registry { + use super::Tweak; + pub fn read(_tweak: &Tweak) -> Result, String> { + Err("tweaks 仅在 Windows 提供".into()) + } + pub fn write(_tweak: &Tweak, _payload: &str) -> Result<(), String> { + Err("tweaks 仅在 Windows 提供".into()) + } + pub fn remove(_tweak: &Tweak) -> Result<(), String> { + Ok(()) + } +} + +pub fn states() -> Vec { + let backups = TweakBackups::load(); + catalog() + .into_iter() + .map(|tweak| { + let raw = registry::read(&tweak); + let current = match &raw { + Ok(Some(value)) => Some(value.clone()), + // Absent DWORDs read as their documented default 0. + Ok(None) if tweak.kind != TweakKind::String => Some("0".to_string()), + Ok(None) => None, + Err(_) => None, + }; + let enabled = current + .as_ref() + .is_some_and(|value| value.eq_ignore_ascii_case(tweak.on)); + TweakState { + tweak: tweak.clone(), + enabled, + unreadable: raw.is_err(), + recorded: backups.originals.contains_key(tweak.id), + } + }) + .collect() +} + +/// Flip one tweak. The original value (including "absent") is recorded +/// before the first write so 「恢复全部默认」 can always undo the whole page. +pub fn set(id: &str, enabled: bool) -> Result { + let tweak = find(id).ok_or_else(|| format!("未知的优化项:{id}"))?; + let mut backups = TweakBackups::load(); + let original = registry::read(&tweak)?; + // Absent DWORDs read as their documented default 0 for comparison. + let current = original + .clone() + .or((tweak.kind != TweakKind::String).then(|| "0".to_string())); + let already = current + .as_ref() + .is_some_and(|value| value.eq_ignore_ascii_case(tweak.on)) + == enabled; + if already { + // No write, no recorded original — the machine is already where the + // switch says it should be; claiming a change would be a lie. + } else if enabled { + backups + .record( + tweak.id, + original.clone().unwrap_or_else(|| "absent".into()), + ) + .map_err(|error| error.to_string())?; + registry::write(&tweak, tweak.on)?; + } else { + // Turning off explicitly = restore the recorded original. + restore_one(&mut backups, &tweak)?; + } + Ok(states() + .into_iter() + .find(|state| state.tweak.id == id) + .expect("catalog round-trips")) +} + +fn restore_one(backups: &mut TweakBackups, tweak: &Tweak) -> Result<(), String> { + match backups.originals.get(tweak.id) { + Some(original) if original == "absent" || original.is_empty() => { + registry::remove(tweak)?; + } + Some(original) => { + registry::write(tweak, original)?; + } + None => registry::remove(tweak)?, + } + backups.originals.remove(tweak.id); + backups.save().map_err(|error| error.to_string()) +} + +/// 「恢复全部默认」: every recorded tweak back to its original value. +pub fn restore_all() -> Vec { + let mut backups = TweakBackups::load(); + let mut restored = Vec::new(); + for tweak in catalog() { + if backups.originals.contains_key(tweak.id) && restore_one(&mut backups, &tweak).is_ok() { + restored.push(tweak.id.to_string()); + } + } + restored +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn catalog_ids_are_unique_and_prefixed_hkcu() { + let mut seen = std::collections::HashSet::new(); + for tweak in catalog() { + assert!(seen.insert(tweak.id), "duplicate {}", tweak.id); + assert_eq!(tweak.hive, "HKCU", "batch 1 stays user-hive only"); + assert!(!tweak.key.is_empty() && !tweak.value.is_empty()); + } + } + + #[test] + fn unknown_ids_are_rejected() { + assert!(find("delete-my-boot").is_none()); + assert!(set("delete-my-boot", true).is_err()); + } + + #[cfg(windows)] + #[test] + fn a_tweak_round_trips_through_the_registry() { + // A private scratch value under a key we own; registry access can be + // denied by endpoint protection in sandboxes, so skip politely then. + let probe = find("show-extensions").expect("catalog"); + let before = match registry::read(&probe) { + Ok(value) => value, + Err(error) => { + eprintln!("skipping: registry read denied ({error})"); + return; + } + }; + if registry::write(&probe, "1").is_err() { + eprintln!("skipping: registry write denied"); + return; + } + assert_eq!(registry::read(&probe).ok().flatten().as_deref(), Some("1")); + // Restore the machine to exactly how we found it. + match &before { + Some(value) => registry::write(&probe, value).expect("restore"), + None => registry::remove(&probe).expect("remove"), + } + assert_eq!(registry::read(&probe).ok().flatten(), before); + } +} diff --git a/crates/squid-platform/Cargo.toml b/crates/squid-platform/Cargo.toml index 09aa6be..4aaa7e4 100644 --- a/crates/squid-platform/Cargo.toml +++ b/crates/squid-platform/Cargo.toml @@ -21,6 +21,7 @@ libc.workspace = true [target.'cfg(windows)'.dependencies] winreg = "0.52" +serde_json.workspace = true sysinfo.workspace = true png = "0.17" windows-sys = { version = "0.59", features = ["Win32_System_Console", "Win32_Foundation", "Win32_Storage_FileSystem", "Win32_Security", "Win32_System_Threading", "Win32_System_Registry", "Win32_Globalization", "Win32_UI_WindowsAndMessaging", "Win32_UI_Shell", "Win32_Graphics_Gdi", "Win32_System_SystemInformation", "Win32_System_IO"] } diff --git a/crates/squid-platform/src/advanced.rs b/crates/squid-platform/src/advanced.rs new file mode 100644 index 0000000..aa25256 --- /dev/null +++ b/crates/squid-platform/src/advanced.rs @@ -0,0 +1,532 @@ +//! 进阶启动项 (advanced startup) — the Autoruns-shaped tail of the startup +//! story: Winlogon hooks, AppInit, IFEO debuggers, browser BHOs, and the +//! hidden corners of Task Scheduler and Services that ordinary listings +//! skip. Everything here can break boot or logon, so the contract is: +//! +//! * **display first** — the UI lists these read-mostly, with signature +//! trust and the exact registry location on every row; +//! * **disable is reversible** — the first disable records the original +//! value in `advanced-backup.json`; restoring puts the bytes back; +//! * hidden tasks and automatic services ride the *same* id scheme as the +//! normal startup list, so their toggles reuse the proven arms. +//! +//! Signature trust is a batched `Get-AuthenticodeSignature` PowerShell +//! call over the deduplicated exe set — one process, honest status +//! (微软 / 已知厂商 / 未签名 / 失效), no FFI. + +use serde::{Deserialize, Serialize}; + +/// One advanced row. `kind` decides how disabling works. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AdvancedEntry { + /// `adv||||` (or task/service ids for the + /// reused arms). + pub id: String, + pub kind: String, + pub name: String, + /// Registry command line or task/service target. + pub command: String, + /// Human location, e.g. `HKLM\…\Winlogon\Userinit`. + pub location: String, + pub scope: String, + pub enabled: bool, + /// Digital-signature verdict: `microsoft` | `vendor` | `unsigned` | + /// `invalid` | `unknown` (no exe resolvable / non-Windows). + pub signature: String, + /// Subject of the signing certificate when known. + pub signer: Option, + /// A warning the UI must show: IFEO hijacks a program, Winlogon is + /// boot-critical, etc. + pub warning: Option, +} + +#[cfg(windows)] +mod windows { + use super::AdvancedEntry; + use std::path::PathBuf; + use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ}; + use winreg::RegKey; + + const WINLOGON: &str = r"Software\Microsoft\Windows NT\CurrentVersion\Winlogon"; + const IFEO: &str = r"Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options"; + + fn hive(machine: bool) -> RegKey { + RegKey::predef(if machine { + HKEY_LOCAL_MACHINE + } else { + HKEY_CURRENT_USER + }) + } + + fn read_string(key: &RegKey, path: &str, value: &str) -> Option { + key.open_subkey_with_flags(path, KEY_READ) + .ok()? + .get_value::(value) + .ok() + .map(|text| text.trim().to_string()) + .filter(|text| !text.is_empty()) + } + + /// Strip quotes and arguments from a registry command to reach the exe. + pub(crate) fn exe_of(command: &str) -> Option { + let text = command.trim(); + if let Some(rest) = text.strip_prefix('"') { + return rest.split('"').next().map(str::to_string); + } + // Up to the first `.exe` boundary, else the first whitespace token. + if let Some(end) = text.to_ascii_lowercase().find(".exe") { + return Some(text[..end + 4].to_string()); + } + text.split_whitespace().next().map(str::to_string) + } + + fn winlogon_entries(out: &mut Vec) { + for (machine, hive_label) in [(true, "HKLM"), (false, "HKCU")] { + let root = hive(machine); + for (value, meaning) in [ + ("Shell", "登录外壳(正常情况下只有 explorer.exe)"), + ( + "Userinit", + "登录初始化链(正常情况下以 userinit.exe, 结尾)", + ), + ] { + let Some(text) = read_string(&root, WINLOGON, value) else { + continue; + }; + // The pristine value is a bare system component; anything + // extra rides alongside and is worth a warning. + let clean = text.split(',').all(|part| { + let part = part.trim().to_ascii_lowercase(); + part.is_empty() + || part + .replace("%systemroot%", "") + .replace("\\system32\\", "") + .starts_with(if value == "Shell" { + "explorer.exe" + } else { + "userinit.exe" + }) + }); + out.push(AdvancedEntry { + id: format!("adv|winlogon|{hive_label}|{WINLOGON}|{value}"), + kind: "winlogon".into(), + name: format!("Winlogon {value}"), + command: text, + location: format!("{hive_label}\\{WINLOGON} · {value}"), + scope: if machine { "machine" } else { "currentUser" }.into(), + enabled: true, + signature: "unknown".into(), + signer: None, + warning: (!clean) + .then(|| format!("{meaning};存在附加程序,请确认是否认识")) + .or_else(|| Some(format!("{meaning};改动需重启生效"))), + }); + } + } + } + + fn appinit_entries(out: &mut Vec) { + const KEY: &str = r"Software\Microsoft\Windows NT\CurrentVersion\Windows"; + for (machine, hive_label) in [(true, "HKLM"), (false, "HKCU")] { + let root = hive(machine); + let enabled = read_string(&root, KEY, "LoadAppInit_DLLs").as_deref() == Some("1"); + let Some(dlls) = read_string(&root, KEY, "AppInit_DLLs") else { + continue; + }; + out.push(AdvancedEntry { + id: format!("adv|appinit|{hive_label}|{KEY}|AppInit_DLLs"), + kind: "appinit".into(), + name: "AppInit_DLLs 全局注入".to_string(), + command: dlls, + location: format!("{hive_label}\\{KEY}"), + scope: if machine { "machine" } else { "currentUser" }.into(), + enabled, + signature: "unknown".into(), + signer: None, + warning: Some("每个 GUI 进程都会加载这些 DLL;除非认识每一个,否则保持关闭".into()), + }); + } + } + + fn ifeo_entries(out: &mut Vec) { + for (machine, hive_label) in [(true, "HKLM"), (false, "HKCU")] { + let root = hive(machine); + let Ok(ifeo) = root.open_subkey_with_flags(IFEO, KEY_READ) else { + continue; + }; + for name in ifeo.enum_keys().flatten() { + let Some(debugger) = read_string(&ifeo, &name, "Debugger") else { + continue; + }; + // A Debugger replaces the program's launch entirely — the + // classic persistence trick. Only flag non-microsoft ones. + let lower = debugger.to_ascii_lowercase(); + if lower.contains("mseone") + || lower.contains("hybridlaunch") + || lower.contains("msedge.exe --profile-directory") + { + continue; // Edge/IE protocol handlers live here legitimately + } + out.push(AdvancedEntry { + id: format!("adv|ifeo|{hive_label}|{IFEO}\\{name}|Debugger"), + kind: "ifeo".into(), + name: format!("{name} 被调试器接管"), + command: debugger, + location: format!("{hive_label}\\{IFEO}\\{name} · Debugger"), + scope: if machine { "machine" } else { "currentUser" }.into(), + enabled: true, + signature: "unknown".into(), + signer: None, + warning: Some(format!( + "启动 {name} 会先启动调试器;安全软件常用,也可能是流氓持久化" + )), + }); + } + } + } + + fn bho_entries(out: &mut Vec) { + const BHO: &str = + r"Software\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects"; + let root = hive(true); + let Ok(bho) = root.open_subkey_with_flags(BHO, KEY_READ) else { + return; + }; + for clsid in bho.enum_keys().flatten() { + let module = read_string(&root, &format!(r"Classes\{clsid}\InprocServer32"), ""); + let friendly = read_string(&root, &format!(r"Classes\{clsid}"), ""); + let load = bho + .open_subkey_with_flags(&clsid, KEY_READ) + .ok() + .and_then(|key| key.get_value::("LoadBehavior").ok()) + .unwrap_or(3); + out.push(AdvancedEntry { + id: format!("adv|bho|HKLM|{BHO}\\{clsid}|LoadBehavior"), + kind: "bho".into(), + name: friendly.unwrap_or_else(|| clsid.clone()), + command: module.unwrap_or_else(|| clsid.clone()), + location: format!("HKLM\\{BHO}\\{clsid} · LoadBehavior"), + scope: "machine".into(), + enabled: load & 1 != 0, + signature: "unknown".into(), + signer: None, + warning: Some("浏览器加载项(IE 模式);现代浏览器大多不再使用".into()), + }); + } + } + + pub fn scan() -> Vec { + let mut out = Vec::new(); + winlogon_entries(&mut out); + appinit_entries(&mut out); + ifeo_entries(&mut out); + bho_entries(&mut out); + enrich_signatures(&mut out); + out + } + + /// Signature trust is a batch pass: collect the unique exes, grade them + /// all in one PowerShell call, then stamp every entry from the map. + fn enrich_signatures(entries: &mut [AdvancedEntry]) { + let mut exes: Vec = Vec::new(); + for entry in entries.iter_mut() { + if let Some(exe) = exe_of(&entry.command).filter(|path| PathBuf::from(path).exists()) { + if !exes.iter().any(|seen| seen.eq_ignore_ascii_case(&exe)) { + exes.push(exe); + } + entry.signature = "pending".into(); + } + } + if exes.is_empty() { + return; + } + let list = exes + .iter() + .map(|exe| format!("'{}'", exe.replace('\'', "''"))) + .collect::>() + .join(","); + let script = format!( + "$ErrorActionPreference='SilentlyContinue'; {list} | ForEach-Object {{ $s = Get-AuthenticodeSignature -FilePath $_; \"@@|$_|$($s.Status)|$($s.SignerCertificate.Subject)\" }} | Out-String -Width 4096" + ); + let Ok(output) = std::process::Command::new("powershell.exe") + .args(["-NoProfile", "-NonInteractive", "-Command", &script]) + .output() + else { + return; + }; + let text = String::from_utf8_lossy(&output.stdout); + let mut grades: std::collections::HashMap)> = + Default::default(); + for line in text.lines() { + // Out-String may pad lines; match on containment of the marker. + let Some(start) = line.find("@@|") else { + continue; + }; + let rest = &line[start + 3..]; + let mut parts = rest.splitn(3, '|'); + let (Some(path), Some(status)) = (parts.next(), parts.next()) else { + continue; + }; + let subject = parts.next().unwrap_or_default().to_string(); + let signer = subject + .split("CN=") + .nth(1) + .map(|tail| tail.split(',').next().unwrap_or(tail).to_string()) + .filter(|name| !name.is_empty()); + let verdict = match status { + "Valid" => match &signer { + Some(name) if name.contains("Microsoft") || name.contains("Windows") => { + "microsoft" + } + Some(_) => "vendor", + None => "vendor", + }, + "NotSigned" => "unsigned", + "HashMismatch" | "NotTrusted" | "CertificateExpired" | "UnknownError" + | "Missing" => "invalid", + _ => "unknown", + }; + grades.insert(path.to_ascii_lowercase(), (verdict.into(), signer)); + } + for entry in entries.iter_mut() { + let Some(exe) = exe_of(&entry.command) else { + continue; + }; + if let Some((verdict, signer)) = grades.get(&exe.to_ascii_lowercase()) { + entry.signature = verdict.clone(); + entry.signer = signer.clone(); + } else if entry.signature == "pending" { + entry.signature = "unknown".into(); + } + } + } +} + +#[cfg(not(windows))] +mod windows { + use super::AdvancedEntry; + pub fn scan() -> Vec { + Vec::new() + } +} + +pub fn scan_advanced() -> Vec { + #[cfg(windows)] + { + windows::scan() + } + #[cfg(not(windows))] + { + Vec::new() + } +} + +/// Disable/enable one advanced entry. Winlogon/AppInit/IFEO/BHO write +/// registry values (original recorded on first disable); tasks and services +/// are not handled here — the caller routes them through `set_startup_enabled` +/// because their ids use the ordinary scheme. +pub fn set_advanced_enabled(entry: &AdvancedEntry, enabled: bool) -> Result<(), String> { + #[cfg(windows)] + { + windows_set(entry, enabled) + } + #[cfg(not(windows))] + { + let _ = (entry, enabled); + Err("进阶启动项管理仅在 Windows 提供".into()) + } +} + +#[cfg(windows)] +fn windows_set(entry: &AdvancedEntry, enabled: bool) -> Result<(), String> { + use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE}; + use winreg::RegKey; + + // id shape: adv|kind|HIVELABEL|key|value + let parts: Vec<&str> = entry.id.splitn(5, '|').collect(); + if parts.len() != 5 { + return Err("无法解析的进阶项 id".into()); + } + let (hive_label, key_path, value_name) = (parts[2], parts[3], parts[4]); + let root = RegKey::predef(if hive_label == "HKLM" { + HKEY_LOCAL_MACHINE + } else { + HKEY_CURRENT_USER + }); + let mut backups = Backups::load(); + match entry.kind.as_str() { + "winlogon" => { + let original = read_raw(&root, key_path, value_name)?; + if enabled { + let restore = backups + .originals + .get(&entry.id) + .cloned() + .unwrap_or_else(|| match value_name { + "Shell" => "explorer.exe".to_string(), + _ => r"C:\Windows\system32\userinit.exe,".to_string(), + }); + write_raw(&root, key_path, value_name, &restore)?; + backups.originals.remove(&entry.id); + } else { + // Keep the mandatory piece, drop the third-party tail. + let kept: Vec<&str> = original + .split(',') + .map(str::trim) + .filter(|part| !part.is_empty()) + .filter(|part| { + let lower = part.to_ascii_lowercase(); + lower.contains("explorer.exe") || lower.contains("userinit.exe") + }) + .collect(); + let joined = kept.join(","); + if joined != original { + backups + .originals + .entry(entry.id.clone()) + .or_insert_with(|| original.clone()); + } + write_raw(&root, key_path, value_name, &joined)?; + } + } + "appinit" => { + backups + .originals + .entry(entry.id.clone()) + .or_insert_with(|| if enabled { "1".into() } else { "0".into() }); + write_dword( + &root, + key_path, + "LoadAppInit_DLLs", + if enabled { 1 } else { 0 }, + )?; + } + "ifeo" => { + let original = read_raw(&root, key_path, value_name)?; + if enabled { + let restore = backups + .originals + .get(&entry.id) + .cloned() + .unwrap_or_else(|| original.clone()); + write_raw(&root, key_path, value_name, &restore)?; + backups.originals.remove(&entry.id); + } else { + backups.originals.insert(entry.id.clone(), original); + delete_value(&root, key_path, value_name)?; + } + } + "bho" => { + write_dword(&root, key_path, "LoadBehavior", if enabled { 3 } else { 0 })?; + } + other => return Err(format!("不支持的进阶类型:{other}")), + } + backups.save() +} + +#[cfg(windows)] +fn read_raw(root: &winreg::RegKey, key: &str, value: &str) -> Result { + use winreg::enums::KEY_READ; + Ok(root + .open_subkey_with_flags(key, KEY_READ) + .map_err(|error| error.to_string())? + .get_value::(value) + .unwrap_or_default()) +} + +#[cfg(windows)] +fn write_raw(root: &winreg::RegKey, key: &str, value: &str, text: &str) -> Result<(), String> { + use winreg::enums::{KEY_READ, KEY_WRITE}; + root.create_subkey_with_flags(key, KEY_READ | KEY_WRITE) + .map_err(|error| error.to_string())? + .0 + .set_value(value, &text.to_string()) + .map_err(|error| error.to_string()) +} + +#[cfg(windows)] +fn write_dword(root: &winreg::RegKey, key: &str, value: &str, number: u32) -> Result<(), String> { + use winreg::enums::{KEY_READ, KEY_WRITE}; + root.create_subkey_with_flags(key, KEY_READ | KEY_WRITE) + .map_err(|error| error.to_string())? + .0 + .set_value(value, &number) + .map_err(|error| error.to_string()) +} + +#[cfg(windows)] +fn delete_value(root: &winreg::RegKey, key: &str, value: &str) -> Result<(), String> { + use winreg::enums::{KEY_READ, KEY_WRITE}; + root.open_subkey_with_flags(key, KEY_READ | KEY_WRITE) + .map_err(|error| error.to_string())? + .delete_value(value) + .map_err(|error| error.to_string()) +} + +/// Original values for disabled advanced entries (restore data). +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +struct Backups { + originals: std::collections::HashMap, +} + +impl Backups { + #[cfg(windows)] + fn path() -> std::path::PathBuf { + squid_core::Settings::config_dir().join("advanced-backup.json") + } + + #[cfg(windows)] + fn load() -> Backups { + std::fs::read_to_string(Self::path()) + .ok() + .and_then(|text| serde_json::from_str(&text).ok()) + .unwrap_or_default() + } + + #[cfg(windows)] + fn save(&self) -> Result<(), String> { + let path = Self::path(); + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + std::fs::write( + &path, + serde_json::to_string_pretty(self).unwrap_or_default(), + ) + .map_err(|error| error.to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn scan_runs_and_ids_are_prefixed() { + // Real-machine smoke test: the scan must never panic and every id + // must carry the adv| prefix the parser in set_advanced_enabled + // depends on. + for entry in scan_advanced() { + assert!(entry.id.starts_with("adv|"), "{}", entry.id); + assert!(!entry.location.is_empty()); + } + } + + #[cfg(windows)] + #[test] + fn exe_extraction_handles_quotes_and_arguments() { + assert_eq!( + windows::exe_of(r#""C:\Program Files\Tool\warp.exe" --quiet""#.as_ref()).as_deref(), + Some(r"C:\Program Files\Tool\warp.exe") + ); + assert_eq!( + windows::exe_of(r"C:\Windows\System32\userinit.exe,").as_deref(), + Some(r"C:\Windows\System32\userinit.exe") + ); + assert_eq!( + windows::exe_of("mscandui.dll"), + Some("mscandui.dll".to_string()) + ); + } +} diff --git a/crates/squid-platform/src/lib.rs b/crates/squid-platform/src/lib.rs index 3f68ad6..791840e 100644 --- a/crates/squid-platform/src/lib.rs +++ b/crates/squid-platform/src/lib.rs @@ -10,6 +10,7 @@ use squid_core::progress::CancelToken; use squid_core::{AppInfo, Bytes, Volume}; use std::path::{Path, PathBuf}; +pub mod advanced; pub mod apps; pub mod console; pub mod currency; diff --git a/src-tauri/src/app.rs b/src-tauri/src/app.rs index e8a3c0e..799fc9c 100644 --- a/src-tauri/src/app.rs +++ b/src-tauri/src/app.rs @@ -926,6 +926,104 @@ pub async fn maintenance_run( Ok(outcome) } +/// Privacy traces scan: rows never pre-selected, running browsers locked. +#[tauri::command] +pub async fn privacy_scan(app: AppHandle, job_id: String) -> Result { + let token = app.state::().begin(&job_id)?; + let progress = Progress::new(); + let reporter = + ProgressReporter::start(app.clone(), job_id.clone(), "privacy", progress.clone()); + let started = Instant::now(); + let task = tauri::async_runtime::spawn_blocking(move || { + let engine = Engine::new(); + let items = squid_engine::privacy::collect(&engine, &token); + Ok::(ScanReport { + items, + scanned_at_ms: 0, + ..Default::default() + }) + }) + .await + .map_err(|error| format!("Privacy scan failed: {error}"))?; + reporter.finish(); + app.state::().finish(&job_id); + let report = task.map_err(|error| error.to_string())?; + let view = scan_view( + job_id.clone(), + &report, + started.elapsed().as_millis() as u64, + ); + app.state::() + .scans + .lock() + .map_err(|_| "The scan cache is unavailable.".to_string())? + .insert(job_id, report); + Ok(view) +} + +/// Privacy deletes are permanent by design (a bin-restored browser profile +/// is broken worse than a clean one) but land in the same history ledger. +#[tauri::command] +pub async fn privacy_delete( + app: AppHandle, + job_id: String, + scan_id: String, + selected: Vec, +) -> Result { + let token = app.state::().begin(&job_id)?; + let mut report = app + .state::() + .scans + .lock() + .map_err(|_| "The scan cache is unavailable.".to_string())? + .get(&scan_id) + .cloned() + .ok_or_else(|| "This scan has expired. Run it again.".to_string())?; + select_indices(&mut report, &selected)?; + let items = report.items; + let progress = Progress::new(); + let reporter = ProgressReporter::start(app.clone(), job_id.clone(), "delete", progress.clone()); + let task = tauri::async_runtime::spawn_blocking(move || { + let engine = Engine::new(); + let job = DeleteJob::new(items, DeleteMode::Permanent, "Squid · Privacy"); + delete::execute(&engine, &job, &progress, &token) + }) + .await + .map_err(|error| format!("Privacy clean failed: {error}"))?; + reporter.finish(); + app.state::().finish(&job_id); + let outcome = task.map_err(|error| error.to_string())?; + if let Ok(mut scans) = app.state::().scans.lock() { + scans.remove(&scan_id); + } + Ok(DeleteResultView::from_outcome(outcome)) +} + +/// Optimisation tweaks: catalog + live state; writes record the original. +#[tauri::command] +pub async fn tweaks_states() -> Result, String> { + tauri::async_runtime::spawn_blocking(squid_engine::tweaks::states) + .await + .map_err(|error| error.to_string()) +} + +#[tauri::command] +pub async fn tweaks_set( + id: String, + enabled: bool, +) -> Result { + tauri::async_runtime::spawn_blocking(move || squid_engine::tweaks::set(&id, enabled)) + .await + .map_err(|error| error.to_string())? +} + +#[tauri::command] +pub async fn tweaks_restore_all() -> Result, String> { + tauri::async_runtime::spawn_blocking(squid_engine::tweaks::restore_all) + .await + .map_err(|error| error.to_string()) +} + #[derive(Clone, serde::Serialize)] pub struct AppEntry { #[serde(flatten)] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 507cf3a..55fcae2 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -131,6 +131,11 @@ pub fn run() { app::large_files_delete, app::maintenance_tasks, app::maintenance_run, + app::privacy_scan, + app::privacy_delete, + app::tweaks_states, + app::tweaks_set, + app::tweaks_restore_all, app::apps_scan, app::app_plan, app::app_uninstall, @@ -152,6 +157,8 @@ pub fn run() { permissions::open_full_disk_access_settings, manage::manage_scan, manage::startup_set_enabled, + manage::advanced_scan, + manage::advanced_set_enabled, manage::extension_set_registered, manage::popup_list, manage::popup_close, diff --git a/src-tauri/src/manage.rs b/src-tauri/src/manage.rs index 999fce3..f3eba50 100644 --- a/src-tauri/src/manage.rs +++ b/src-tauri/src/manage.rs @@ -335,6 +335,94 @@ pub async fn startup_set_enabled( Ok(enabled_count) } +// ---- 进阶启动项 (advanced startup) ---------------------------------------- + +/// One advanced row for the UI: registry hooks with signature trust, plus +/// the hidden-task / auto-service tails merged from the ordinary scan. +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AdvancedView { + id: String, + kind: String, + name: String, + command: String, + location: String, + scope: String, + enabled: bool, + signature: String, + signer: Option, + warning: Option, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AdvancedScanView { + entries: Vec, + /// Hidden scheduled tasks and automatic services, in the ordinary + /// startup shape so their toggles reuse `startup_set_enabled`. + extras: Vec, +} + +#[tauri::command] +pub async fn advanced_scan(app: AppHandle) -> Result { + let manage = app.state::(); + let (entries, startup) = tauri::async_runtime::spawn_blocking(|| { + ( + squid_platform::advanced::scan_advanced(), + permissions::scan_startup_entries(), + ) + }) + .await + .map_err(|error| format!("进阶扫描失败:{error}"))?; + // Cache the ordinary scan so the extras' toggles can find their entries. + *ManageState::lock(&manage.startup)? = startup.clone(); + let extras: Vec = startup + .iter() + .filter(|entry| { + // Only the corners the plain list does not already show: + // hidden-by-default vendor tasks (source marks) and services. + entry.source == "service" + }) + .map(StartupView::from) + .collect(); + Ok(AdvancedScanView { + entries: entries + .iter() + .map(|entry| AdvancedView { + id: entry.id.clone(), + kind: entry.kind.clone(), + name: entry.name.clone(), + command: entry.command.clone(), + location: entry.location.clone(), + scope: entry.scope.clone(), + enabled: entry.enabled, + signature: entry.signature.clone(), + signer: entry.signer.clone(), + warning: entry.warning.clone(), + }) + .collect(), + extras, + }) +} + +#[tauri::command] +pub async fn advanced_set_enabled(app: AppHandle, id: String, enabled: bool) -> Result<(), String> { + let manage = app.state::(); + // Advanced rows carry their whole state in the id + a fresh scan match. + let entry = tauri::async_runtime::spawn_blocking(squid_platform::advanced::scan_advanced) + .await + .map_err(|error| error.to_string())? + .into_iter() + .find(|entry| entry.id == id) + .ok_or_else(|| "该进阶项已不存在,请重新扫描".to_string())?; + tauri::async_runtime::spawn_blocking(move || { + squid_platform::advanced::set_advanced_enabled(&entry, enabled) + }) + .await + .map_err(|error| error.to_string())??; + Ok(()) +} + /// Unregister / restore a context-menu handler. Removal keeps the entry in /// `manage.json`, which is both the restore recipe and the audit trail. #[tauri::command] diff --git a/src/App.tsx b/src/App.tsx index 158d50d..ec1d761 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -5,6 +5,7 @@ import { CircleGauge, CopyX, Eraser, + EyeOff, FileArchive, History, LayoutDashboard, @@ -12,6 +13,7 @@ import { RefreshCw, Settings, ShieldCheck, + SlidersHorizontal, Sparkles, Wrench, } from "lucide-react"; @@ -39,8 +41,10 @@ import { DuplicateFilesPage } from "./pages/DuplicateFilesPage"; import { HistoryPage } from "./pages/HistoryPage"; import { LargeFilesPage } from "./pages/LargeFilesPage"; import { MaintenancePage } from "./pages/MaintenancePage"; +import { OptimizationPage } from "./pages/OptimizationPage"; import { OverviewPage } from "./pages/OverviewPage"; import { PermissionsPage } from "./pages/PermissionsPage"; +import { PrivacyPage } from "./pages/PrivacyPage"; import { SettingsPage } from "./pages/SettingsPage"; import { SpacePage } from "./pages/SpacePage"; import { StoragePage } from "./pages/StoragePage"; @@ -133,6 +137,18 @@ const NAV_GROUPS: { labelZh: "桌面小工具", icon: MonitorSmartphone, }, + { + id: "privacy", + labelEn: "Privacy cleaning", + labelZh: "隐私清理", + icon: EyeOff, + }, + { + id: "optimization", + labelEn: "System optimisation", + labelZh: "系统优化", + icon: SlidersHorizontal, + }, ], }, ]; @@ -294,13 +310,16 @@ export default function App() { "space", "applications", "permissions", + "maintenance", "storage", + "duplicates", + "large-files", "system", "widget", "history", "settings", ]; - // Ctrl/Cmd+1..9 map in navigation order. + // Ctrl/Cmd+1..9 map to the first nine pages in order; 0 opens the widget. const onKey = (event: KeyboardEvent) => { if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return; const index = event.key === "0" ? 9 : Number(event.key) - 1; @@ -393,6 +412,8 @@ export default function App() { {page === "duplicates" ? : null} {page === "large-files" ? : null} {page === "maintenance" ? : null} + {page === "privacy" ? : null} + {page === "optimization" ? : null} {page === "system" ? ( void; view: ManageView | null; windows: PopupWindowItem[]; + /** Advanced startup rows; scanned lazily the first time the tab opens — + * the signature batch call is not something the plain page should pay. */ + advanced: AdvancedScanResult | null; + advancedScanning: boolean; scanning: boolean; busyId: string | null; error: string | null; @@ -18,10 +22,12 @@ export interface PermissionsWorkspace { closedTotal: number; recentClosed: { process: string; title: string }[]; scan: () => Promise; + scanAdvanced: () => Promise; refreshWindows: () => Promise; toggleStartup: (id: string, enabled: boolean) => Promise; /** 电脑管家's master switch: flip every entry of one software group. */ toggleStartupGroup: (ids: string[], enabled: boolean) => Promise; + toggleAdvanced: (id: string, enabled: boolean) => Promise; toggleExtension: (id: string, registered: boolean) => Promise; addRule: (hwnd: number, matcher: "exact" | "contains") => Promise; toggleRule: (index: number, enabled: boolean) => Promise; @@ -33,6 +39,8 @@ export interface PermissionsWorkspace { export function usePermissionsWorkspace(active: boolean): PermissionsWorkspace { const [tab, setTab] = useState("startup"); const [view, setView] = useState(null); + const [advanced, setAdvanced] = useState(null); + const [advancedScanning, setAdvancedScanning] = useState(false); const [windows, setWindows] = useState([]); const [scanning, setScanning] = useState(false); const [busyId, setBusyId] = useState(null); @@ -64,10 +72,28 @@ export function usePermissionsWorkspace(active: boolean): PermissionsWorkspace { } }, []); + const scanAdvanced = useCallback(async () => { + setAdvancedScanning(true); + setError(null); + try { + setAdvanced(await api.advancedScan()); + } catch (reason) { + if (!isCancelled(reason)) setError(messageFrom(reason)); + } finally { + setAdvancedScanning(false); + } + }, []); + useEffect(() => { if (active && !view && !scanning) void scan(); }, [active, scan, view, scanning]); + // Lazy first load for the advanced tab: the PowerShell signature batch + // runs once, when the user actually opens that tab. + useEffect(() => { + if (active && tab === "advanced" && !advanced && !advancedScanning) void scanAdvanced(); + }, [active, advanced, advancedScanning, scanAdvanced, tab]); + useEffect(() => { if (!active) return; let stop: (() => void) | null = null; @@ -143,6 +169,24 @@ export function usePermissionsWorkspace(active: boolean): PermissionsWorkspace { [push, scan], ); + const toggleAdvanced = useCallback( + async (id: string, enabled: boolean) => { + setBusyId(id); + setError(null); + try { + await api.advancedSetEnabled(id, enabled); + setAdvanced(await api.advancedScan()); + } catch (reason) { + const why = messageFrom(reason); + setError(why); + push(why, "danger"); + } finally { + setBusyId(null); + } + }, + [push], + ); + const toggleExtension = useCallback( async (id: string, registered: boolean) => { setBusyId(id); @@ -236,6 +280,8 @@ export function usePermissionsWorkspace(active: boolean): PermissionsWorkspace { setTab, view, windows, + advanced, + advancedScanning, scanning, busyId, error, @@ -243,9 +289,11 @@ export function usePermissionsWorkspace(active: boolean): PermissionsWorkspace { closedTotal, recentClosed, scan, + scanAdvanced, refreshWindows, toggleStartup, toggleStartupGroup, + toggleAdvanced, toggleExtension, addRule, toggleRule, diff --git a/src/lib/api.ts b/src/lib/api.ts index c293de6..3573aef 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -2,6 +2,7 @@ import { invoke } from "@tauri-apps/api/core"; import { listen, type UnlistenFn } from "@tauri-apps/api/event"; import type { AppsResult, + AdvancedScanResult, Bootstrap, DeleteMode, DeleteResult, @@ -24,6 +25,7 @@ import type { SettingsView, SpaceInsight, SystemSnapshot, + TweakState, UndoResult, UpdateCheckResult, UpdateProgress, @@ -85,6 +87,12 @@ export const api = { maintenanceTasks: () => invoke("maintenance_tasks"), maintenanceRun: (jobId: string, task: string) => invoke("maintenance_run", { jobId, task }), + privacyScan: (jobId: string) => invoke("privacy_scan", { jobId }), + privacyDelete: (jobId: string, scanId: string, selected: number[]) => + invoke("privacy_delete", { jobId, scanId, selected }), + tweaksStates: () => invoke("tweaks_states"), + tweaksSet: (id: string, enabled: boolean) => invoke("tweaks_set", { id, enabled }), + tweaksRestoreAll: () => invoke("tweaks_restore_all"), appsScan: (jobId: string) => invoke("apps_scan", { jobId }), appPlan: (jobId: string, appKey: string) => invoke("app_plan", { jobId, appKey }), appUninstall: (jobId: string, planId: string, selected: number[], mode: DeleteMode) => @@ -112,6 +120,9 @@ export const api = { manageScan: () => invoke("manage_scan"), startupSetEnabled: (id: string, enabled: boolean) => invoke("startup_set_enabled", { id, enabled }), + advancedScan: () => invoke("advanced_scan"), + advancedSetEnabled: (id: string, enabled: boolean) => + invoke("advanced_set_enabled", { id, enabled }), extensionSetRegistered: (id: string, registered: boolean) => invoke("extension_set_registered", { id, registered }), popupList: () => invoke("popup_list"), diff --git a/src/pages/OptimizationPage.tsx b/src/pages/OptimizationPage.tsx new file mode 100644 index 0000000..32f18b2 --- /dev/null +++ b/src/pages/OptimizationPage.tsx @@ -0,0 +1,123 @@ +import { RotateCcw, SlidersHorizontal } from "lucide-react"; +import { useCallback, useEffect, useState } from "react"; +import { api } from "../lib/api"; +import { useI18n } from "../i18n"; +import { messageFrom } from "../lib/format"; +import { Button, InlineError, PageHeader, Toggle, useToast } from "../components/ui"; +import type { TweakState } from "../types"; + +export function OptimizationPage() { + const { t, lang } = useI18n(); + const { push } = useToast(); + const [states, setStates] = useState([]); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(null); + + const refresh = useCallback(async () => { + try { + setStates(await api.tweaksStates()); + } catch (reason) { + setError(messageFrom(reason)); + } + }, []); + + useEffect(() => { + void refresh(); + }, [refresh]); + + const flip = async (tweak: TweakState, next: boolean) => { + setBusy(tweak.id); + setError(null); + try { + const state = await api.tweaksSet(tweak.id, next); + setStates((current) => current.map((row) => (row.id === state.id ? state : row))); + } catch (reason) { + setError(messageFrom(reason)); + } finally { + setBusy(null); + } + }; + + const changed = states.filter((state) => state.recorded).length; + + const restoreAll = async () => { + setBusy("__all__"); + try { + const restored = await api.tweaksRestoreAll(); + push( + lang === "zh" + ? `已恢复 ${restored.length} 项为系统默认值` + : `Restored ${restored.length} tweaks to system defaults`, + "success", + ); + await refresh(); + } catch (reason) { + setError(messageFrom(reason)); + } finally { + setBusy(null); + } + }; + + return ( +
+ } disabled={busy !== null || changed === 0} onClick={() => void restoreAll()}> + {t("Restore all defaults", "恢复全部默认")} + + } + /> + {error ? setError(null)} /> : null} + +
+
+

+ {t("Everyday privacy & clarity", "常用隐私与界面")} +

+ + {changed > 0 + ? t(`${changed} changed · revertable`, `已更改 ${changed} 项 · 可随时恢复`) + : t("Nothing changed yet", "尚未更改任何项")} + +
+
    + {states.map((state) => ( +
  • +
    + + {lang === "zh" ? state.titleZh : state.titleEn} + {state.restartHint && state.enabled ? ( + + {t("needs Explorer/Windows restart", "需重启 Explorer/系统生效")} + + ) : null} + + {lang === "zh" ? state.detailZh : state.detailEn} + + {state.hive}\\{state.key} · {state.value} + +
    + + {state.risk === "safe" ? t("Safe", "安全") : t("Read the note", "看说明")} + + void flip(state, next)} + label={lang === "zh" ? state.titleZh : state.titleEn} + /> +
  • + ))} +
+ {states.length === 0 && !error ? ( +

{t("Loading the catalog…", "正在加载目录…")}

+ ) : null} +
+
+ ); +} diff --git a/src/pages/PermissionsPage.tsx b/src/pages/PermissionsPage.tsx index ee0c078..ced2aa1 100644 --- a/src/pages/PermissionsPage.tsx +++ b/src/pages/PermissionsPage.tsx @@ -49,19 +49,28 @@ export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace id: "startup" as const, label: t("Startup items", "开机启动项"), count: view?.startupCount ?? 0, + fresh: false, }, { id: "extensions" as const, label: t("Context menus", "右键菜单"), count: view?.extensions.length ?? 0, + fresh: false, + }, + { + id: "advanced" as const, + label: t("Advanced startup", "进阶启动项"), + count: workspace.advanced?.entries.length ?? 0, + fresh: true, }, { id: "popup" as const, label: t("Popup blocker", "弹窗拦截"), count: view?.rules.length ?? 0, + fresh: false, }, ], - [t, view], + [t, view, workspace.advanced], ); if (!view && workspace.scanning) { @@ -386,6 +395,112 @@ export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace ) : null} + {workspace.tab === "advanced" ? ( +
+
+ {t( + "Advanced rows can break boot or logon if changed carelessly — Squid only displays them here, every change records its original value, and nothing is auto-disabled.", + "进阶区的项目改错了可能影响系统行为——默认只展示不勾选,每一项带数字签名与位置说明;改动会原样记录,可逐项恢复。", + )} +
+ {workspace.advancedScanning && !workspace.advanced ? ( +
+ + + {t( + "Reading Winlogon / IFEO / BHO and verifying signatures…", + "正在读取 Winlogon / IFEO / BHO 并核验数字签名…", + )} + +
+ ) : null} + {workspace.advanced && workspace.advanced.entries.length === 0 ? ( +

+ {t( + "No third-party Winlogon hooks, AppInit DLLs, IFEO debuggers or BHOs found — the machine is clean.", + "没有发现第三方 Winlogon 挂钩、AppInit DLL、IFEO 调试器或 BHO——系统很干净。", + )} +

+ ) : null} + {workspace.advanced + ? (["winlogon", "appinit", "ifeo", "bho"] as const).map((kind) => { + const rows = workspace.advanced!.entries.filter((entry) => entry.kind === kind); + if (rows.length === 0) return null; + const titles: Record = { + winlogon: ["Winlogon hooks", "Winlogon 与登录链"], + appinit: ["AppInit DLL injection", "AppInit_DLLs 全局注入"], + ifeo: ["IFEO debuggers (can hijack any program)", "IFEO 调试器(可劫持任意程序启动)"], + bho: ["Browser helper objects", "浏览器加载项 BHO"], + }; + return ( +
+ + {rows.map((entry) => ( +
+ + {entry.signature === "microsoft" + ? t("Microsoft signed", "微软签名") + : entry.signature === "vendor" + ? t("Signed by", "已知厂商") + : entry.signature === "unsigned" + ? t("Not signed", "无数字签名") + : entry.signature === "invalid" + ? t("Signature invalid", "签名无效") + : t("Signature n/a", "无签名信息")} + +
+ {entry.name} + {shortPath(entry.command, 90)} + {entry.location} + {entry.warning ? ( + {entry.warning} + ) : null} +
+ void workspace.toggleAdvanced(entry.id, next)} + label={entry.name} + /> +
+ ))} +
+ ); + }) + : null} + {workspace.advanced && workspace.advanced.extras.length > 0 ? ( +
+ + {workspace.advanced.extras.map((entry) => ( +
+ {scopeLabel(entry.scope, t)} +
+ {entry.displayName || entry.name} + {shortPath(entry.command, 90)} + {entry.sourceLabel} +
+ void workspace.toggleStartup(entry.id, next)} + label={entry.name} + /> +
+ ))} +
+ ) : null} +
+ ) : null} + {workspace.tab === "popup" ? ( <>
diff --git a/src/pages/PrivacyPage.tsx b/src/pages/PrivacyPage.tsx new file mode 100644 index 0000000..b0ec80e --- /dev/null +++ b/src/pages/PrivacyPage.tsx @@ -0,0 +1,216 @@ +import { ClipboardList, EyeOff, FileClock, History, Lock, ShieldQuestion } from "lucide-react"; +import { useCallback, useEffect, useState } from "react"; +import { api } from "../lib/api"; +import { useI18n } from "../i18n"; +import { formatBytes, formatCount, messageFrom } from "../lib/format"; +import { + Button, + Checkbox, + EmptyState, + InlineError, + PageHeader, + useToast, +} from "../components/ui"; +import type { CleanupItem } from "../types"; + +function jobId(): string { + return crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`; +} + +const SPEC_ICONS: Record = { + "privacy-edge": History, + "privacy-chrome": History, + "privacy-recent": FileClock, + "privacy-clipboard": ClipboardList, + "privacy-activity": EyeOff, +}; + +const WARN_COPY: Record = { + "privacy-edge": ["影响「恢复上次会话」", "affects session restore"], + "privacy-chrome": ["影响「恢复上次会话」", "affects session restore"], + "privacy-clipboard": ["Win+V 历史会被清空", "clears the Win+V list"], + "privacy-activity": ["影响「恢复上次会话」", "affects session restore"], +}; + +interface SpecGroup { + ruleId: string; + label: string; + detail: string | null; + indexes: number[]; + bytes: number; + locked: string | null; +} + +export function PrivacyPage() { + const { t, lang } = useI18n(); + const { push } = useToast(); + const [items, setItems] = useState([]); + const [scanId, setScanId] = useState(null); + const [picked, setPicked] = useState>(new Set()); + const [scanning, setScanning] = useState(false); + const [cleaning, setCleaning] = useState(false); + const [error, setError] = useState(null); + const [loaded, setLoaded] = useState(false); + + const scan = useCallback(async () => { + setScanning(true); + setError(null); + const id = jobId(); + try { + const view = await api.privacyScan(id); + setItems(view.items); + setScanId(view.scanId); + setPicked(new Set()); + } catch (reason) { + setError(messageFrom(reason)); + } finally { + setScanning(false); + setLoaded(true); + } + }, []); + + useEffect(() => { + void scan(); + }, [scan]); + + const groups: SpecGroup[] = []; + items.forEach((item, index) => { + const last = groups[groups.length - 1]; + if (last && last.ruleId === item.ruleId) { + last.indexes.push(index); + last.bytes += item.onDisk; + if (item.lock && !last.locked) { + last.locked = item.note ?? item.lock; + } + } else { + groups.push({ + ruleId: item.ruleId, + label: item.label, + detail: item.note, + indexes: [index], + bytes: item.onDisk, + locked: item.lock ? item.note ?? item.lock : null, + }); + } + }); + + const toggleGroup = (group: SpecGroup) => { + if (group.locked) return; + setPicked((current) => { + const next = new Set(current); + const allOn = group.indexes.every((index) => next.has(index)); + for (const index of group.indexes) { + if (allOn) next.delete(index); + else next.add(index); + } + return next; + }); + }; + + const pickedBytes = [...picked].reduce((sum, index) => sum + (items[index]?.onDisk ?? 0), 0); + + const clean = async () => { + if (!scanId || picked.size === 0) return; + setCleaning(true); + try { + const outcome = await api.privacyDelete(jobId(), scanId, [...picked]); + push( + lang === "zh" + ? `已清除 ${outcome.removed} 项隐私痕迹(${formatBytes(outcome.freed)});这些删除不进回收站,明细见历史记录` + : `Cleared ${outcome.removed} traces (${formatBytes(outcome.freed)}); these deletions skip the Recycle Bin — see History`, + "success", + ); + await scan(); + } catch (reason) { + push(messageFrom(reason), "danger"); + } finally { + setCleaning(false); + } + }; + + return ( +
+ + {error ? setError(null)} /> : null} + +
+ {groups.map((group) => { + const Icon = SPEC_ICONS[group.ruleId] ?? ShieldQuestion; + const allOn = group.indexes.every((index) => picked.has(index)); + const warn = WARN_COPY[group.ruleId]; + return ( + + ); + })} + {loaded && groups.length === 0 && !scanning ? ( + } + title={t("Nothing to clean", "没有可清理的痕迹")} + description={t( + "No browser profiles or trace stores were found on this machine.", + "本机没有找到浏览器 profile 或痕迹存储。", + )} + /> + ) : null} +
+ +
+ + {picked.size > 0 + ? t( + `${formatCount(picked.size)} traces selected · ${formatBytes(pickedBytes)} · permanent`, + `已选 ${formatCount(picked.size)} 项 · ${formatBytes(pickedBytes)} · 永久删除`, + ) + : t( + "These deletions skip the Recycle Bin on purpose; History still lists every path.", + "这些删除有意绕过回收站;历史记录仍会逐条登记路径与大小。", + )} + + + +
+
+ ); +} diff --git a/src/styles.css b/src/styles.css index b67124a..81a5dd5 100644 --- a/src/styles.css +++ b/src/styles.css @@ -7697,3 +7697,322 @@ html.widget-mode body { max-height: 200px; overflow: auto; } + +/* ---- privacy cleaning (隐私清理) ---------------------------------------- */ + +.privacy-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(330px, 1fr)); + gap: 10px; + margin-top: 14px; +} + +.privacy-card { + display: flex; + align-items: flex-start; + gap: 10px; + padding: 13px 14px; + border: 1px solid var(--line); + border-radius: 14px; + background: var(--card, #fffdf8); + cursor: pointer; + text-align: left; +} + +.privacy-card.is-picked { + border-color: rgba(224, 95, 33, 0.45); + background: rgba(224, 95, 33, 0.04); +} + +.privacy-card.is-locked { + cursor: not-allowed; + opacity: 0.72; +} + +.privacy-icon { + flex: 0 0 auto; + display: inline-flex; + padding: 7px; + border-radius: 10px; + background: rgba(120, 120, 140, 0.09); + color: #6d7683; +} + +.privacy-copy { + flex: 1 1 auto; + min-width: 0; + display: flex; + flex-direction: column; + gap: 2px; +} + +.privacy-copy b { + color: #55493a; + font-size: var(--nex-text-2xs); +} + +.privacy-copy small { + color: #8b94a0; + font-size: var(--nex-text-3xs); +} + +.privacy-warn { + color: #b0763d !important; +} + +.privacy-lock { + flex: 0 0 auto; + display: inline-flex; + align-items: center; + gap: 4px; + padding: 2px 8px; + border: 1px solid #e2c793; + border-radius: 99px; + background: rgba(197, 145, 47, 0.08); + color: #9a6f1d; + font-size: var(--nex-text-3xs); + max-width: 150px; +} + +.privacy-size { + flex: 0 0 auto; + color: #55493a; + font-size: var(--nex-text-2xs); + font-weight: var(--nex-weight-semibold); + font-variant-numeric: tabular-nums; +} + +.privacy-footer { + position: sticky; + bottom: 0; + display: flex; + align-items: center; + gap: 12px; + margin-top: 14px; + padding: 11px 14px; + border: 1px solid var(--line); + border-radius: 14px; + background: var(--card, #fffdf8); + box-shadow: 0 -6px 18px rgba(80, 60, 30, 0.05); +} + +.privacy-footer-sum { + flex: 1 1 auto; + color: #8b94a0; + font-size: var(--nex-text-3xs); +} + +/* ---- optimisation tweaks (系统优化) ------------------------------------- */ + +.optimize-group { + margin-top: 14px; +} + +.optimize-group-head { + display: flex; + align-items: center; + gap: 10px; + padding: 0 2px 8px; +} + +.optimize-group-head h2 { + display: flex; + align-items: center; + gap: 6px; + margin: 0; + color: #55493a; + font-size: var(--nex-text-xs); +} + +.optimize-group-head .tip { + margin-left: auto; + color: #97826c; + font-size: var(--nex-text-3xs); +} + +.optimize-list { + margin: 0; + padding: 0; + list-style: none; + border: 1px solid var(--line); + border-radius: 14px; + background: var(--card, #fffdf8); + overflow: hidden; +} + +.optimize-row { + display: flex; + align-items: center; + gap: 12px; + padding: 12px 15px; + border-bottom: 1px solid #f2eade; +} + +.optimize-row:last-child { + border-bottom: 0; +} + +.optimize-copy { + flex: 1 1 auto; + min-width: 0; +} + +.optimize-copy b { + display: block; + color: #55493a; + font-size: var(--nex-text-2xs); +} + +.optimize-restart { + margin-left: 8px; + padding: 1px 7px; + border: 1px solid #ecd3bd; + border-radius: 99px; + color: #b8531c; + font-size: var(--nex-text-4xs, 10px); + font-weight: normal; +} + +.optimize-copy small { + display: block; + margin-top: 2px; + color: #8b94a0; + font-size: var(--nex-text-3xs); +} + +.optimize-path { + color: #b8b0a4 !important; + font-family: var(--nex-font-mono, monospace); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.optimize-risk { + flex: 0 0 auto; + padding: 2px 9px; + border-radius: 99px; + font-size: var(--nex-text-3xs); + white-space: nowrap; +} + +.optimize-risk.is-safe { + border: 1px solid #bfe0c4; + background: rgba(88, 170, 98, 0.08); + color: #4b8a55; +} + +.optimize-risk.is-notice { + border: 1px solid #ecd3bd; + background: rgba(224, 95, 33, 0.08); + color: #b8531c; +} + +.optimize-empty { + color: #97826c; + font-size: var(--nex-text-3xs); +} + +/* ---- advanced startup (进阶启动项) -------------------------------------- */ + +.perm-advanced .perm-adv-note { + margin: 0 0 12px; + padding: 9px 13px; + border: 1px solid #e9c9c0; + border-radius: 11px; + background: rgba(194, 84, 56, 0.05); + color: #a1543f; + font-size: var(--nex-text-3xs); +} + +.perm-adv-group { + margin-bottom: 16px; +} + +.perm-adv-row { + display: flex; + align-items: center; + gap: 11px; + padding: 10px 13px; + border: 1px solid var(--line); + border-radius: 12px; + background: var(--card, #fffdf8); + margin-bottom: 7px; +} + +.perm-adv-main { + flex: 1 1 auto; + min-width: 0; +} + +.perm-adv-main b { + display: block; + color: #55493a; + font-size: var(--nex-text-2xs); +} + +.perm-adv-main small { + display: block; + color: #8b94a0; + font-size: var(--nex-text-3xs); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.perm-adv-loc { + color: #b8b0a4 !important; + font-family: var(--nex-font-mono, monospace); +} + +.perm-adv-warn { + color: #b0763d !important; +} + +.perm-sig { + flex: 0 0 auto; + padding: 2px 9px; + border-radius: 99px; + font-size: var(--nex-text-3xs); + white-space: nowrap; +} + +.perm-sig.is-microsoft { + border: 1px solid #bcd2ea; + background: rgba(63, 107, 189, 0.08); + color: #3f6bbd; +} + +.perm-sig.is-vendor { + border: 1px solid #bfe0c4; + background: rgba(88, 170, 98, 0.08); + color: #4b8a55; +} + +.perm-sig.is-unsigned { + border: 1px solid #ecd3bd; + background: rgba(224, 95, 33, 0.08); + color: #b8531c; +} + +.perm-sig.is-invalid { + border: 1px solid #e6c2b8; + background: rgba(194, 84, 56, 0.09); + color: #b0563d; +} + +.perm-sig.is-unknown { + border: 1px solid #ddd6cc; + background: rgba(140, 140, 140, 0.07); + color: #8b94a0; +} + +.perm-scope { + flex: 0 0 auto; + padding: 2px 9px; + border: 1px solid #ddd6cc; + border-radius: 99px; + color: #8b94a0; + font-size: var(--nex-text-3xs); + white-space: nowrap; +} diff --git a/src/types.ts b/src/types.ts index cf0a428..efbc299 100644 --- a/src/types.ts +++ b/src/types.ts @@ -366,6 +366,26 @@ export interface MaintenanceResult { durationMs: number; } +// ---- optimisation tweaks (系统优化) -------------------------------------- + +export interface TweakState { + id: string; + titleZh: string; + titleEn: string; + detailZh: string; + detailEn: string; + risk: "safe" | "notice"; + hive: string; + key: string; + value: string; + kind: "dword" | "string" | "none-means-zero"; + on: string; + restartHint: boolean; + enabled: boolean; + unreadable: boolean; + recorded: boolean; +} + // ---- large files (大文件) ------------------------------------------------- export interface LargeFile { @@ -487,6 +507,27 @@ export interface PopupRuleItem { icon?: string | null; } +// ---- advanced startup (进阶启动项) --------------------------------------- + +export interface AdvancedEntry { + id: string; + kind: "winlogon" | "appinit" | "ifeo" | "bho"; + name: string; + command: string; + location: string; + scope: string; + enabled: boolean; + signature: "microsoft" | "vendor" | "unsigned" | "invalid" | "unknown"; + signer: string | null; + warning: string | null; +} + +export interface AdvancedScanResult { + entries: AdvancedEntry[]; + /** Auto-start services, in the ordinary startup shape (shared toggle). */ + extras: StartupItem[]; +} + export interface ManageView { watcherEnabled: boolean; intervalMs: number;